{"version":3,"mappings":"wpBAAA,WACA,+CACA,8CACA,OAEA,sEACAA,KAEA,yBACA,iBACA,wBAGA,4BACAC,6CACAD,IAGA,+CACA,cACA,WACA,qBACAE,yBACAC,mBACAD,mCACAC,kCACAD,wBACAC,4BACAD,qBAEAA,4BACAA,CACA,CACA,cACA,QAEA,OACAE,QAEA,aACA,eACA,CACA,+uBCxCAC,iBACA,kBAEA,QADAC,8BACAC,mBACAD,kBAEA,mBACA,CACA,ECRAE,MAIAC,6BAQA,eACA,uBACA,CAQA,eACA,mBACA,CAQA,eACA,mEACA,oEACA,CAQA,eACA,0CACA,CAQA,eACA,uCACA,CAQA,eACA,MACA,kDACAC,wBAEAA,4BAEAA,CACA,CAQA,eACA,yBACA,CAQA,eACA,yBACA,CAQA,eACA,mCACA,CAQA,eACA,kCACA,SAGA,+BACA,qCACA,CAQA,eACA,mCACA,CAQA,eACA,mCACA,CAQA,eACA,mCACA,CAQA,eACA,uCACA,CAQA,eACA,wBACA,CAQA,eACA,8CACA,CAQA,eACA,iDACA,CAiBA,cACA,iEACA,oCACA,0BACA,GAGA,mBACA,mBAEA,CAcA,iBAEA,6BAUA,GALA,qBAEAC,OAGAC,MAEA,+BACAC,0BAIA,gBACA,2CACAA,qBAIA,CAmBA,cACA,SACA,gBACAC,gBACAJ,gBACAI,MACAJ,cACAE,MACAF,eAEAA,MAEA,CAEA,uCACAK,mBAEA,QACA,CAUA,mBACA,0BACAC,wBACAC,aAEAA,MAEA,GACAA,CACA,CAQA,eACA,iCACAC,cAEAA,CACA,CAEA,QACA,WACA,iBACA,YACA,cACA,qBACA,YACA,YACA,YACA,iBACA,eACA,UACA,UACA,UACA,cACA,YACA,qBACA,wBACA,WACA,SACA,UACA,QACA,WACA,EC1VAC,MAEA,eACA,6BACA,qBACA,oBACA,qBACA,oBACA,qBACA,oBACA,wBAWA,MACA,SAGA,MACA,KACAC,eACAD,wBACAC,mBACA,CACA,SAEAD,2BACAE,yBAIAF,cACAG,SAEAD,MAGAF,yBACAA,aACAI,kBACAJ,iBACAI,qBAEAC,uBACA,GACA,GAEAJ,aACA,CAEA,MACA,qBACAK,SACAC,gBAGAA,kCACA,CAEA,QACA,ECnEAC,MAEA,cACA,gBACA,CAUAC,iCACA,2BACA,YACA,WACA,+BACA,wBACA,GACA,sBACA,EAOAA,+BACA,mBACA,sBAEA,EAUAA,iCACAD,qCACA,UACAd,IAEA,EACA,EAEA,UCnDAgB,MAEAC,iBACAD,2BACAE,2CACAC,OACA,YAEA,EACA,ECCAC,uBACA,kBACAC,IACAC,UAGAA,YACAA,aACAA,kBAEAA,oBACA,OAEA,qBACA,eAEA,6BACA,mBAEA,uBACA,2BACA,+BACA,iBAEA,mBACA,eACA,oEACA,CACA,EACAA,CACA,oDC5BA,iDAEA,gFCLA,wDAEA,2BACAC,SAGA,qDAEA,eAEAC,CACA,6DClBA,8CAKA,OACA,4BACA,SACAC,oCAEAC,eACAD,6CAGAC,iCAIAA,mCAIAC,QACAF,+CAMA,iBACA,oEACA,wCAGA,mBACA,kCAEA,CACA,eAIA,OACA,gDAEA,mBACA,CACA,gDC3CAG,eAIA,0FCHAC,iBACA,SACAC,8CACAA,sECEA,wCAEAD,mECVAE,kIAGA,gEACA,oCACA,EAeA,sBACA,yBAOAL;AAAA,mCAEAjB,sCACAD,2BAGA,yBACA,OAEAC,yEAMA,+DC7CA,gIAgBA,cACA,4CAKAuB,mCAMA,CACA,YACA,mDACA,YACA,8CACA,uCACA,oBACA,YACA,+CAEA,cACA,mCAWA,YACA,2BACA,gCACAC,eACA,CACA,yCAMA,CACA,kECzDA,eAGA,uCACA,kDACA,EAEAC,0BAEAC,2HCLA,uDAEA,aACAC,YACAC,gCAGAC,4CAIAA,kDAKAZ,iBACA,yBAGA,yBAGA,wGAGAU,uCAGA,4FAIAG,wCAOA,qEACAC,6BACAD,oCAGA,gBACA,oDAIA,EAEAE,cACAlB,QAEA,cACAmB,qBAyEA,GAjEA,gBAEAH,cAGAA,0HAcA,aACA,EAIAA,0BAKAG,kDAIA,EAGAH,qBAGAG,qCAIA,EAGAH,uBACA,0GAEAD,wBACAK,6BAGAA,EACAL,EACAM,2DAKA,EAKAlB,0BAEA,kDACAmB,yBACA,kCAQA,wBACAnB,0BACA,+CAEA,mCAKA,6EASAW,gBACAE,+BAIA,8IAMAA,qFAMAO,wDAKAP,iBAEA,EAEAD,0CACAA,WACAA,wEASAC,SACA,uEC5MAQ,qDAEA,EAEA,gBACA,sDACA5B,qBAIA,mBAEA,kCAGA,8FAOA,kBACA,iBACA,6BAEAO,mBAEA,+DASA,OAEA,4HAYA,OAHAsB,cACAA,oBAEAtB,iBACAA,oBACAA,eACAA,eACAA,aACAA,cAIAA,uBACAuB,SAEAvB,wBACAwB,uDACAD,cAEAvB,0DACAwB,wBACAC,OAGA,GAEA,0JAMA,iCACA,IACA,mCAGA,gEASA,4GAcA,iDAIA,SACA,oDAIA,EAEA,oEAEA,GAEAzB,6CACA0B,uBACA,GAEAC,QCnIA,UACAC,2BAWA,eAEA,gCACAL,eACA,GAEAA,CACA,uCCnBAM,8CCAA,UACAC,MACAC,QACAC,QACAxB,QAKA,eAKA,GAJAI,eACAA,iCAGAA,2BACA,wBAEA,CAQA,mBACAqB,MAGArB,wBAGAA,eACAA,EACAA,OACAA,UACAA,kBACA,EAGAA,mBACAA,qBACAA,wBACAA,SACA,EAEAsB,WACA,sDACA,YACA,mBACA,CACA,EAEA,4BAEA,6BACA,aAGApC,eACAc,EACAd,OACAA,UACAc,mBACA,EAEAd,CACA,cACA,eACAmC,MAGAE,gBACAA,wBACAvB,EACAuB,gBACAA,mBACAvB,mBACA,IAIA,iBACA,EACA,ECpFAwB,MAUAC,iBAEAC,QACA,SAEA,gBACA,gDACAF,cACAA,oBACAA,eACAA,cACAG,UAEAA,CACA,CAGA,cACA,yBAEA,yBACA,0BAFA,oBAIA,CAGA,cACA,yBACA,qBAEA,CAGA,cACA,yBAEA,yBACA,0BAFA,sBAIA,CAGA,cACA,UACA,oBACA,UACA,qBAEA,CAEA,OACA,MACA,SACA,OACA,UACA,mBACA,oBACA,mBACA,UACA,iBACA,kBACA,UACA,eACA,iBACA,iBACA,mBACA,qBACA,aACA,mBACA,gBACA,YACA,YACA,aACA,cACA,aACA,mBACA,gBACA,EAEA,oEACA,cACAC,OACAJ,kCACA,GAEAxB,CACA,uCClGA6B,0BCEA,oBAEAC,MAGA,iFACAA,kBACA,yCACA,CACA,GAEA,UASAC,gCACA,gBACA,mEACA,CAGA,uBACA,UACA,0DAGA,mBACAC,SAEA,aACAC,EACAC,EACA,0EACA,CACA,GAGAC,aACA,CACA,EASA,mBACA,sBACA,iDAIA,QAFAC,iBACAhF,WACAA,SACA,WACA+E,OACA,MACA,WACA5E,uBACA,UACA,+CAEA,QACA,CACA,UACA,gCAEA,CACA,CAEA,QACA,iBACA,aACA,EC/EA8E,MACAC,MACA7D,MACA8D,MACAC,MACAL,MAEAJ,iBAMA,eACA,gBACA,mBACA,eACA,eACA,CACA,CAOAU,mCAUA,GAPA,oBACAzC,QACAA,SAEAA,QAGA,OACA,oDAGAA,sBAGAA,SACAA,gCACA,qBACAA,4CAEAA,eAGA,qBAEAM,YACA6B,oBACA,8CACA,8CACA,+CACA,MAIA,SACAO,KACA,8CACA,kDAIAA,mBAEAC,kCACA,GAEA,SACA,+CACAC,8BACA,GAEA,MAEA,OACA,kBAMA,IAJA,mCACAC,cAEAC,qBACAD,UACAC,8BAGA,QACA,CAIA,QADAC,IACAJ,WACA,gBACAK,YACA,IACAD,MACA,UACAC,KACA,KACA,CACA,CAEA,IACAF,OACA,UACA,wBACA,CAEA,eACAA,8BAGA,QACA,EAEAL,gCACA,UACA,oDAEA,6BACAH,uDACA,EAGAlD,yDAEA6D,8BACA,8BACA,SACA,MACA,iBACA,GACA,CACA,GAEA7D,8CAEA6D,gCACA,8BACA,SACA,MACA,MACA,GACA,CACA,GAEA,4EC/IA,wBACA,kGAOA,GAEA,yCAIA,kFAQAC,kBACA,iEAOAA,kBAEA,WAEA,2BACAA,gBACA,GAGA,EAEAC,cACAD,6BAMAE,YACA,GAMA,+CACA,eACA,iBAEA,oCAOA,gBACAC,eACA,OAGA,wCAGA,mBAEA,sCAOA,uDAIAC,oCAGA,EAMAC,iDAIA,GACA,uBAGA,CACA,EAEAC,iDChGAC,eACA,yCAEA,6DCfA,sBACA,8CCTA,UACAC,MACAjB,MACAkB,MACAC,QAQA,eACA,gBACAC,6BAGA,mCAGAC,eAGAD,qBACA,kBACA,EAEAA,CACA,CAGA,cAGAE,YAGAA,eACAA,oBACAA,iBACAA,wBAGAA,mBACA,qBACA,EACAA,eAGAA,qBAEAC,cAGAC,mCCxDAC,qECIA,uFACA,6CAEA,SACAC,iBACAC,YAIA,GAHA,oBAEA,uDACA,+DAUA,SACA5G,OACA,oBAGA,GAFA,2DAEA,iGAEA,sCAGA,GAFA6G,wBAEA,0DAEA,uDACA,2CACA,0CACA,CAEA,QACA,ECvCAC,6BACAC,oBAMA,OAHA,uBACA,2BACA,4BACA,kCAEAA,IACA,ECRAC,qDACAC,yBACAC,6BACAC,uBAEAC,eACA,WACA,yCACA,0BAyBA,QAvBAzH,uBAEA0H,EACAC,aACA,sBACA,cACA,KACA3H,4BACA,EACA,qBACAI,EAEA,IACA,KACA,gBACAwH,EACA5H,4BACA,CAEA,EAEA6H,gCACAC,KACA,YACAA,cAKA,GAFAJ,oGAEAK,aACA,mBACAC,wBACAN,kBACAM,gBACA,CAEA,QACA,ECjDAC,MAEAC,+BCFAC,MAEAC,0DCFAC,GAEAC,eACAC,YACAC,aAGAC,eACA,IACA,wDACA,QACA,EAEAC,mCACA,MACA,IACAA,SACA,OACAA,OACA,CAGA,kBACA,YACA,EACAC,MACA,WACA,IAEA,wBACAC,EACA,OACA,IAEA,iCACA,OACA,SACA,CACA,CACA,IACAA,GAEAC,QAEAC,0DAEAC,MAEAC,2CAEAC,IACA,+DACA,gBACA,sDACA,2DACA,sCACA,qBACA,sBACA,8BACA,8BACA,0CACA,uCACA,4DACA,+DACA,oBACA,6CACA,cACA,wBACA,0CACA,wBACA,0CACA,gBACA,cACA,wBACA,yDACA,yDACA,iFACA,gBACA,yBACA,gDACA,mDACA,mDACA,sBACA,gBACA,0DACA,uCACA,8BACA,iFACA,cACA,kBACA,kBACA,0BACA,sBACA,0CACA,oCACA,0BACA,kCACA,0CACA,kBACA,8BACA,iFACA,wEACA,kBACA,4DACA,wBACA,mBACA,sBACA,kBACA,iBACA,mDACA,wEACA,sDACA,sDACA,sBACA,0CACA,0CACA,yCACA,EAEA,IACA,UACA,UAEA,iBACAA,0BACA,CAEA,qBACA,MACA,yBACAC,qCACAzH,0BACAyH,gCACAzH,+BACAyH,sCACAzH,wBACA,oCACAlB,IACA2I,cAEA,yCACA,4BACAC,IACAD,kBAEA,CAEA,eAEAA,CACA,EAEAE,IACA,qDACA,yCACA,uDACA,uDACA,iDACA,qDACA,yDACA,0DACA,+EACA,6CACA,+CACA,uCACA,yCACA,iDACA,uDACA,uDACA,+CACA,gDACA,qEACA,iDACA,mDACA,mDACA,+BACA,uCACA,qCACA,2CACA,2CACA,wDACA,sDACA,6CACA,qDACA,kCACA,wCACA,0CACA,mDACA,2DACA,2CACA,qCACA,iEACA,2CACA,2CACA,qDACA,mDACA,iDACA,mDACA,iEACA,qDACA,qDACA,+CACA,6CACA,4CACA,EAEAC,MACAC,MACAC,iDACAC,kDACAC,mDACAC,iDACAC,gDAGAC,wGACAC,cACAC,eACA,gBACAC,WACA,oBACA,+DACA,oBACA,+DAEA,SACA,iCACA3J,gCACA,GACAA,CACA,EAGA4J,iBACA,QACAC,EAMA,GALAX,WACAW,QACAC,gBAGAZ,UACA,YAIA,GAHAJ,SACAA,SAEA,iBACA,oFAGA,OACA,QACA,OACA,OACA,CACA,CAEA,+CACA,EAEAiB,iBACA,oCACA,0DAEA,2CACA,0DAGA,8BACA,mGAEA,YACAC,qBAEAC,kBACAC,SACApB,UACAqB,KAEAN,UACAA,IACAG,OACAZ,mBAGA,kCACA,WACAgB,YACAT,WACA,IAEAS,2BACAT,4BAEAS,MAEA,qEASA,IAPAC,yBACAF,MAGAH,SACAE,YAEAhB,SACAJ,gBACAA,SACA,cACA,MACA,oFAEA,MACA,CACA,sBACA,cACAwB,MASAA,yCACAxB,QAEAA,MAEA,MACAwB,UACAxB,OAGAwB,QACAzB,QAEA,CACA,CACA,QACA,6CClVA0B,kCACAC,iCACAC,qHAIAC,kBAEA,KACA,IACAC,iCAOAhE,6CAEA,6BAEAiE,gBAEAD,EACAE,EACA,qDAEA,UAIA,EAEA,wCAEA,EAEAF,EACAA,uDCzCA,UAEAG,cAEAC,sCAEAC,iBACA,gBACA,oDACAF,MAEAb,CACA,ECdA,+HCAA,6CACAgB,kGACAC,iDACAC,6BACAC,yCACAC,kGACAC,iDACAC,6BACAC,iDACAC,iCACAC,iDACAC,iCACAC,iDACAC,mCACAC,6BACAC,6BACAC,+BACAC,0BACAC,0BACAC,4BACAC,gCACAC,gCACAC,yBACAC,0BACAC,wBACAC,yBACAC,cACAC,2DACAC,gCACAC,8FACAC,+DAEAC,qGACA,mBACA,KACAC,yCAEAC,+EACA,+BACA,YACA,kBACA,EACA,MAGA,iBACA,GACAC,SACAA,UACAA,OACAA,kBACAZ,eAEA,SAEA,yCACA,uBACA,wBACA,UACA,gBACAa,wBACA,6EACA,CACA,CACA,yBACA,CAEA,UACAC,aACAC,yCAGA,YAEA,wEACA,wEAEA,GACAC,6DACAC,6CACAA,0BAGA,8GAEA,+CACA,qCACA,qGAGA,GACAD,gBACAC,iBACAA,gBACA,gDAEA,gFAEA,kEACA,yFAEA,yBAEA,gBACA,kBAEA,YACA,aAEA,uBACA,wBAGA,sBACA,eAEA,uBACA,SACA,wBAEA,gBACA,kBACA,CACA,uBACA,oBACA,kBACA,CAEA,mCAEA,GADA,oBACAC,8BACA,kCAGA,cAEA,gBACAC,aACAC,WACA,mBAGA,kBAKA,GAJAC,IACAF,aACAA,WAEAG,GACA,OACA,aACA,EACA,4BACAC,2BAEAC,YACA,CACA,mBACA,CAEA,iCACA,YACAjJ,UACA,0FACA,CACA,UACA,qEACA,sCACA,CACA,UAGA,QAFAkJ,kCACAC,mBACAnO,mBACAkO,mDAEA,cACA9N,8CACA8N,wCACAA,CACA,CACA,UACA,2BACA,cACA,iBACA,gBAEA,yBACA,CACA,UACA,cACA,qEACA,0EAEAjN,+BACA,yCACA,CACA,0BACA,oCACA,yBACA,8CACA,kBAEA,CACA,UACA,SACA,WACAqK,wBACA8C,+BACA,GAEAC,wBACA,CACA,UACA,SACA,WACA3C,sBACA4C,cACA,GAEAD,wBACA,CACA,SACA,qBAEA,SACA,qBAEA,SACA,qBAEA,SACA,wBAEA,SACA,yBAEA,SACA,sBAEA,SACA,wBAEA,mBACA,cACAE,0EACAC,0CACAC,mEACAC,sFACAC,6DACA,2BACAC,EACAD,kBAEAA,2BACA,CACA,gBACA,EAEA,mBACA,2CACA,YACA,CAEA,eACA,uCACA,CAEA,sFACA,qFACA,uFACA,sFACA,uFACA,uFACA,wFAGA,eACA,MACA,kDAEA,sBACA,SAEA,+BACA,SAEA,IACA,kBACA,EACA,QACA,QACA,CAEA,eACA,+BACA,SAEA,IACA,kBACA,EACA,QACA,QACA,CAEA,sEACA,iBACA,mBACA,CAEA,eACA,iBACA,CAEA,eACA,wBACA,iDACA,cACA,IACA,CAEA,iBACA,iCACA,+BACA,qBAEA,QACA,CAEA,eACA,+BACA,SAEA,IACAtD,WACA,IACAI,UACA,OACA,QACA,CACA,uBACA,QACA,QACA,CAEA,eACA,+BACA,SAEA,IACAG,cACA,IACAE,aACA,OACA,QACA,CACA,2BACA,QACA,QACA,CAEA,eACA,+BACA,SAEA,IACA,kBACA,EACA,QACA,QACA,CAEA,eACA,+BACA,SAEA,IACAL,WACA,IACAJ,UACA,OACA,QACA,CACA,uBACA,QACA,QACA,CAEA,eACA,+BACA,SAEA,IACAS,cACA,IACAF,aACA,OACA,QACA,CACA,2BACA,QACA,QACA,CAEA,eACA,gCACA,iDACA,GAEA,8DACA,CAEA,iBACA,+BACA,iCACAiD,0CACA,6CACA,CAEA,8DACA,uBACA,CAEA,eACA,sBACAC,GACA,MACA,MACA,OACA,OACA,MACA,KACA,gBACA,2CACA,CAEA,eACA,qBACA,CAEA,eACA,iBACA,CAEA,qBACA,gCACA,2BACA,CAEA,eACA,2BACA;AAAA,MACA,SAGA,QACA,CAEA,iBACA,MACA,kBACAC,cACA,sCACAA,qCAEA,aAEA,OACA,OACA,0BACA,CACA,CAEA,iBACA,yBACA;AAAA,gBACA;AAAA,QACA,CAEA,iBACA,YACAC,KACA,MACAA,kBACA,2BACAA,yBAEA,CACA,qCACAC,EACA,OACAA,KACA,2BACAA,gBAEA,CAEA,eACA,UACAC,sCACAjC,gCAGAR,oBACAuC,8BAEAA,0BAGA,yBACA,2BACA7B,iBACA6B,uCAIA,QACA,CCjgBA,UACAG,MACAC,MAEAC,qBACAC,sBACAC,kBAEAC,kCACAC,kCACAC,kCACAC,8BACAC,8BACAC,8BAUAC,iBACA,oCACA,aACA,qBACAC,cACAC,SACAD,CAGA,EAEAE,iBACA,cACA,iBACA,EACAC,mBACA,cACAxQ,EACAA,UAGAyQ,QACA,MACA,YACA,OACA,CAEA,EACAC,iBACA,eACA,gBAGA,MACAC,EACAC,EACAC,GACA,mBACA,aACA,oDAEA,EACA,gBACA,sDACA,KACA,uBAEAhB,IACA,KACA,uBAGAe,EACA,cAGA,EACA,gBACA,sDACA,KACA,uBAEAf,IACA,KACA,uBAGAe,EACA,eAGA,QACA,EACA,kBACAhB,mDACAkB,IACAA,UAEAf,WACAF,IACAc,IACAA,UAEAT,YAEAU,IAMAA,sBAEAJ,UAEA,CACA,EACA,QACA,ECzHAO,4BACAC,UAEAC,IACA,kBACA,iBACA,EAEAC,IACA,mBACA,YACA,oBACA,wBACA,EACA,oBACA,gBACA,CACA,EACA,mBACA,kBACA,ECpBAC,MAEAC,mCACAC,iBAEAC,cAEA,QADAC,KACAjR,cACAiR,yDAGA,QACA,IAEAC,eACA,kBACA,cACA9Q,gBAEA,UAGA,QAFA+Q,KAEAC,mBACA,iBACAD,aAIAE,eACA,CACA,CACA,EAEAC,iBAEA,QADAlR,2CACAJ,mBACA,kBACAI,WAIA,QACA,EAEAmR,qBAEA,MACA,SAGA,uBACA,SACAzJ,kBACAA,uBACA0J,wEACA1J,aAGA,aAGA,QACA,CAEA,0BACA,oBAGA,QAKA,OAJAiJ,gBACAU,WAGAV,cACAxM,wBACA,iBACA,WACAmN,6CACA5J,cAEAA,SAEA,MACAA,MAEA,GACAA,GAGA,oCACA,WAEA,oBACA6J,iBAEAA,OAEAA,CACA,IACA,EAEAC,iBACA,2CACA,iBACAD,CACA,IACA,EAEAE,mBACA,2BACA,oBAEA,4CAGA,IACA,4BACA,OACA,QACA,CACA,EAEAC,uBAGA,gBACA,SAGA,QAOA,GANA,mBACAC,oCACA,qBACAA,aAGAC,iBACA,uDACA,4CACA,GAIA,QADAC,KACA,oBACA,sBAEA,GACAC,QACAA,QACAA,QACAA,SACAA,cACAA,cACAA,eACAC,iCACA,CACAF,eACA,QACA,CAEA,UACAA,UACA,QACA,CAEA,WACAA,gCACA,QACA,CAEA,sBACAA,iDACA,QACA,CAEA,KACAC,4CAEAD,iBACAjB,iBACAA,gBACAA,YACA,CAEA,QACA,EAEAoB,eAIA,QAHAC,yBACAC,KAEAtS,mBAKA,QAJAqR,OACAjR,gBAEA4E,iBACAoM,oBACA,WACAtQ,OACA,kDACAuR,uBACAC,UAEA,CAGA,aAEArJ,CACA,EAEAsJ,eACA,4DACA,EAEAC,eACA,6BACA,GAGA,oEACA,EAEAC,iBACA,oBACA,EAEAC,iBACA,UAEA,QADAC,KACA3S,oBACA2S,gBAEA,QACA,CACA,WACA,EAEAC,IACA,iBACA,UACA,WACA,WACA,UACA,UACA,YACA,YACA,YACA,QACA,ECzPAC,MACAC,MACAC,MACAC,mCAEAC,IACA,qBACA,aACA,EACA,cACA,sBACA,kBACA,EACA,mBACA,QACA,CACA,EAEAC,iBACAC,wBACAC,iBACAD,uBACA,EAEAE,8BAEAC,cACAC,IACA,kBACA,aACA,gBACA,mBACA,cACA,UACA,kBACA,oBACA,UACA,4BAEA,WACA,0BACA,iBACA,EACA,aACA,qBACA,EAEAC,eACA,2BACA,oBACA,qBACA,oBACA,kBACA,EAEAC,MAEAC,cACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAlC,EACAmC,EACAC,EACAvC,EACAwC,EACA,CAMA,QALApU,IAEAqU,IACAC,IACAC,MACAF,4BAEA,eAEA,GADAC,KACA,cACA,SACA,4CAEAC,IAEA,CACA,uBACAD,IAEA,CAeA,GAbA,qBACAtU,SACAA,kBACAA,OACAyT,qBACAzT,4BACA,yBACAiU,KAEApL,CACA,IAGA7I,UACA,KACA,yCAGAA,IACA,CAEA,0BACA,MACA,oCACA,+CACA,CACA,6BACA,CAEA,SAEA,gBACA,SAGA,MACA,sBAEAmU,OACAnU,oBAEAwU,wDACA1B,MACA0B,QACA,CACA,qBACAA,eACA,CAIA,QAFAC,kCAEAzD,oBACA,WACAnI,sDAEA,kBAIA,aACA,8BACA4L,sBAEAL,WACA,WACAM,YACA1B,OACAnK,EACA8L,EACAlB,EACAC,EACAC,EACAC,EACAH,6BACAK,EACAC,EACAC,EACAC,EACAlC,EACAmC,EACAC,EACAvC,EACA8C,CACA,GACA,CAEA,QACA,EAEAE,eACA,MACA,UAGA,wEACA,qDAGA,4BACA,uEACA,yFAGA,iBACA,wBACA,oCACA,uDAEA7C,UACA,CACA,uBAEA+B,YACA,oDACAA,YAGA,CACA,qFACA,4DACA,UACA,yFACA,0DACA,qDACA,0DACA,6FACA,SACA,SACA,YACA,kFACA,iEACA,2CACA,oGACA,CACA,EAEAe,iBACA,QACAzD,QAEAoD,EACAV,EAEA,6BACAA,WACA9T,WACA8S,eACAgB,WACAU,KAGA,SAEA,gCACA,SAGA,MACAlH,uBACAwH,gBACAxH,iBACAwH,+BAEAA,YAGA,YACA,+DACA,qEAEA,uCAEAN,IACAA,kBAGApD,QACAoD,eAIA,QADAJ,OACAxU,oBACA,WAEAwR,0BAGA4B,QACAhT,KACAW,EACA8S,EACAC,EACAtC,qBACAA,YACAA,wBACAA,SACAA,OACAA,YACAA,gBACAA,SACAA,YACAA,mBACAA,UACAgD,CACA,EACA,CAEA,0BACAZ,+BAEA,2BACApC,yBAEAoC,0BAGAA,sBAIAuB,iBACA,EC7TAnT,MAEAoT,mCACAC,iBAEA3R,IACA,aACA,mBACA,eACA,cACA,gBACA,mBACA,SACA,kBACA,cACA,QACA,qBACA,4BACA,mBACA,eACA,gBACA,qBACA,EAEA4R,eACA,2CACA,0CACA,EACA,EAEAC,iBACA,yDACAzU,aAGAA,CACA,EAOA0U,yBAGAC,oBAEAC,iBACA,SACAC,4CACAC,iDACA3U,yBACA4U,KACA,EAEA7D,YACA,qBACA,uBACA/Q,4BACAA,UACA+Q,UACA/Q,YACA+Q,gBAEA6D,IACA,YAKA,uBACA,SAGA,YAEAC,kBACAC,4BAEAhV,IACAgV,QACAhV,kCACAD,iCAEAC,6CACAD,cACAyU,mBACA,YACA,wCACA,CACA,GAGAzU,kDACAA,SAGA0J,sBACA1J,eAGAsU,aACAhV,wBAEAA,OAIA,QACA,EAEA4V,qBAGA,QAFAC,cAEAjW,uBACA,MACAkW,OAEA,2BACA9V,mBACA,CACAA,wCACA,oEACA8F,iBACA,uBACA9F,QAEA,WACA8V,OACA,eACAhQ,MACAsL,gCAEApR,KACAA,QACA+V,kBACA/V,OAEA,CAEA6V,GACA,CAEA,QACA,EAEAG,qBACA,OAKA,qDAIAC,iBACAC,kBAIAC,uBACAC,yBAIAxR,KACA,MAEA,iDACA,mBACA,OAIAA,SACA,CAKA,QADAhF,IACAwR,6CAEA,GADAxR,KACA,6DACA,mBACA,OAGAgF,YACA,CAIA,UACAA,iCAGAgR,YACA,EAEAS,eACA,MACA,UAGA,sEACA,qDAGA,uEACA,yFAEA,gDAEA,OACA,4DACA,yFACA,yEACA,oEACA,UACA,yFACA,iDACA,0DACA,0FAEA,+DACA,2CACA,6HACA,oFACA,+BACA,6EACA,oGACA,CACA,EAEAC,iBACA,YAEA,kCACA,6CASA,QANAC,+BACAvW,wCAIA4E,iBACAhF,oBACA,WACA4W,kCACAxW,iBACA,CAEA,0BACAA,EAGA4B,aACA,ECpQA6U,MACAC,MACAC,MAEAC,IACA,WACA,SACA,YACA,ECLA,cAGArQ,wCAEA,SAEA,sCACA,8CAOA,gCACAlF,yCAGAmB,wBACA,IACA,EAGAA,EACA,EAKA+D,kCACA/E,IAEAA,YAEA+E,mBAiBA,kBACA,CAEA,wBC3DA,6JAYA,mEACAsQ,oBAGAA,0DAEAA,qBAIA,SACAC,gIAGA,UACA,4DAIAD,sBACAA,wCACAA,uBACAA,WACA,6BAOAA,6IAOAA,kCACA,uCAQA,UACA,YACA,kCACA,UACA,uIAGA,oEAEA,EAMAA,SACAA,0DACAA,kCACAA,yEACAA,6BACAA,eACAA,wBACAA,qCAQAA,6BAQAA,yBAQAA,wBAKAA,qBASAA,mBASAA,2BAUAA,uBAMAA,8CACAA,iCACAA,8BACA,EAeAA,8BAMAA,wBAUAA,wBAMAA,yBASAA,wDAGA,wIAEA,mDAEA,2BACA,kCAEA,2CAKA,iBAIA,WAOA,mGASAA,yBAaA,gBAKA,GAJA,wBACA,0BAGA,qBACA,yIAaA,sEAIA,0BAIA,gBAEA,wBACA,eACAE,sDAmBA,gBACA,sCAKA,wBACA,sDAKA,oDACA,eACAC,sDAiBA,gBACA,uFASA,+BACAC,4BAEA,qDACA,aACA,8CAcA,CACA,6CAwBA,GADA,kDACA,oBACA,+JAqBA,6BAEAlH,2IAoBA,QAHAA,gBACAjK,OAEAlG,yDAIAkG,4BAGA,4HAoBA,4BAEA,QADAiK,oBACAnQ,uBACAsX,gCAYA,uBACA,oBACA,wDAGA,iBACA,IAQA,iBACA,6FAgBA,6BASA,uBACA,uEAKA,sDACA,uEAWA,8CAIA,mBAYA,wBACA,iCAUA,4BACAC,6CACA,4DAWAA,uCACA,+BAGAD,QAOA,uBACA,kCAYA,kBACA,0BACA,wCAQA,mBACA,WASA,qCAEA,iDAWA,gBACA,eAEA,cAKA,gBACAE,aACAC,WACAC,cACAC,oBAcA,kCAEAC,MAEAA,MAEA,UACA,iCAEA,gBAEA,oBAUA,gDAOA,OAJAA,MAEAC,MAEAC,GACA,gBACA,gBACA,gBAEA,oBAYA,iDAEA,gCAcA,2BACA,4CAUA,6BACA,YAUA,6BACA,2EAcA9W,2BACA,0CAWA,+DAGA+W,cACAC,cACA,cAGA,GAgBA,gEAYA,qHAUA,yBACA,mJAaAC,mGAGAC,mBACA,OACA,4DAEA,oEAwBAC,sEAEAC,cACA,mEAEA,6EAIAlS,gBAEAmS,4JAUA,gCACAC,WACAL,UACAM,EACAC,EACA,gCACAD,mBACAC,iCAGA,EACA,mFAGA,uBAIAA,iCAGA,wCAGA,8CAeA,YACAC,kBACAA,iBACA,EAEA,yDAGA,GASA,6CAEA,2BACAC,mCAGA,gFAGAC,MACAC,4EAGAC,MAEA,oCAKA,GAUA,0DAEAC,kCACAC,4EAcA,sBACA,yCAUA,iDAEAC,gBAIA,WAFAC,gCAEAC,MACA,6BAGA,6BAGA,SACA,eAEA,2BAGA,8BAGA,SACA,iEAwBA,6FAGAjC,+BASA,oCAEA,sBACA,QACA,KACA,OACA,EACA,UACA,2FAEA,MACA,oGAEA,MACA,WACAkC,mDACA,gBAWA,+DAMAC,aACAhZ,oGAoBA,+CAOAkX,2CAEA,EAEA+B,WAEAA,mDAEA/B,8CAEA,gDAUA+B,wDAOAA,0CAIAA,SAUA,mEAEAC,mCACAA,iCACAA,4BACAA,iBACArC,gDAMAoC,0DAIA,oCAcAlJ,qBAIAoJ,wBAGA,sDASAjC,QACA,mDAOA,OAEA,wFAKA,EACA,6KAaA,2CAGAkC,cACA,GACAlC,OACA,IAWA,8BACAmC,qBAGA,SACAnC,qBAMAoC,kBAGApC,QACA,+BAIAqC,wCAEAC,UAEA,IAGAA,WAGA,mEAeA,kCAGAC,4CAKA,YACA,YACA,GAGA,eACA,qCAIA,eACAlG,kFAeA,+BACAmG,WACAC,4FAuBA,iEAEA,uBACAC,kBACAA,4MAsCA,OACAtZ,oBACAA,oBACAA,oBACAA,6EAGA,GAUA,wBACA,yCAEAuZ,4DAGA,OACA,4BAGA,kBAEA,gBACA,eACA,GAaA,6BACA,YACA,0BAEA,uEAGA,sBAoBA,iCACA,qCACAC,iCACAC,GACA3I,aACA,EACA,EACAA,aACA,EACA,GACA4I,mCACAC,0BACA,qBAEAF,EACA,kCAGA3I,cAEA2I,EACA,qCAwBA,0EAEAC,mCACA,iBACAE,gEAGA9I,sCACA8I,0CAWA,iCACAxS,WACAA,WACAA,UACAA,UACAA,WACAA,WACAA,aAUA,gCACA,OACA,gBACA,gBACA,cACA,cACA,cACA,YACA,cACA,cACA,SACA,mCAeAyS,MACAzL,aAMA0L,cAQA,iDAEAC,gBAGA,0BAEAC,OACAA,QAHA1a,KAGA,kBAeA,4FAIA,qBACA2a,iDAKAC,WACAC,YAIAC,iCACAC,iCACA,gCAIA,GAeA,2DAKA9D,sBACA,4BAHAA,sBAgBA,qEAGA,sDAIA,kCAgBA,iFAiBA,mFAWA,0DAEA,uEAgBA,wEAEA+D,4FAaA,mCACA/D,8BACAtD,EACAsD,qDACA,GASA,iEAEAgE,yCACAtH,WACAA,6DAGAA,gBACAA,gBACAA,+GAsBA+E,6CAgBA,oCAEAwC,wCACA,OACA,UACA,UACA,GAsBA,4EAQAjE,8BACAkE,EACAlE,yGAIA,8IAkBA,gCAEAmE,qBACAA,+BACAA,yBACAA,6BACAA,6BACAA,2BACAA,+CACAA,qBACAC,IACAD,yBACAA,2DAaA,4BAMA,QAJAE,4BACAC;AAAA,GACAC,eAEAxb,oBACA,yBAGA,SAGA,iDAIA,+BACA,uDAIA,eAEA,uBAOAob,mBAeA,4DAOA;GAFAI,cAEAxb,mBAEA,kCAGAsb,MACAA,6GAeA,MAIA,WACA,2BACAG,wCAWAC,cAGA,wGAMAC,gBACAC,gBACAC,qBACAC,qBACAC,qBACAC,6CAMA,EAOA,0BACA,wDAGAC,oCAKA,qBACAC,yCAEAC,oBAGA,SACA,8DAMA,oDAKAC,iBACAC,4CAEAC,sDAGAA,sBAGAA,SASA,QALAC,8CAEAC,oDACAC,SAEAzc,gBACAG,gJAeA,YACAuc,oBAoBA,kCAEA,+CAEAzF,yBACA,+BAIA,sDAGA0F,UACAjc,oBAEAya,eACAza,6BAGA,qBAOA,GANAV,MACAmb,eACAza,8BAIAkc,YACA,cACA,SAEAnE,iBAEAoE,UAEA,sBAGA,UAGAC,SACAC,6BAEAF,WAEAG,6BAEAH,oBAIA/N,iCAEA2J,QACAwE,OACAnO,yDAGA0L,kHAUA,qBACA,uBAGA,qBACA,qBAEA,EACA,gFAsBA,QATAzC,OACAC,OACAkF,OACAC,OACAC,OACAC,OACAC,8BAGAtd,iGASA,CASA,cAIA,uBAIAud,0CAOA,kCACA,QACAC,SACAA,QACAA,QAEA,QACA1O,OACA0L,OACA,MACA,QACAgD,QAEA,QACAA,SACAA,OACA1O,OACA,MACA,QACA0O,QAEA,QACAA,SACAhD,OACAgD,OACAA,OACA,MACA,QACAA,SACAA,QACAA,QAEA,QACA1O,OACA0L,OACA+C,OACAE,OACA,MACA,QACAD,SACAA,QACAA,QACAA,QACAA,QACAA,QACAA,QAEA,QACAE,OACAC,OACA7O,OACA0L,OACA,MACA,QACAgD,SACAA,QACAA,QACAA,QACAA,QAEA,QAEAI,SAEAF,QACAC,mBAQA7O,OACA0L,OACAgD,iDAKAA,OACAA,OAGAE,OACAC,OACA,MACA,QACAH,SACAA,QACAA,QACAA,QACAA,QAEA,QACAE,OACAC,OACA7O,OACA0L,OACA,MACA,QACAgD,SACAA,QACAA,QAEA,QACAI,SAEAF,QACAC,mBAQAH,SACA1O,OACA0L,OACAgD,OACAA,OACAA,OACAA,OACA,MACA,QACAA,SACAA,QACAA,QAEA,aAEAK,qBACA/O,OACA0L,OACA,cAEA,gBAGA,SAIAqD,UAEAD,eAGA,+DAgBA,cACA,aAEA,iCAGA,cACA,uBAEA,cACA,wBAGA,+CAEA,gCACA,OACA,kBACA,iBACA,CACA,EAGA,+CAEA,4GAMA,EAGA,cACA,WAGA,+BAIA,gCAIA,oEAGA,OACA,cACA,aACA,CACA,EAGA,2CAEA,4EAIA,4CAQA,kEAgBA,wBACAE,qCACAnE,yCAIAA,gCAIAoE,wDAqBA,cAKA,iEAOA,OANAP,OACAQ,WAGA,YACA,EACAR,MACA,QACAQ,6BAGA,MACA,kCAEAT,OACAE,OACA,MACA,YAEAF,EACAE,+BAOA,MAEAF,EACAE,+BAOA,EACAO,aACAA,gBACAA,kBACAT,OACAE,OACA,MACA,YAEAF,EACAE,qBAKA,MAEAF,EACAE,qBAKA,EACAO,aACAA,gBACAA,kBACAT,OACAE,OACA,cAEA,QAEAO,UACAA,UACAA,4BAGA,MAEAC,YACAC,UAEA,0DAMAC,gBAEAne,sDAMA,wBACAoe,qBAEA,UACA,QACA,oCAEA,QACA,mCACA,6BACAC,CACA,gDAGA,QACA,mCACA,uBACAA,CACA,0CAGA,QACA,cACA,QACA,eAgBA,4BAGAC,EACA/b,EACAgc,2HAIAC,oBACAC,iCAEAC,EACAC,EAEAC,uGAOAN,2BAGAO,6BAKA,GAFAC,MAEAV,sBAEA,uBACA,gFAWA,wDAEA,UACAU,gEAQA,iFAMA3e,kBAKA,CASA,gBACA,qEAGAiZ,6BACA2F,WAGAC,iCACAC,gJAWAC,2CAMAF,qCACAC,oGAkBAE,mCACAA,EACA,mBACA,GAEAP,kBAEA,QADAQ,kBACApf,0CAGAqf,yDAKA,sFAUA,EACApI,mBACAA,yBACAA,iCACAA,6BACAA,0BACAA,wBACAA,uBACA,IAGA,uCAWA,gBAEA,QADAlX,2BACAC,uBACAG,gEAYA,2CAEA,WACA,GAUA,2CAEA,UACA,GAMA,wBACAmf,gBAEArO,yDAaA,kBACA9Q,gCAGAof,qDAQApf,kBAUA8W,yCAKA,CAEA,IAGA,uFAuBA1S,yBAEA,+BACAwV,0BAGAxV,sBACA,yCAIAwV,UAEAxV,sBACAwV,gCAUA,mCAiBA,iCAKA9C,+BAGA,EACAA,yCACA,IAGA,WAQA,kFAGA,GAYA,kDAEAuI,uCASA,6CAEA,uBACA,uBACA,qBACA,qBASA,6BAEA,0BACAC,gBAGAC,mBAMA,sCAGA,yCAIA,mNAaA,iCAGA,0KAoBAzI,kEAKA,CACA,IAGA,WAEA,iFAIA,mCAKA,sBAIA,eAEA0I,sDAEApb,4DAGA,oDAGA,8BACA,iCAGA,GAFA,8BAEAob,yBAGA,8KAgBA,gBAIA,cAKA,iDACA,4CACA,iBAEA,oDAUA,mBACAC,kCACAA,aALA,0JAoBApJ,gEAMAqJ,eACAA,oBAGAC,wBACAD,wCAGA,2CAGA,gCACAA,0BAEAA,0BACAA,0BAIA5I,oBACA,IAGA,WAEA,4FAUAA,qCACA8I,iCACA,EAUA9I,wCACA8I,oCACA,EAEA,cACA,uBACA,eACAC,qCAMA,4CAEAC,OACA,2CAGA,CACA,kCAGA,oDACA,CACA,IAGA,WASA,gBACA,6BAIA,4EAGAC,0CACAH,EAEA,eACA,kHAMAJ,gNAiBAO,gBACA,0BAEA,MAIAA,gBACA,iEAEAC,4BAGAlX,yCACAkX,gCAGAA,uCAGA,GAGAlJ,iBAEA,IAGA,uCAUA,cACA,yDAGA,MAOAmJ,gCAEA,EAEA,IACAC,sDAKAD,sBACAE,wDAKA,GAUA,kDAEA,eACAC,6BAGAA,yDAgBA,mEAEAR,uDAaA,sCAGAA,6CAGAS,mBAUA,8BAIAC,6BACAC,oBACA,wBACA,qDAWAX,gFAKAY,mBACAC,mBAGA,sEAeA,cACA,MACAC,uDAGAC,EACAC,kFAKA,iBAMA,+CAIA,2BACA,qCACAC,6BAGAF,OAEA,CACA,4CACA,sCACA,QAWA7J,gEACAgK,gBACA,0EAEA,EAGAA,iCAEA,iDAIA,EAGA,kDAEAC,mBACA,iCAEA,uCAEA,yCAEA,kBACA,GAQA,cACA,8FAMA,kCACAnB,uBAWA,cACA,oCACAA,sCAKA,kCACAA,qBAKA9I,iCACAA,8BACA,IAEA,uEAGA,CAEA,cACA,wDAKAkK,cACAA,eAEAA,mBACAA,mBACAA,oBAIA,gLAGAC,0BAWAnK,2BACAA,iBACAA,iBACAA,kBACAA,qBACAA,qBACAA,0BACAA,0BACAA,uBACAA,yBAEA,IAGA,WAEA,gBACA,gDAgBA,gBACAzF,UAEA,4CACA6P,kFAKA,uCACAC,mBACAD,KACAC,uBAEA,EAEAC,mBAEA,qKAWAD,YAIArK,gBACA,IAOAA,kBAMAA,oBAGA,4DA8CAuK,uEASA,6BACAC,UACA,MASA,wEAKA,qDACA,GACA,6BACAA,UACA,MASA,gEAEA,6BACAA,UACA,MASA,+BACA,4CAQA,0BACA,6BACA,mBACA,IAQA,4CAIA,wBACA,mBACA,MAEA,oFAoBA,cACAjQ,mBAEAgI,oDAGA,+CACA,kIAUA,+BAGAkI,iCAEAC,kBACAC,QACAC,gBACAC,aACAT,kBACAU,cACAC,8GAGAC,qDAEA,+BAIA,8BAEA,gBACAC,MACA1E,wBACA,+EAKAhE,6BACAA,mBACAA,sCAMA,OAEA,QAEAA,6BACAA,mBACAA,iBAEAqI,kCAGA,qBAIAH,UAGA,GAEAlI,SAGA,sCACAvC,sCACAA,mCACAA,iCACAA,8CAEA,oCACA,EAEAkL,uJAiBAlL,iBACAA,0BACAA,yBACAA,qBACA,IAGA,mJAUA,mFAmBA,8DAEAmL,eACAC,aACA,eAEApL,uCACA,2EAKA,oBACAzF,mBACA,6EAMA,SACA8Q,SACAC,EACAL,CACA,kCAKA,oBACA,SACAI,SACAC,EACAL,CACA,gBAQAjL,qBAEA,IAGA,yDAKA/I,oBAKAA,6BAGAA,+BAGA,+CAKA,+HAkBA,OADAuK,OACAA,IACAvG,YAEAA,yCAQA,+FAiBA,OADAuG,OACAA,IACAvG,0DAUA,mGAiBA,OADAuG,OACAA,IACAvG,0SA0CA,kEAQA,eAGAuG,MACA0C,KAEA1C,OACAA,oMA4BA,OADAA,OACAA,oFAWA,sBACA,kBAIA,cACA,eAGAkB,QAEA,iBACA,sCAQA,sBACA,kBAIA,cACA,eAGAA,QAEA,4GASA,sBACA,kBAIA,GADAlB,OACAA,MACA,6BAKA,iBACA,WACA,eAEA/K,2BACA,6CAOA,sBACA,wDAUA,sBACA,+BAGAwE,gCAOA,sBAKA,OAJAhE,wBAGAuK,OACAA,qCAGAvG,4DAQA,iFAWAuG,SACAvG,iCAEAuG,WACAvG,oCAGAA,4DASA,aACAsQ,2CAUAvL,6FAeA,yDASA,OADAwB,OACAA,cAGA,oDAQA,oaA6BA,CAEA,gBAYA,2EAGAgK,iBACAC,mBACAC,mCAEAC,gFAEAC,qDACAC,kEACAC,6CAEAC,gwBAiCAC,8CAKAC,oJAOAjM,cACAA,kBACAA,eAEA,cAEA,cACA+L,oDAQA,mDAGA,wBACA,gCAEA,yBACA/Z,6EAOAka,sBACAC,gHAQAD,2EAOAA,cACAla,0CAEAA,sBAGAka,iBACAla,wDAEAka,kBAEA5gB,uBAEA4gB,gEAGAla,UACAoa,iDAOA,sDAGA,wBACA,6BAGA9gB,qBAGA,uBAMA,cACA,+CAOA,cACA,eAEA,mFAMA,SAEA4W,2BAGA,4BAIA,yBACAA,8DAQA,gBACA,iBACA,2BACAmK,mCAEAC,mDAaAtM,qCACA,+DAEAnI,UACA/O,gBACA+O,SACA0L,UAGAF,QACAA,QACAA,SACAA,QACAA,sBACAA,sBAGA,iBACA,aACAkJ,6BAEAlJ,QACAA,2EAOA,4BAEAva,4BAMA,gBAGAiZ,UAEAyK,aAEAC,yCAEAC,yCAEAC,qCACAH,YACAA,sBAEAI,oCACAJ,sBAEAK,wCACAL,kDAGAzK,QACA,YACA,YACA,YACA,YACA,wDASA2K,EACA,IAEAI,+BAEAC,2BAGAC,0DAQA,wBAKA,0DAMA,kDAEA,UACA,GACAC,SACAnkB,+BAEA,WACA,gBACAokB,SACA,MACA,aACApkB,qCACAqkB,SACA,MACA,YACAjK,SACA,MACA,uBAEA,MACA,uBAEA,MACA,mBAEA,2BAMAG,aACA,GAGA,QADA+J,SACAC,aACAA,WACAD,uDAGA,CACA,IAKA,gBACA,QACAE,wEAGApB,0CAGAqB,MACA,GAMA,gBACA,QACA,iCAKArB,kBACAla,OAEAub,QAOA,gBACA,oCAEA,qBACA,8BACAlJ,kCAUA,gBACA,iCAGAmJ,2CAMA,gBAEA,QADAC,OACA3E,uDAEA2E,WAEA3E,wBAGA,oBAMA,gBACA,iBACA4E,0BACAC,2BASA,6CAJAA,cACAC,8DAGAF,+CAGAE,kEAIA,oBAOA,yBAEAhE,qDAIA,wCACA,8BACAnhB,yCAUA,uBACAolB,oDAEA,WACAC,uDAEA,YACA,0EAMAC,sFAEAC,EACAC,aACA9T,EACAjD,GACAiL,GACA+L,cAEAC,gCAEA,0GAGAC,6CAGA,wMAaAlC,6CAIA6B,gHAMAA,wBACAC,mCAGAH,mBAQA,iBACA,SACA7N,wBACAA,wBACAA,wBACAA,iBAEA,EAKA,cACA,wGAQAqO,QACAC,0BACAC,0HAIAC,uBACAC,kCACAC,UACAC,wBAEAA,UACAA,WACAA,qBAGA9W,2DACAqV,oCACA7J,qEAEAyF,uBACAA,+JAkBA6F,SACAA,SACAA,iBACAA,sBAQAA,UACAA,wCALA3L,YACAC,8DASA2L,qBAEAA,0BACA3L,aAGA2L,2BACA3L,4CAKA2L,2BAGAA,2BAGAA,0BAGAA,6EAoBA,IAZA/W,6CACAqV,qCAGA7J,kBACA,eAGAwL,0BAIA/F,oBAGA,IAFAgG,+CAEAhG,0CAGAA,0BAIAgG,uBACAA,8FAOA,0CAEA,sDACA,yDAmBA9O,4CAKA,OAEA,2BACAzF,OACAwU,gFAEAxU,gFAMA,SACA,oEAOA,YACAyF,6FAEA,oCAGA,OAEA,SACA+O,qBACA,iDACA,uHAGA,mEACA,EACA,GACA/O,uCACAA,+FAMA,yBACA,qBACA,kCAGA,EAEA,uHAGAgP,sCAUA,yBAPAC,OAEAC,sBACAC,0CACAC,mCAEA,GACA,mBAEA,oEAIAA,qBAGA,iBACA,oMAcA,2DAMA,YAGAC,OACArN,OACAsN,OACAC,WAGAhC,mBAGAA,4EAMAA,qDAeA,mCAEA,iBACA,iBACA,qBACA,sBACAiC,wBAEArV,gBAEA2U,OACAA,8BACAG,kFAsBA,gBAIA,2CAIAnG,mEACAqD,sGAMAsD,sBAOAC,OACA1P,wBACA,MAEA2P,EACAC,CACA,EACAA,6BAGA5N,6CACA2N,OAEAA,+BAIA,eACAE,OACAC,gBACAC,OAEAA,yDAIA,wDAYA,kCACA,yCAUA,8EAQA,mBACAC,OAGAC,WAaA,mDAQAxO,2DAKA,2EAIA,aAmBA,wBACA,0CACAyO,OAGA,uFAKAC,+BAOAC,yCAGAA,yCAGAC,yEAGA,+EAIAA,wDAIAC,iCACAA,UAGAJ,MACAlQ,8BAGAkQ,6BAEA,EACA,+CAiBAhmB,+EAIA,GAEA,cAEA,8CAEA,qBAIA8V,uDACAK,aACA,0EAeAuJ,yCACA5J,iEAEA,OAEA,OAKAA,uCACA,gBACA,gBACA,eACA,eACA,2BACA,sBACA,6CACA,UACA,cAGAuQ,mBACA,qFAEA,oBACA,EAEAA,2BACA,oGAIA,EACA,EAEAA,sFAEA,qDAIA,oBACA,IACA3H,gEAGA5I,cAIA,kBAEA,iCAGA,uLAQA7W,mDAEAqnB,2CAEAA,eACA,CACA,8CAGA,0CAIA,eACA,mBACA,qBACAxQ,qBACA,oCAGA,kGAGAoP,wDAGA,4DAIAqB,2BACAA,sBACAC,SACA,CACA,kCAGA,sFAIAC,kDAIA,0BADAC,IACAA,wDACAA,2CAGA,2BACA9H,uCAGAA,EACA,6CAEA,EAEA4H,aACAG,wBAKAC,mCACAH,yBAEA,EACAE,kEAIAA,WACAA,6DAGAA,gBACAA,gBACAA,mFAEA1nB,kBAIA,iBAEA,EAEAonB,yBACA,yBACA,iDAEA,cACA,GACA,4CAEA,CACA,0CASA,8BAEA,YACAvQ,0CACA,OAGAA,UAWA,gBACA,SACA,iDAcA,qDAUA,sBACA,mBACA,kBASA,sBACA,iCASA,4BACA,iBACA,gBASA,0DAUA,2BACA,mBACA,kBASA,2BACA,iCASA,iCACA,iBACA,gBAUA,qBACA,iCAUA,2BACA,iBACA,gBAUA,mBACA,iCAUA,yBACA,iBACA,gBASA,eACA,mCAQA,eACA,+BAQA,gBACA,iCASA,eACA,+BAQA,gBACA,iCASA,mBACA,4BAGAwB,4BACA,oDAQA,uDAGA,2BAQA,yBACA,qBAQA,gBACA,yDAQA,gBACA,uGAiBA,oBACA,gBACA,eASA,iBACA,sBASA,iBACA,sBASA,yBACA,kBACA,iBAQA,iBACA,aACA+B,SACA,WACA,WACA7S,MACAA,wBAQA,4BAEA,kBAUA,8BAEA,mBACAsP,iDACA,OASA,cACA,cACA,eAGAA,iBAEAA,wCAUA,yDAWA,yBACA,8CAGA,EAYAA,mDACA,MACA+Q,0CACAC,0CACAC,0CACA,UACA,UACAC,MACA,wBACAhoB,wBACAA,6DAGAA,0BAKAA,sBAGAA,4BAIA,EAYA8W,oDACA,YACAmR,WACAC,wBAGAA,oBAEAC,mFAKAnoB,0BAGA,uDAUA,YACAioB,8BAGA,wBAEAE,oFAKAnoB,0BAGA,EAUA8W,wEAEAsR,WACAC,uBACAC,uJAKAtoB,uIAQAA,0BAGA,kBASA,8BAEA,YACA8W,2CACA,OAaA,gBAKA,yBAHA,0BAOAA,UAEAA,mBAMA,mCAGAyR,2CAIAA,yIAkBA,6CAaA,qBAEA,UACAH,4BACAI,4BAIA,mBACAC,WAGA,UAEA,mCACA,OACAA,oBACA,MACA,mBAEA,MACA,mBAEA,WAKA,OACA,kBACA,kBACA,iBACA,wBAQA,qBAOA,sBACA,iCAQA,kFASA,uBACA,oEAQA,qHAWA,wDAGA,sEAQA,wDAGA9P,2CAGA+P,2CAGA1N,uBAEArC,4FAUA,+CAEA,qGAkBA,qBACA,uBACA,cACA,+CASA,uBACAgQ,sDACAC,OACA,uCASA,yBACA,gEAEAA,OAEA,gBAEAD,4BACA,gCASA,wBACAE,iBACAA,qBAIA/Q,uBAEA1T,qDAIApE,sCAGA,cACA,uBAGA,EASA8W,mJAQAA,+GAQAA,uEASAA,25FAqJA,oBAgBA,OANAwB,YAGAA,YAGAA,kBAGAA,QAGAA,MACAkB,gDAYA,uCACA,kEAWA,wEACAkP,oEACA1N,oEAEA,OACA,eACA,eACA,eACAuD,uBACA,EAEA,yDAmBA,uCACA,mMAmBA5F,MAEA,SACAA,yCAIAa,QAEAb,0BAEAqC,eAGA,OACA,kBACA,kBACA,kBACAuD,uBACA,EACA,yDAoBA,uCACA,yDAWA,gCACAuK,6BACAC,oKAIAxoB,oDAEA,OACA,eACA,eACA,eACA,2CACA,EAEA,iCAUA,YACA,uBAEA,kBASA,2GAIAyoB,iDACAC,yCAMA,4EAUA,yDAEA,4BAGA,gBACA,yBACAC,WACAC,yBACAA,WACAD,qCAUA,+CAEAE,OACA,6BACA,qBAQA,cACA,sDAWA,sCAUA,MATA,wBAMAC,YAGAC,kDAeAC,kBAEAC,wBAGAA,4DAOA,yCAWA,gGAQA,0LA0BA,WAEA,0BAEA,WAEA,4CAaA,oCAGAA,kCAIA,uBAGA,iBAIA,EASA,uCAEA,uCACAC,qDACAC,cACA,wDAEA,EAQA,0CAEA,8BAEAC,mBAGA,EAaA,sBACA,yCAEAC,uBACAC,yDAEA,iBACAC,SAEAA,WACAA,SAEAA,UACAA,SAEAA,UACAA,SAEAA,gBACAA,kBASA,wCAQA,sBACA,mGAYA,yDAGAA,gCAIAC,yBACAC,aACAD,cAMA,qCACA,EAGA/K,+BACAiL,MAEAjL,+BACAiL,MAEAC,QACAD,OAGA,6EAIAE,2DAUA,yDAGAL,gCAIAC,yBACAC,aACAD,cAMA,qCACA,EAGA/K,+BACAiL,MAEAjL,+BACAiL,MAEAC,QACAD,OAGA,6EAIAE,qGAsBA,2BAGA,WACA,oBACAC,sBAUAJ,sBAGAA,sBAIAE,uBAMAlL,aACA,wGAqBA,2BAGA,WACA,oBACAoL,sBAUAJ,sBAGAA,sBAIAE,uBAMAlL,aACA,sEAgBArX,YACA0iB,sEAEA,mEAKAC,sDAIA,mBACA,oBACAC,8CAEAC,wEAWA,aACA/S,gBAIAgT,gBACA9iB,cAgBA,sBACA0J,QACA,sDAEAqZ,mBACAnB,uEAQAzP,eACAC,uBAGA4Q,+BAMAC,qBACAC,qBACA7L,UACAA,YAEAA,UACAA,sEAWA,GAFA8L,kCAEAvB,SAEA,mCACAwB,cACAC,sCACA,mCACAtH,SACA5J,gBACAC,qBAGAD,gCACAC,gCAGAkR,oEAMAnR,OACAkF,4DAIAjF,OACAiF,YAIA,yCAOA0L,8BACAA,mFAEAQ,yFA0BA,+CAaA,sFAeAC,wBAEAA,+EAeAA,wBAEAA,uFAcAC,0DAEAC,WACAC,gCACA,oCACAD,2BAaA,eACAE,eACAC,eACAC,wCACAC,wFAGAD,SACA9B,uBAEA8B,OAGAN,4BACAA,2BACAA,gCACAA,0CACAA,mCACAA,6BACAA,6BACAA,uBACAA,uBACAA,iCACAA,iBACAA,iBACAA,gBACAA,0BACAA,yBACAA,cACAA,wBACAA,sBACAA,kBACArU,kCASA,8BACAoD,0BACAiR,kBAaA,sBACAQ,QACA,6CACAC,yCACAC,kCACAF,0CACAG,oBACAC,qDAEAC,MACA/K,yGAIAgL,wBAGAD,SAEAJ,wBAGAM,aAMAjL,cACAA,4CAEAA,UAEAA,WAEAA,YAcA,sBACA0K,QACA,6CACAC,yCACAC,kCACAF,0CACAG,2BAEAH,0CACAQ,YACAlL,yGAIAA,oDAMAA,0BAEAA,wBAEAA,YAGAkK,wBACAA,wCASA,8BAEA,cACA,4BAKArU,YAEAA,wSAgKA,0DAWA,2DAWA,4BAYA,iCACA,sBAUA,4BACA,qBASA,4BACA,sDAEAsV,KAEA,cAQA,0BACA,gBAIA,2DAEA,0BACA,wCAaA,qCACA,MACAC,EACAC,EACAC,iCAEAX,qEAIAY,uBACAC,+BACAC,yCACAC,kBACAN,kBAEAC,kBACAC,sCAOAC,gBAEA,oCACAG,oBACAN,oBAGA,OACA,IACA,MACA,OAEA,IACA,MACA,OAEA,IACA,MACA,OAEA,IACA,MACA,MAEA,GAeA,2BAEA,OADAV,QACAA,8BACA,sEAEA,wEAKA,MAKA,WAGA,4EAGApD,WAGAqE,qCACAA,oEAKAC,iFASAjsB,qBAGAA,2IAcAksB,eACAC,uCACAA,OAEA,UAEA,yBAEA,EAGA,cACA,uHAKA,EAGA,cACA,OACA,qDACA,qJAKA,2IAyEA,uBACA1b,kCAGA,yDAKA,GAEA,QACA,uDAMAqN,0EAKA,EAEA,gEAKA,oDASA,yBACA,gBACA,wBACA,sBACA,qBACA,gBACA,oBACA,gBAUA,4BAEA,eACA,mBACA,2BACA,qBACA,qBACA,iCACA,+FACA,EACA,kDAWA,wDAEAsO,wCAEAhO,4EACAiO,gCACAC,+FAsDA,gDAjDA,GAEAC,yBACAF,WACAG,cAGAH,aACAG,eAEA5Z,qDACAyZ,kBACAG,mBAIApO,QACAA,QAEAqO,uBACA,0BACAA,6BACAhc,yDAEA,qBACA2b,GACA,mBACAK,EACA,aACA,cACA,cACA,cACA;AAAA,CACA,EAEA,uBAEAL,GACA,mBACAK,yGAMA;AAAA,CACA,GAGA,2BAKA,IAFAC,aACAA,YACAztB,uBACAytB,0BAGA,0BACA,QAEA,0BACAC,MACA,2BACAD,gCAKA,4BACA,kBAEA,qCAEA,+BACA,qDACA;AAAA,CACA,EAGA;AAAA;AAAA,GAEAN,YASA,gEAGA,eAaA,KATA,qBACA9G,yBACAxH,qBAEA,uBACAwH,yDAIArmB,8HAKA,eACA0oB,qEAOA,kEAwDA,yCACAiF,gBACA,qDAKAC,wIAMAC,MACA9H,yEAEAlH,oBAIAA,wBAIA4O,4DAOAH,eACAF,UACAG,UAGA,sBACA,4GAQA,YAKA,uBAMA,2CAEAO,OACAA,mBAGAA,2CAKA,4DAEAR,gBAEA/M,oHASA/O,MACA,GAEA,IAGA,uIA2DA,yBAKA,GAJAA,mCAGA,mBACA,gDACA8F,WACA,YAIA,4CAEAL,wCACAwQ,oBAEA,2BASA,qBACA,+EAKAljB,kBAGA,iFAIAoP,2BAGA,mBACA,iFAGA,0EACA,EACAsD,2CAWA,kBACA,yJAMA,wFAMA,gFAOA8W,MACAC,QAEAD,cACAC,iBAGA,gEAIA;AAAA,4BAEAD,QACA,yCAEA;AAAA;AAAA,GAKA,uBACA,6BAUA,mBACA,kBAOA,6BACA,aAGAxpB,2EAMA,EACA,gBAOA,8BACAke,iBAEA,aACAxL,4CACA,wIAkEA,uBAEA,6CAIA,sDAYA,yBACA,eACAgX,wCACAvF,wDAEA,OACA,eACA,+BACA,+BACA,2BACA,2FAkBA,kBACA,6CACAqE,sBACA,mEAEAmB,0DAKAC,+CACAC,iDAEAza,UACAoZ,SAEApZ,UACAoZ,SAIA,0EACAoB;AAAA,kDAEA1L;AAAA;yBAGAiG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAeA,6BACA,OACA,iBACA,eACA,qBACA,qBACA,+BACA,0BACA,EAEA,8BAEA,mIAQA,GASAzR,qJAKA,WAIA,mBACAA,kDACA,kCAKAoX,0BACAC,yBACA7L,iBACA8L,wBACAC,yBACAC,uBACAC,6BAEAC,qDAeA1X,mDAQA,yBACAzF,UACA,wDACA,8RAkGA,yIA8DA,0BACA,iCACA,iBACA,2BACA,qBAEA,kBACA,0BAGAA,uDAGAA,gEAGAA,gEAGAA,uDAGA,kIAeA,+FAOA,6BAGA,0BACA,qEACA,oBACA,qGAKA6X,qCACAA,2JAgEA,0FAoDA,0DAwBA,mFAyBA,+HAaA,0BACApS,uCAEA,uBACA,UACAxQ,oEAOA,mFAgBA,wGAUA,UAOA,QAHAsZ,UACAA,YAEA,2CAUA,yBACA,yBACA,oBAEA,+CACA,kDAEA,2BAIA6O,mBACAA,2IAaA,+BAEAC,gBACA,qBAGA,kEAGA5X,sGAEA,6DAIA,+EAQA,wCAQA,oBAYA,uBACA,wCAYA,wBACA,yCAcA,kCAGAzF,QAEA,eACAsd,OAEAtd,wDAGA,wBAGAA,4CAIA,iCACA,8EAEA,0BACA,kBAEAA,WACA,8BAcA,oEAGA,8CAIA,8CAIA,gBAaA,oEAGA,oDAIA,qEAYA,kCASA,iCACA,yBACAud,uBACAC,oBACArb,MAEA,IADA,yBACA3T,yFAKAivB,iBAGAF,mBAGAC,gBAEA,oFAeA,0BAEA,0CACA3P,iCACA6P,OACAA,oBAEA,qBACAA,cACA,8BASA,oBACA,kDAUA,yFAIA,8BASA,yHAIA,0BAQA,2BAOA,+EAGA9uB,cACA,qCACAA,iBAOA,6BACA,uCACAA,kBACA,iBASA,yBACA,2EASA,+CASA,iDACA,0BACA,uBACA,wBACA,qBACA,wEAEA,0BACA,oEAGA,uGAWA,sGAgBA,mBACA,8CAWA,0BACA,4GAaA,gEAEA,2BACAsY,oFAGA,qDAKA,4DAEA,qBAWA,2BACA,6CACA,6BACA,8BACA,qBACAzB,uDACA,mCACA,0BAEAmK,SAEAA,oEAEAA,0DAEA,yBAGAxC,cAEAA,gBACAA,oDAEA,8BAEA,oEAEA,qBAEA,mCAOA,iCACA,6CACAwC,SACAA,2CAGAA,4CACAxC,eACAwC,6BACAA,sEACAA,aAQA,6BACA,QACA,2BACAjR,sBASA,yCACA,wCACAnP,yCACA,oBAIAogB,SACAA,mDAGAA,yDAEAA,cACAA,qBACA+N,iBACAA,KAEA/N,wIAIAgO,8CACAhO,SACAA,gBAGAA,YAEAA,2CAEAzN,YACAyN,eAQA,+EAQA,8FAWA,OACA,kBACA,iBACA,6BAQA,gDAQA,kHAUA,kHAUA,yBACA,4DAUA,iCACA,yDAUA,kCACA,kGAWA,kCACA,oHAWA,wDAEA,eAUA,8EAEAzN,oEAUA,2BACA,iCAQA,gEASA,gFAOA,qDAGA,8CAEA,EACA,iCACApQ,8CAEA8rB,oCAEApY,2CAQA,iEAEA,0BACA,wFAWA,4BACAqY,yBACA7oB,yCAIA,mCACAA,6BAQA,mCACA,+FAGA,qBACA8oB,sDAKAhsB,gBAGAisB,cACAA,mDAKAjsB,aAGAksB,0BACAlsB,yCAEAmsB,0BACAnsB,sEAoDA,oBACAiO,UACAA,YACA,kEAIA,eACA2b;AAAA,yHAKA,eACAA;AAAA,0FAKAA,iBAEAA,YAMA,8BACA3b;EAKA,kDACA;AAAA,CACA,GAMA,8EAGA0d,oDACAS,+BAEAne,wBAEAA,gBACAA,gBACAA,oBACAA,sBAGA,iCACA0d,uCAEAzM,oBACAA,oBACAA,yBACAA,mCAKA,QACA,sCACA,8CACA,iBACA,iBACA,kBACAmN,EACA;AAAA,EACA;AAAA,EACA;AAAA,oEAGA,gCACA;AAAA,CACA,GAGA,oCACA,8BAEA9H,0CACA;AAAA,yCAEA;AAAA,wDAWAqF,8DAEA,gBACA,uCACAxZ,GACA,yBACA,0BACA,iBAEAA,EACA,gDACA,EAEA,GACA,yEAYA4Q,iCAUA,wCANApU,UACAwD,iCAGA,GAEA3T,0BACAI,OACAomB,6DAIAqJ,QACA,YAGA,YACA,YACAC,OACA,WACAC,OACAvJ,6BAEAqJ,UAMA,eACA1C,IACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,CACA,sBAIAA,GACA,2BACA;AAAA,EACAA,EACA,MACA;AAAA,CACA,eASA,6BACA,0BACA,2BACA1mB,OACA,6LAmBA0mB,0BAOA,gGAEA6C,qBAIA,wEAEAC,oCAEA,qGAGA,UACAC,gCACA3Y,eACA4Y,EACA,aACAD,gCACA3Y,gBACAyY,EACA,gCACA;AAAA,CACA,cAIA,gDACA,eACA;AAAA,CACA,GAYA,yCAIA,yBACAhwB,+CAEAowB,6BAEAhwB,iKAoBA,2CAIA,yBACAJ,2CAGA,IADAowB,aACApwB,mBACAI,2JAwBA,8CAIA,yBACAJ,mDAIA,IADAowB,aACApwB,mBACAI,kCAEAiwB,QACAC,yBAEA,iEAOAD,QAEAC,oDAEA,6HAWA,aAMA,wBAEA,mJAMA,YAKAA,gBAiBA,6CAIA,yBACAtwB,uDAGAowB,6BAEAhwB,kCAEAiwB,6BACAC,yBAEA,8FASAA,oDAEA,6HAWA,6DAQA,mJAMA,YAKAA,gBAaA,+CAEA,gGAWA,mEAEA,oBAEA,qDAEA,GACA,qEAEA,+BAEA,wEAEA,4BAEA,uBACA,0BACA,+EAGArZ,8DACA,iCAEA,oDACA,kGAEA,4IAYA,GAEAoY,yCACAA,yCACAA,8CAEAA,sEAkBA,qBACA,sFAWA,UAEA,kBACA,qDAMA,GAoBApY,kEAEAA,iGAGA,6BACA,mHAIA,EAEA,0LA2EA,4BACAmK,yBACAA,uBACAA,6BACAA,mCACAA,wEASA,kEAEAA,SACAA,kEAQA,iBAIA,mBACAmP,cACAnP,eACA2I,cACAV,0BACAU,uBAGA3I,iIAOA,8BACA,2FAUAA,iBACAA,gDAQA,6BACA,6EAEA,GAGA,WAMAnK,yGA8BA,uBACA,cACA,gNAqBA,0BACA,iCAGA,gDACA,2BAGA,4BACA,iBAOA,0BACA,qCAGA,gDACA,4DAGA,oDACA,0BAGA,iDACA,2EAKA,0BACA,cACAmK,cACAA,yFAGAA,WACAA,cAQA,sBACA,sCAGA,yBACA,mBACA,mCAQA,+BAEA,2BAEA,cACA,kBACA,wCAOA,kGAIA,+CACA,yBACA,gEAWA,6DAEA,kBACA,0BAOA,gCACA,2BACA,0BAQA,4BAEAlC,mEAGA,0BACAkC,kFAOAlC,uBACAsR,uBACAtR,OACAsR,OAIA,IAFApP,kBAEA,iGAUAA,kBACAA,WACAA,aAQA,oGAUA,qDAEA,oCAQA,qDAGA,kBACA,uBACA,iCACA,uCACA,mCACA,oCACA,GACA,qBACA,4BACAxC,uCASA,6BACA,kGAKA6R,EACA,kBACAA,gDACAA,OACAC,OACAC,8FAkBAvP,cACA,gBACA,8GAGA,4BAKA,+BACA,gCAIA,iDACA,oEAEA,+BACAxC,cACA,oBAIA,0CAEA,EACA,IAOA3H,uDAcA,uBACA,cACA,gBAOA,2CAEAmK,yBACA,wCAEAA,aAGA,kBACAA,mBACAA,qDAEAA,cACAA,UAMA,wBACA,qBACA,iDACA,kBACA,qEASA1I,cAEA,IADA,0BACA,wCAGA0I,aAOA,wBACA,0DAGA,wBACA,iDACA,iBACA,gBAGA,uCAQA,wCACA,iCAEA,SAEA,2DAEAwP,gBACA,gBACA,SACA,0CAGA,WACA,GAEA,kDAEAC,+BAGAC,qBAEA,oEAEA,0CAEA,iDACA,oBACA,gCACA,gCAOA,qBACA,2BAEAC,2FAIA,kDAGA,kBACAC,+BAMA,GAOA/Z,uIAiDA,uBACA,cACA,qBAOA,wBACA,0BACA,iDACA,kBAEA,0DAQA,wBACA,0DAGA,oHASA,yCAEAga,2CAKA,sDAEA,kBACA,iBACA,+EAKA,eACA,GACAA,UAIA,qIAMA,oEAEA,0CAEA,iDACA,oBACA,gCACA,gCAOA,8CAKA,2BACAlwB,wBACAmwB,kBAIA,SACA,kCAUA,mBACA,iCAKA,IAJA9P,uBAEA,0BAEAphB,wBACA,WACA,uBACAohB,6DAIAA,gCAOA,iCAKA,IAJAA,uBAEA,0BAEA,uEAGAA,aAMA,0BACA,yBAEA,2BAEA,kGAKA,sBACAzI,sBAEA,qFAIAA,gBAGA,uBACA0G,UAEA,qBACAA,qHAQA,GAQApI,uFAMAka,gFAKAC,uBACAA,gDAEAA,cACAA,yHAaA,uBACA,oEAOA,kGAQA,4DAEAC,mIAIA,aACA,YACA,KAGA,GAGA,WAEA,wBACAhX,0BACAiX,sBAyCAra,4CAQA,yBACAzF,UACA,wDACA,kFAEA,wBACA,k0BA2SA,4BACA,yBACA,2BACA,0BACA,2BAEA,0BAEA,6DAEA,qDASA,8BACAmC,6IAQA4d,UAGAC,UAGAC,aACA,sDAKAF,+CAWA,qGAEA,yBAEA,2DAEA,wBAEA,4FAKA,2BACAnQ,+GAGA,+DAIA,uBACA,yBAEAA,kCAUA,sBACA,4BACA,uBACA,gCAOA,gCACA,6JAgBA,4DACA,sIAIAsQ,sGAMA,8EAGA5pB,8BAEA,qBAEAsZ,SACAA,2CACAtZ,YACAsZ,YAEAtZ,6BAEA,qEAWA,mCACA,qIAiBA,oCACA,8BACAmnB,2BAGA,IAEAnnB,GACAmnB,GACAwC,sCAGA,iCAEA3pB,eAEAA,kBAEAmnB,+DAsBA,yGAGA0C,4DAIAC,SAOA,0CAEA,YACA,WACA,EAEA,oCACAC,aAEAC,gCACAD,YAGAC,6BACAD,cAEAC,gCACAD,qDAaA,wHAiBA,uCACAlI,gBACAoI,OACApI,sDACAgI,sEAEAK,sBACA7S,8CAKA,gBACA,gBACA,cACA,mDAIA,YACA,YACA,OACA,OACA,UACA,UAIA,wCAGA,mEAGA,uCAGAA,mBACAA,kEAIA,yBACA,2BAQA,yDAQA,2BACA,0BACA8S,yBACAC,wFAEAC,kDACArM,oBACAsM,oBACAC,oBACAC,oBACAC,4BAEA,sBACAnR,gCACAA,mFAMAA,oCACAA,4DAOAnK,qEACAmK,4BAYA,yBACA,yDAMA6N,qBACAuD,8BAEAC,OACAC,kCAKA,6GASA,iBACAzD,uCACA,mCAKA0D,eACA,8BAGA,mDACA,kDAEA,iDAcA,4BAKAvyB,mBAEA,kEACA,wEAkBA,kEAMA,WACAwyB,UACA,iEAEA9qB,gDAEA+qB,qEAGA,iBAWA,8BACA,6BACAC,gDAEA,GAqBA,yBAEA,6BACA,6BAEA,oBACA,qBAGA,WACAC,qBACApW,4BACAqW,aACAC,cACAC,GAEA,oCAEAD,sDAGAD,6BAIA,kBACAF,0BACAA,0DAKA,8BACA,eACAA,OACAA,0CAQAI,GACA,gBACA,iBACA,EAGA,6BAGA,iCAQA,gHAKAH,gBAGAA,8BACA,sBAEA9b,8FAKA,uFASA,qGAQA,oDACA,sDACA,sFAOA,4DACA,yBACA,mCAEA,sBACA,2CAEA,mDAQA,gFAIAA,uCAEA,aACA,0JAKA,GACA8I,UACAA,8CAUA,+FASA,uDAQA,sDAQA,uDAQA,6FAMA,QAUA,6BAEA3f,yBACA,iDACA,4BACA,0CACAA,sBAEAA,0BACA,yBACA,+DAUA,sEAEA+yB,UACAC,+CAGAC,iCAGA,GACAC,UAEA,GACAnjB,+CAGAwD,+BAGA,GACAwf,UAEA,GACAC,uBACAG,6DAIA,GAEApjB,WACA,6CAGA,GAEAijB,YACA,+CAGA,IAWA,8BACA,qGAgBA,sCACA,+EASA,0BAcA,mCACA,+BAGA,yCAGA,kCAcA,gCACA,uDACA,iBACA,qDAEA,qFAWA,qBACA,kGAGA,uBACA,4GAGA,cACA,cACA5S,cACAA,6DAEA,sBACAvJ,mEAWA,qEAEA,yBAOA,yBACA,4BAGAgY,6FAaAtb,sFAYA,sMAIA6f,KACA,sCAEA,GACAvc,sFAcA,+CAEAxQ,qFAWA,+EAIA,iCACA,0EACA,qCAEAwQ,2DAEA,GAIA,4BACAsJ,kBACAtJ,8BAGA,IAGA,WAEA,yBACAwc,oCAEAC,eAEA,gBACA,gCAGAzc,yFAiBA,uBACA,4HAYA,0BACA,yBACA0c,yBACAC,oCACAA,gCACAA,kCACAA,8BACAA,6QAQA,0BACAA,0EAGA,wCACA,kCACA,sDACA,oCACA,sGAUA,6BACAH,qCACAA,4CACAA,2CACAA,sEAOA,mBAIA,+CACA,iDACA,+CACA,2CACA,6CACA,yCACA,2CACA,qCACA,uCACA,+CACA,+DACA,iDACA,6CACA,iDACA,mDACA,mDACA,6CACA,kEACA,kEACA,qCACA,sBAQA,yBACA,2DAQA,sBACA,mCAOA,0BACA,wBAOA,wBACA,0BACA,sCACA,yBACA3rB,4BAEA,oDAEA2f,mCACAoM,2BACA,GACA,yBAOA,0BAOA,+CACA,0CACA,yBACA,0BASA,mCACA,6DAQA,uBACA,qCAQA,2BACA,6CAQA,wBACAC,iGAYA,yGASA,2BACA,8BACAA,oBACAA,wBASA,2BACA,iEAEA,kCASA,yBACA,gCAGAC,sBAGA,yBACAC,gBAWA,yBACA,2BAGAA,oBAGAA,6CAGAA,iBACAA,sDASA,0BACAF,mBACA,iEAGA,sBACA,gCACA,yBACAH,yBACAM,4CACAA,8CAEAR,iCAOA,yBACA,sBACA,gCACA,yBACAE,yBACAF,kCACAQ,qCACAA,4CAOA,iDAKA,qBACA,gCACA,sBACA,6BACAR,4CACAA,8CACA,WACA,wBACA,qCAEA,6CAGAQ,2CACAxM,8BAQA,uBACA,oBACA,gCACA,yBACAkM,yBACA,uBACAF,qCACAA,2CACAQ,oCAQA,yBACA,gEACA,4CAOA,mBAQA,0BACA,+BAGA,0BAOAhF,oBAeA,wBACA,0DAEAiF,4BAMA,GALA,iCACApsB,gDAIAqsB,QACA,qBACA,8BAEA,OAGA,WACA,sBACA,8BAEA,gCACA,wDAIA,gCACA,yCAOA,kCACAC,sDAIA,+BAEAA,EACA,mDAKA,cAMA,GAJAtC,sBACA,sBACA7a,sBACA,EACAnP,gHAMAusB,yDAGAA,gBAGAvsB,cAIA,oCACA,4CACAwsB,wDAEAA,gDAGA,8BACA,yBACA,gDAIA,2BAGA,mBAWA,2DAEAC,eACA/iB,4BAIA,+CAMA,mFAgBA,mBACA+iB,mBACA/iB,6BAIA,YACA,cACA,sBACA,sCACA,gCACA,EACAgjB,8CAEAhjB,0DAGA1J,uBACA,2BACAysB,wBAQA,sCAEA,6BACAzsB,WACA0J,4BAIA,eACA,EAEA1J,aACAA,eAGAA,eAEAqX,kFASA,sCACA,4BACA,gGAIA,kFAQA,sCACA,sDAEA,yHAUA,kKAcA,0BACA,oEAEA,mBAEA,WACA,mDAGA,OAGA,WACA,oDAGA,OAGA,uBACA,kCACA,kCAQA,wBAIA,qBAEA,gHAIA,0DAIArX,sBAGA,qBACA,4EAEA,2BACA,uCAGA,gGAQA,0BACA,sBACAmP,sBACA,EAEA,GADAnP,aACAA,wFAGAgrB,qBACA2B,qCAEAA,uIAcA,kBACA,mBACA,4BAQA,qCAEA,gCACA,oCACA,wJAOA,6BACA,iEAEA,6CAGA,IAYA,6DAEA,iCACA,QAEA,uBACA,kCACA,iCAOA,8BAIA3B,uDAKA,kBAEA,uBAMA,6IAGA,kCASA,iCACA,gEAEA1K,8BAEA,oIAMA,GACA,0DAEA,kDAGA,GAEA,kEAUA,oCACA,oEAEAA,8BAEA,mFAIA,GACA,0DAEA,mDAGA,GAEA,oEAgBA,0BACAsM,6CAEAC,kCACAC,+BAEAC,OACAC,2FAeA,2BACA,8DAEA,iCAOA,sDAEA3V,yBAEAA,WACAA,2KAWA,UACA3E,MACAmX,gBAEAI,sBAKAlI,cAEA8H,gBACAxS,qBACA,8FAQA,gCAQA,2HAMA4V,kEACA,wBAEAjD,wBAIAhqB,6CAaA,6CAVAA,kBAGA,gDACAktB,kBACA,GAEA,2GAcA,EACA,IAGA,WAEA,eACAzM,WAEAtR,yCAQA,2BACA,yBACA,oIASA,8BACA,yBAEAgY,YAGAnnB,uJAmBA,qCACA,+CAEAitB,eACAA,sBACA,iEAEAA,cAEA,qCAIAA,mBACA,kGASA,qCACA,qDACA,iFAYA,yBACA,oBACAE,iDAEA,uBACA,uBACA,sEACA,oCAEA,IAOA,gEAGAC,EAGApE,0CAGAA,6DAGA,+BAQA,4BAYA,aAVAqE,EACA5X,yBACAE,4IAKA2X,+CAGAp1B,gDAGA,qCAIAo1B,kEAEAA,+BACAA,iCAEAtE,gBATA,CAiBA,2CAEA,wBACA,OASA,oEAEA,iEAIA,yBAEA,EAEA,IAGA,WACA7Z,+CAkCA,sBACAzF,UAEA,sBACA6jB,eACA1H,kGAEA,gCAgBA,8BACAA,OACA2H,QACA,0DAEAvL,iBACAwL,aACAC,cACAC,MACAC,yBACAC,uBACAC,sBACAC,mBACAC,gBACAC,2BACAlH,+BACAmH,kBACA,iBACAnH,WACA,qBACA,4BACA,oBACA,yBACA,aACA,cACA,8BACA,oDACA,yBACA,aACA,cACA,8BACA,mBACA,2BACA,oBAGA,EAEA,IAGA5X,mFA4BA,0BACA,4CAIA6Q,aACAmO,yBAEA,iCAEA,6DAGAxO,UACAA,iFAIAA,+BACA,GAGAA,+BAEA,8CAaA,kDAKA,GACA,yBAEA,iBACA,yBACA,sBACA,oBACA,iBAKA,oBACA,iBACAnQ,QAQA,wGAMA,qEAGAA,OACA,wBAIA4e,sEACA5e,MAEA,EAEA,6DACA,uDACA,wDACA,oFAWA,kBAGA4e,QACA5e,OACA,iDAIAL,gDAEAif,QACA5e,MACA,2DAIA4e,QACA5e,MACA,yDAYAA,SACA,2CAIAA,OACA,WAQA,yBACA,wCAEA,6CAUA,wDAEA,IAQA,oBACA,qCACA,kCACA6e,4BACA7e,OACA,EACA,IASA,gEAGAyO,mBACAA,2CAGA,+EAEAoQ,cACA7e,OACA,GACA6e,qDACAA,sDAGA7e,QAGA,eAOA,2EAGAmL,4CAEApI,0BACA+b,sBAGAnf,WAuCAA,gqCA0hBA,gBACA,iUAaA,gBACA,mLAQA,gBACA,2FAqCA,0BAEA,kDASA,wEAEA,sDACA,0BAEA,eAkBA,4BACA,4FAGA,sBACA,aACAof,WAEAxd,MACAwd,cAIA,wCACAC,+BAEA9b,aACA,aACA6b,aACAA,UACAA,aAEAxd,MACAwd,aACAA,WACAA,qDAiBA,yEAGAE,2BACAC,2BACA,OAIA,UACA,WACA,eACA,oBAGA,iCAUA,gEAEA,iCACA7E,6BACA,sDAIA,iFAEA8E,sBACA9d,6CAEA+d,4CACAC,iCACAC,0BAGA,+BACAC,uCAEAC,qBACAC,UACAC,OACAC,2BACAC,OACAC,6DAMAD,sCACAC,6CAIA9N,uBACAA,0BAGA,6CACA,oDAEA+N,QACAC,QACA,iDACA,kDACA,kBACA,mBACA,0GAEA,aACA,qBAUA,uBACA,mKAWA,sBACA,8CACA,mFAEAjW,4CAQA,qBACA,mCAEAzN,GACA,eACA,kBACA,qBACA,yRAQA,wFACA,iCACA,uCACA,mCACA,mJAKA,iBACA,uHAGA,qBACA,qCACA,uBACA,2BACA,kGAGA,2DAGAA,gJAKAsD,wCACA,+DAYA,6BAEA,yBAOA,iCACA,wCACAqgB,oBACA,kEAKA,YAGA,0CACA3jB,kCACA,YAEA,0FAsBA,eACA,OACA,mBACA,kBACA,EAGA,mJASA,oDACA,6EAGAsG,OACAC,8DAUA,mBACA,yDAYA,oDAEAqd,mGAOAtuB,iDAIAA,OAEAlI,+GAOA,cAGAy2B,sCACA,oCACA,cACAA,+BAEAA,mLAyBA,8BAEAvgB,4CAUA,yBACA,iDACA,eAOA,mBAEA,+FAMAmK,SACA,iCACA,gCACA,kBACA,4CAEA,oBACA,mBACA,4BAGA,0BACA,cACA,6GAKAA,cAGA,wBACA5P,mDAEA,0BAEA,sBACA,qEACA,kDACA,8CAQA,uBACA,wBACA,kBACA,yCAcA,mKA8BA,MAJA,+BACA,gEAGA,uCAgBA,qEAEA,uCAEA,oHAiBA,kCAWA,GAVA4P,SAGA0G,WACA1G,6CAGAA,4CAGA0G,sBACA,yDACA1G,2CAEA0G,eACA1G,6BACAA,sEACAA,aAOA,yBACA,iCAEA,kBACA,eACA,gCAGA,0BAEA,oDAEA,YACA,eAQA,4BACA,KAIA0G,qBACAA,gBACAA,oFASA,8BACA1G,mCACAA,gFAQA,yBACA,gCAGA,2XAyBA,8BACA,0BAGA,2CACAA,4CAGA,OACA,cAGA,EAGA,wBAOA,qGAKAA,6BAIA,+BACA,mBAEAA,0BACAA,0BACAA,oCACAA,4BACAA,gCACA8K,SACAA,uHASA9K,yEAMAA,yBAKA,6BACA,iBAEA+N,UACA/N,4EAIAA,gBAKA,mCACAA,gBACAA,4BACAA,uBASA,8CAKA,8BAGAA,mBASA,8BACA,kCACA9G,6BACA9I,MACAsa,QACA2L,uDACAC,0DACApd,gEAEA8G,SACAA,4EAEA,aACAA,4DAEA,aACA5P,cAEA4P,4EAEAqW,qFAMArW,aAOA,uBACA,iBAIA,mCACAuW,+BACAC,+BACArH,mCAIAsH,0BAEAxO,0BACAsO,sBACAC,uBAEAxW,uEAEAuW,2BACAvW,qCACAA,uCAOA,0BACA,eAIAA,iBACAA,iDAUA,wIAKAgM,6BACAG,8BAEA,kFAIAnM,4BAGAA,kEASA,gCACA,4BACA,sBACA,sBAGA,oBACA,6CAmBA,wBACA,aAIAA,qCAEA,0BACAA,kBAGAA,SAEAA,cAOA,+GAMA,sBAGAA,yCAEA,8BACAA,oCAEA,oBACAA,6GAIAA,WACAA,cAcA,+GAEA0W,0GAEAA,UACAA,gCAEAC,wDACAA,4BACAA,wEAIA,mEAGAA,SACA3W,mIAIA,EACAA,kLAqBA,yBACA,+CACA,cACA,sEAGA,mBACA,mBACA,eAWA,mCACA,oCACA,uBACA,mCACAnG,iDAEA,8BAEA,sBACA,sBACA,mBACA,mBACAA,kBACAA,iBACA,mBACA,qEAUA,2CAEA,6DAIAhE,oCAyBA,2FAqBA,4BACAzF,UAEA,2CACAwmB,sCAEArK,iEACA,kBACAnc,oBACAxP,6BAEAwP,kBACA,mFAMA+e,gBACA0H,sBAIAC,SACA3H,mCAIAsH,qRAgBA,GACArmB,oBACA6X,wGAIA,kBACAA,YACA,gCACA,8CAGA,sCAMAA,cACAA,sBAqBA,sBACA,yFASA,sIAiBA,mBAEA,yBASA,mBACA,0FAGA,iDAMA,6CAaA,qFAWA,qFAWA,qFAWA,oFAWA,mFAWA,iEAUA,8BACAyJ,+BACA,2BACAqF,2BACA,oBACAC,qBACAA,qBAEA,oBAGA,GAQA,qCACA,gCACAhX,8EASAnK,8DAIA,GAEAA,yDAEAoY,mCAUApY,mEAWAA,uCACA,qBAEAA,kMASAK,OACA,EACA,EACA,EAQAL,sBAIA,WAEA,8BACAohB,+BAKAC,6BAIA,EAEArhB,yCAWA,2CACA,UACAuD,MACA4S,MAEA,0BACAmL,aAMA,mBACAC,aAMApL,MAEA,mBACAqL,aAMA,mBACAC,aAMAnL,OAEAH,QACAnC,qHAgBA,2DACA,kBACAhU,gFAaA,2DACA,kBACAA,mEAUA,sCACA,iEAkBA,+BACA,oGAYA,kEAIA0C,uDAGAA,kCAGA6W,uBACA,uDAGAA,yDAoBA,yCACAmI,qGAQA,+CAEAC,gEAMA,gDAIAC,kBAEA,mBACAC,OAGAA,4CAIA,iBACA,8CASA,mCACA,mCAEA,4BAEA,sBACA,sBAEA,cACA,sCASA,8EAGA,uBAEA,mCACA,mCAEA,cACA,aAEA,2BACA,yDAOA,uEAEA,EAEA,IAGA,WAEA,cACA,OACA,2BACA,2BACA,2BACA,0BACA,EAGA,aACAze,qBACA0e,8BACAxK,kJA4DA,kCAEAyK,+EAGA,oDAWA,wBACA,+FAaAC,2CACApa,EACAqa,EACAC,CACA,EACA,uEAWA,6CACA,oBACAC,gBACA,EAEA,oJAgBA,yDADAp5B,0BACAA,QACA,8HAmBAq5B,kCAEAA,4KA2BA,uBACA,0GAaA,OAPA3gB,mBACA,2BACA2G,kBACA,IAIA,kHAiBA,oCACA,yCAWA,gCACA,mFAIA,8CAGA,6CACA,6BACAA,mBACA,GACA,+CAQA,kCAGA,SACA,OACA,QAEA,WACA,OACA,QAEA,YACA,OACA,QAEA,UACA,OACA,OAEA,YA4BA,iDAGAia,EAEA,kBACAA,sFAWAC,uDAQAC,gBAEAD,gBAIAA,eAIAE,OACA,gBAaA,wDAEA,iEASA,sEASA,2CASA,kEAEAxwB,IACA,oBAGA,mBAGAA,cAYA,qEAGA,kBAUA,2BAEA,0DACA,mCAUA,4BAEA,4DACA,8DAIA,kCACA+gB,+BACA0P,sBACAC,kBACAC,iFAOA,aAGAC,UACAA,UACAA,UACAA,UACAA,UACAA,UACAA,UACAA,qCAOA,+BACA1V,8BACA+K,8BACA4K,SACAC,SACAA,+BACA9O,qFAGApM,6BACA,6BAgBA,+BACAsF,8BACA4V,SACA9O,mCACA+O,gBACA,OAEA,oBACA,mBACA,mBACA,iBACA,GAcA,6DAIA,yLAeA,iEAQA,4BACA,yBAGA,8CAEA,uBACApmB,sCACAA,mDAEAqmB,0IAWA,gCACA,2BACA,sGAIA,iBACAC,SAEA,aACA5f,2CAEA4f,QACAA,yHAWA,aACA,eAEA,kCACA1oB,GACA,iBACA,gBACA,gBACA,mBACA,mBACA,iBACA,iBACA,iBACA,gBACA,EACA,0CAEA0oB,iDAUA,uBACAF,eACApR,iCAYA,wCACA,eACAlF,cAEA,eACAC,cAEA,4BAGA,oBACAwW,aACAC,gBAGAC,sCACAF,MACAC,SAGA,6FAGA,mBACA,kCAGA,GACA,0CAWA,4DAEA,8FAWA,kCACAnP,kFAIA,EACA,IAGAhU,+DAQA,kBACAA,0DAEA,wEAYA,kBACAA,4DAEA,kDAYA,0BACA,kBACAA,+DAEA,qDAYA,yBACA,kBACAA,8DAEA,oDAYA,mBACA,uDACAA,wDAEA,6CAKA,GAIA,WACA,qBAIA,8FAMAiW,eACA,eAEAoN,2CAXA,0CAmBArjB,yCAMA,6GAIAsjB,kQAKArN,+JAMA,OACAhB,EACA,wBACA,4BACA,0BACA,6BACA,2BACA,6BACAiD,EACA,qBACA,kBACAjb,EACAsmB,CACA,YASA,+BACA,WACAhU,+FAEA,wCACAiU,wDAEAxhB,gDACAyhB,8CACApU,iDACA6I,6BACAjD,mCACAyO,+BACAC,2DAEAD,2BAGA,CACAzO,EACAuO,EACAjU,EACAvN,EACAyhB,EACApU,EACAqU,EACAxL,EACAyL,EACAC,yBACA,YAQA,iCACA,iEACA,2BACA,sCAQA,0FAQA,OACA,+BACA,kEACA,YAQA,8BACA,wDACAC,sCACA,UACA7K,aAGA,sBACA,mEAGA,WACA,8CACA,0BAEA,4BAEA,YACAxN,gBACA,aACAA;KAUA,kBACA,8DAQA,mGAOA,2CACAjR,QACA,gBACAye,4BACA8K,GACA,+CAEA,uCAGA,cACAC,4BAMA,mCACAxpB,QACA,gBACAwpB,YACAC,0CACAC,qDACApT,8EAEAqT,0BACAjP,wCACA6O,SAEA70B,4BACA+pB,mCAEAnI;EAEAA,mBACA;AAAA;CAKA,SAGA,MACA,qDAEA;AAAA,CACA,EACAiT,GACAE,EACAG,yDAGA,WACAC,OACAlM,mCAGAjD,+DAOAiB,6BAGAA;AAAA;GAEA6N,qDAIA,yEAEA,EACA,IAIA,0FAUAM,+BAEA,iCAMA,kBAIA,qBACA,mDAGA,+BACA,2CAMAC,yEAIA,8CAIA,kCACAx6B,qCAOA,iCASAkW,yCAOA,4BACAukB,OACA,YACA,qDAGA,qBAQA,gDAEAzhB,QACA,kCAIAvI,wDAHA,oBAcA,uBACAA,+BAEA,sCAEA,uBAGA,EACA,IAGA,yCAIAyF,yCAOA,0HAOA,UACAwkB,MACAC,+CAMA,IAHA,gBAGAtqB,YACApR,gHAoBA07B,qDAEA,mCAYA,2BACA,2BACAp7B,0BACA,8BAWA,mBAEA,2MAkBA,oCACA,oIAMA8gB,SACA,iEACA8N,gCACA,4BACA9N,+CAEAA,4EAEAA,kBAaA,0BACA0K,QACA,yCACA2O,yBACA9hB,QACAE,QACA8iB,2BACA7P,oCAGA,8DAEA,oFAKAnT,EACAE,CACA,MAGAuI,kDAIAuI,8CAGAvI,8DAIA,EAEA,MAEAA,YAGAA,qDAeA0K,QACA,0DACA2O,mBACAmB,qBACAC,yBACAljB,6CAEAE,6CAEA,gBACA,kIAKAF,EACAE,CACA,EAEAuI,kBAaA,2BACA0K,QACA1K,SACA,yCACA,mCACAA,0DACA,qFAGA,6DACA,iBACA,+HAYAzH,8BAEAgQ,wBAEA,GACAvI,kBAUA,8FAWA,gCACA,kCACA,iEAqBA,kCACA5P,UAEA,wGA2BA,EACA,IAGAyF,+DAiBA,8BACA6kB,QAEA,mBACAza,kBACAQ,uBAGA,mCAEA,kBACA,iCACA,0BACA,qCAEA4F,gDAIA9T,kBAGA,IAWA,8BACAmoB,QAEA,mBACAza,kBACAQ,uBAGA,mCAEA,iBACA,iCACA,0BACA,oCAEA4F,gDAIA9T,kBAGA,IAWA,uBACAmoB,QAEA,mBACAza,kBACAQ,uBAGA,mCAEA,gCAEA,0BACA,wCAEA4F,gDAIAA,gBAGA,GAEA,GAEAxQ,4DAqBA,gDACA,kBACA,sBACA8kB,UAEA,+BACAxb,OACAyb,uJAkBA,aAEAC,iBAMAzqB,gEAOA,uCAEA0qB,0CAGA,qBACA,YAEA,aACA1qB,8BAKAyqB,kCAGAA,oCAMA,6BAEA,aACA,gBACA,oBACA,+BACA,yDAIAxU,+BAQAjW,8DAOAiW,cACAjW,mCAEA,uFASA,eAOA,2EAGA2qB,wBAEA,WACAllB,yCACA,OASAA,oEAqCA,+EAQA,yJAYA,yBAOA,4BACAzF,UAEA,qCACA,sCAEA,4BAEA,yBAEA,yBAEA,yBAQA,sEAGA,iSA6CA,oBACA4P,cAGA,4BACAA,oBACAA,oBAEAA,6BAKA,8FAGAA,mDAUA,kDAGA,GASA,qBACA,2JASA,qCACA,iBACA6J,uBAEA,kBACAA,qDAWA,4BACAmR,oGAMA,0BAKA,qBAUA,4BACA,+BAEA,YACA,cACA,cACA,cACA;AAAA,CACA,EAGA,GASAnlB,4EAUAA,mCACAzF,QACA,kDACAkH,GACA2jB,QACAA,QACAA,QACAA,OACA,EACA/kB,uBACA,kCAWA,cACA,gBACAA,OACA,8CAGAL,yCACA,EAKA,gBACA,eACAqlB,UACAC,UACAC,cACAC,YACAxhB,WACAyhB,aAEA,kBACA,oBACA,OACA,yCACA,OACA,wDACA,OACA,yCAEA,mBAWA,8BACAriB,0BAEA,aACApD,4CACA,OASAA,uFAgCA,4FAQA,qDAGAlW,cACA,wBAWA,qIAaA6W,sCAEA,SACA+kB,sDAGA,kBACA;AAAA,CACA,gCAIAC,mBACAC,sGAMAF,GACA,sBACA,cACA,0BACA;AAAA,CACA,YAUA,oBACAvb,oBAEA,EACA,cAEA/G,mBACAA,iBACA,EACA,EACA,mDAQA,oEAQA,8CAOA,sBACA,6DAGA,GASApD,6GAYA,oDAEA,SACA,8EAGAolB,4BACAA,4CAEA,EAKA,cACA,kEAaAplB,kCACA,kBASA,8BAEA,eACAA,6CACA,OAUAA,6EA2BA,oBACA,mBACA6lB,gBAEA1b,0DAIAA,cAEA,+CAUA,mBACA0b,gBACApkB,GACA,iBAEAqkB,OACA,YACA,+CAGA,MACA,EAGA,uCAUA,2CACA,kBASA,8BACAC,YAEA,cACA/lB,6CACA,OAUAA,gEAuBA,qEAOA,sDAEA,0BACA,2BASA,mBAEA,qCAEA,SACA,gCAEA,MAEA,SACA,iCAEA,oCAWA,2DAQA,0CAQA,qBACA,2EAUA,kCAEA,iBACA,eACA,iBACA;AAAA,CACA,GAQA,oBACAmK,cACAA,sDAGA,EACA,UAEA,EACA4b,MAEA5b,YACA,4BAEA,GASAnK,mHAYA,qDAEAolB,wBACAA,yCAEA,qCAYAplB,mCACA,kBASA,qDAGA,WACAA,yCACA,OAUAA,oCAOA,2FAuBA,qEAOA,sDAEA,yDASA,oCAGA,kBAQA,+GAOA+iB,aACApR,cACA9Z,gBACA0L,gCAGA8E,gBACA8B,8BAIAA,kBACA6b,gDAEA7b,oBACA6b,sDAEA7b,kBACA6b,gEAGAA,0CAEA7b,cAEA,6BAQA,qBACA,2EAUA,qCACA,+BAEA,oGAGA;AAAA,CACA,EAGA,GASAnK,uFAUAA,yCAEA,eAEAzF,QAEA,0HAKA,mDACA0rB,2CACA5lB,IACA,kCAWA,uCACA,kBASA,2FAIAmL,iBACA0a,+BAEA,eACAlmB,6CACA,OASAA,wFA2BA,oEAqBA,yBACAzF,QACA,iDAEA,iGAUA,0JAKAA,YACA4rB,+BAGA,gCACA,gCAEA,OACA,+BAGA,GAEA,oBACA,gCAEA,mBACA,+CAGA,0BACA,yBACA,8BAeA,8HAKAzkB,MACAE,MAEA,oCAKA,GAQA,4DAEA,2BACA,8BAUAH,6CACAiX,uEAIAlN,4BACAA,2BACA,EAEA,wCAEA,sBACA;AAAA,CACA,GASA,oDAEA3T,oBACA0L,oBAEA,0CAKA4G,8DAEA,qCAEAA,gCASA,2CAIA,oFAUA,GASAnK,oGAWA,6BAEA,eAEAzF,UAEA,uDACA6qB,4CACAA,aACA/kB,qBACA,CACA,EAEAL,uGAYA,oDACA,kBASA,8BACAkmB,+BAEA,cACAlmB,4CACA,OASAA,sHAoBA,4CAIAmK,cACA,6BAGA,GASAnK,uDAUAA,oGAYAA,4CACA,kBASA,iHAKAwL,iBAEA,WACAxL,yCACA,OAUAA,0DAgBA,6EAEA,kEAQA,oCAEA,qEAUA,wDAEA,sCACA,EAEAA,8DAOA,gCACA,8BAOAwD,0CAGA2G,qDAMA,4BAEA,QACAtS,OACA,OACAsS,kBACA,MAEA,QACAtS,OACA,eAGAsS,kBACA,MAEA,QACAtS,OACA,OACA4O,OACAC,uBAEAH,OACAA,sBAKA,EACA,MAEA,2BAEAA,OACAA,OACAA,OACAA,MACA,EACA1O,OACA,OACA4O,OACAC,OACA,cAGA,gBAGAyD,cACA,QASA,oBACA,4BACA,iDAQA,0CACA,sDAQA,4DAEA,iDACA,IAQA,6BACA,8CACA,qBACA,mCAYA,iCACA,uCAGA,4BACA;AAAA,CACA,qEAKA,iDACAqB,6BAQA,0BACA,iCACA,4CACA,+CACA,GAQA,kBACA,0IAUA,sEAUAjF,kBAKAb,kCAMA,4BAEA,QACA7N,OACA0L,YAEA,MAEA,QACA1L,OACA0L,oBAIA,MAEA,mEAQA,EACA1L,OACA0L,OACA,MAEA,mEAQA,EACA1L,OACA0L,OACA,cAGA,gBAGA,MAEAmC,6CAGA,GACA0gB,UACAC,wBAIAlL,UACAC,UACAC,UACAiL,MACA3C,MAEA,oCAKA,EAEA,mCAUA,kCACA,kDAEA,WACAhc,gBACAjL,WACAsD,+DAEAK,OACA,GAGAA,OAEA,QAGAL,uCAEA,EASAA,yDAWAA,mCACA,kDACAolB,aACA/kB,yBACA,kBAUA,oEAIAL,UAYAA,8JA+CAzF,QACA,mDAKA,oBACA,qEAwBA,yDAdAA,qBACA,wBAEAA,qBACA,wBAIAyJ,sBACA,6BACA,oDAOA,mDAQA,QADAuiB,KACAx9B,2DASA,iCAEA,+DACA,8CASA,kCACA,aACAy9B,oBAIA,WACA,SACA,GACA9pB,aACAA,sFAiBA,6CAEA,4EAKAsD,2FAGAtD,2CAGA,mBACA,4BACA,gBAEA,2BAGA,uBAWA,6BACA,qEAGA,eACA,mBACA,4BACA,iBACA,oBAOA,2BACA,cACAA,2CAOA,6BACA,cACA,gBAMA,8CAEA,gCAEA,iCAGA,0BAEA,2BAGAsD,wCAQA,qBACA,gCACAymB,gBACA,mBACA,0BACA,GACA,gBACA,6BACAt9B,6CAEA,iCAEA,GACAA,2CACA,sBASA,mEAMA,gEAEA,6BACAA,qDAEA,iCAEA,GAEA,uDACA,sBAQA,mBACA,kDAEA,+CAWA,sIAIA,iEAaA,kLAgBA,6DAOA,kIAUA,sEAIA,4EAIA,sCACA,oLAqBA,qGAIA,eACAuT,aACA,sFAcA,GACA,gDAIA,0BACA,qDAEA,GACA,+CAUA,iBAGA,mCACA,iBACA,sBACA,iDAEA,gBACAohB,yBACA1L,eACAlZ,sBACAwD,UACAA,WACA0V,QACA,GACA0L,WACAA,aACA1L,kBACA0L,6CAUA,gEASA,SACA,sCACAphB,cACA,SAOA,wBAQA,kBALAoF,yDAGA3H,aAEApR,gCAEA6e,8BAEA0B,qCAIAxH,+DAUA,6BACA4kB,yBACA/c,+BAEA/H,aACA,aACA,iBAIA,kDAUA;sCAIA8jB,uCAEA;AAAA,8BASA,yHAGA,OACAzP,sBAEAsN,CACA,YAQA,kCACAmC,wCAGAA,8CAGA,wDAGA,oCAUA,gBACAnrB,4BAEA,GADA,iBACA,mDAGA,qCACAsW,aACA,kBACAgJ,WAEA7Z,sDAEAK,OACA,GAGAA,OAEA,GACA,yFAIAA,yBACA,EACA,EACA,mBAQA,8BAEAL,oBAWAA,qEAeA,yBACAzF,QACA,oBACA,gEAIAA,YACA,wBAEAA,YACA,wBAEA,mBACA,4BACAyF,2CACA,kEAYA,iBACA,+DASA,GAPA,cACA2mB,SACAztB,yCAEAwD,SACA,GACAiqB,aACA,sBAGA,kBACA,gBACAvU,kBACAuU,uCAUA,2MAuCAxc,SACAA,iGAEAyc,QACA,2BACAA,kBAEAA,mEAEA,sCAEAzc,YAEA,8CAUAnK,4CACA,iBACAK,mCACA,EACA,8CAeA,GAJAwmB,WACAA,aAGAA,gBACA7mB,2CACA,OAUAA,2KAsEA,2EASA,yHA8CA,yBACAzF,UACA,gBACA,sHAUA,0BAYA,gHAGA,gBACA,wBACA,6CAEA,oBAMA,mBACA,gCAQA,0BACA,sBACAusB,wBACAA,2CAQA,0GAGA,0BACA,kHAEA,cACA,yCAOA,oGAQA,wBACA,qEAGA,GAOA,6DAIA,oCACA3c,0FAMAA,gBAQA,qBACA,iEAMA,0BAGA,sCAEA,GACA,kBACA,2CAEA,GACA,8FAWA,mHAUA,0FAKA,iDAGA;AAAA;EAEA;AAAA,CACA,EACA0G,2CAEA,4DAGAkW,mEACA,8GAMAC;sCAKA,gBACA,eACAC,GACA,UACA,kEAEA,gCACA;AAAA,CACA,EACA,YAEA,mEAeA,mBACA,qDAEAne,YACAA,cAGA,sBACAA,sBAGAA,MAIA,qCAeA,6DAEA,2KAeA,wBACAoe,2BACAC,+BACAnkB,WACAC,qDAKA,GAHA,iCAGA,cACA,gBACA,uBACA,uBACA,mBACA,mBACA,OAEAjD,4FAIAonB,gFAEAxP,UACAA,WACA,wEAGA5X,6BACA,2BACA,yDACA,4DAWA,yBASA,gKACA,2CACA,sBACA,uBACA,4BAIA,+JAOA4X,UACAA,WACA,gBACA,wBAKA,+BACA,qDAEA,mBACA,mBAEA,gEAGA5X,6BACAqnB,oKAGA,qEACA,8EASA,oBACArnB,gDACA,4DACA,0BAEA,gBACA,6BAQA,8BACAA,gDACAA,0EAeA,gCAGA,wBACA,yNAUAsnB,MACAC,gCAIA1vB,2BAEA2vB,yEAUA,mCACA,gIAiBA,2BACA,qCACAxnB,uDAOA,wBACAzF,UACA,mBACA,yBAQA,2BACA8sB,gDAEAhnB,iCAIAA,QAUA,4BACA9F,UACA,wBACA,+CACA,iGAUA,6EACAktB,uHAGA,kDACAC,yBACA1kB,uDAEA0kB,mBACAC,MAEAD,oCAIAA,mBACAE,MAEAF,yBAIAA,0BACA1kB,6CACA8S,QACA4R,mBACAG,OAEAH,wBAGA5R,QACA4R,mBACAI,OAEAJ,wBAGAD,MACAM,SAIA/kB,MACAC,OAEA,4EASA,EAEA,GAQAjD,gCAMAA,sFASA,6BACAA,yDAGA,OAEAA,4DACAtD,qJAIA,uBACA2D,OACA,EACA,EACA,EACA,qBACA,EASAL,gCACAA,iCACAK,gDAEA,EAQAL,wBACAA,2BACA,wFACA,EAUAA,oCACA,sHAGA,MAMAA,qGAQA,WACA,2HAqBA,yBACA6kB,QAEA,mBACAza,kBACAQ,uBAGA,mCAEA,6BACA,4CACA,0BACA,qBACA4F,uCAIAA,kBAGA,GAEA,GAEAxQ,+CAQA,6BACA,sBACA,8BASA,+BACA,uBACA,mCACA,GAEA,GAGA,WAUA;mDAKA,2BADAgoB,mBACA,2CAWAhoB,+BACA,+GAKAgoB,4DACAC,WAGAjoB,oDACAioB,sBAEA,qFAGA,KACA,EAGA,2BAEA,EAEAjoB,uBAKA,cACAzF,gBACA,0BAEA,iDACA,qBACA,4BAaA,aAOA,6BACA,uIAWA,kFAEA,IACA,mCAOA,6BAEA2tB,qFAQAC,yBACA,0BACA,mBACA,kBACA,iFAOA,EACAC,MACAC,UACAA,sCAGAC,4EAIAC,iDAGAC,KACA,mBACA,mBAGA,oBAQA,mEAEApW,UACAA,6JAeA4V,sBAEA,cACA,YAeA,mCACA,wNAaA,yGAGA,gCACA,yBAEA,yBACA,uEAIA,EACAS,kEAEApB,wCACAqB,6HAKAV,0FASA,cACA,iBACA,cAEA,qDAOA,qBACA,sBAeA,kCACA,6DAEAA,gEACAA,gEACAA,+DACAA,8HAKAA,yEAcA,+BACA,wBACA,4BAGA,yBACA,6DAYA,8BACA,uBACA,4CACA,qEAcA,gBACA,oBAEA,uQAeA,wBAGA,CACA,kBAGA,0CAEAW,qBACAC,uCAGAP,UACAA,YAcA,4LAmBA,gBACA,0CACAM,qBACAC,sBACAC,QAGAC,uCAEAC,6FAGA,kDAKA,WAIA,mBAEA/oB,0BAKA,4EAcA,aAcA,0DAEAmK,uBACA,8BACA6e,0IAUA,EACA,6CACAC,wGAIA9e,kCAIA,CACA,yBAUAnK,oCAOAA;;;;;;;;;;GAgCA,0BAEA,oBAQA,uBACA,2DAaAkpB,yBACAC,uBACAnpB,6BACAkpB,YACA,yBACA,sCACA,yCAKA,uBADAlB,mBACA,0DAGA,kDACAA,qBACA,0CAMA,uBADAA,mBACA,0DAGA,oDACAA,qBACA,EAGA,wBAIA,2CADAA,iBACA,wDAGA,wCACAA,sBACA,wCAIAoB,oCACA,iDACAA,0CACA,kDAIA,GAUA,oCACA,mDAEA,8EAwBA,kBACAC,kDAEArB,6BACAA,0CACAA,8CAGA,kDAEAztB,YACAmH,qBACAE,uBACArH,0EAEAA,sDAEAytB,sEACAztB,2DAKAytB,aAIA,0BACAztB,WACAA,SACA,sBACAA,gCACAA,6CAWA,yBACA+uB,oEAGA,2BACA,oFA4BA,oBACA/uB,SACA,0BACA,qBACA,uBAGA,mBAUA,2BACA,kDACAA,oFAiBA,yBACA,uEAGAytB,8CAGAA,oEAGA,2DAEAA,uDACAA,mGAGAA,uDACAA,0EAIAA,8EAMA,sCACAA,6GAMA,iCAGA,sFAoBA,4BACA,wDAEAuB,sBACAA,wBACAhvB,oCASA,0FAaA,uBAEA,GAEAyF,oDACA,qCACA,gBAEA,cAOA,8BACAqnB,kBACAmC;;;;;;;;;;GAoDA,sFAqBA,sDAGA,kCASA,sBACA,kBACAl9B,SACAm9B,WACAtR,cACAtW,4BAEA,iBACAA,4BAIAvV,mCACAA,qCACAA,oDAIAA,0CACAA,4CACAA,iDACAA,mDAWA,kCACA,0GAGA,GASA,8BACA,kBACA+W,GACA8U,oBACAA,oBACAA,wBACAA,mDAGA6P,qEAGA,GASAhoB,6FAQA,8BACAqnB,kBACAmC;;;;;;;;2CA4DA,sBACA,uBAGA,mBACAl9B,sBACAo9B,kCACA,6BAEAp9B,gBACAA,kBAUA,kCACA,wDAEA,GASA,8BACA07B,2CAEA,GASAhoB,4FASA,qDAEAqnB,kBACAmC,uGAqEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA0JA,2BACA,+IAIAjvB,mDAEAA,mBASA,sBACA,kBACAjO,SACAq9B,cACAC,oDAEAC,UACAC,wCAEAC,qCAIAC,QACAnyB,0DAOAgK,+CAIAooB,QACAD,SAGA,sGAgBAD,2BAOAA,uBAIAxvB,eASA,kCACA,8KAKA,GASA,8BACAytB,8FASA,mBACA,kBACA,GAEA,GASAhoB,2FASA,8BACAqnB,kBACAmC,kEAsBA;;;;;;;;;;;;;;;;;;;;;;;wCA6CA,sBACA,kBACAl9B,WACA6V,aACA+nB,YACA,iBACAA,uCAGAA,gFAIAA,qDAGA59B,0BAYA,2BACA,yGAGAiO,kDAEA,0BASA,kCACA,4CAEA,GASA,8BAEA,mEAYA,GASAyF,2FASA,8BACAqnB,kBACAmC;;;;;;;;;;;oCAkDA,sBACA,kBACAl9B,WACA6V,WACA,+BAEA7V,kBACAA,6CAWA,oBASA,kCACA,gDAEA,GASA,8BACA07B,mCAEA,GASAhoB,wFAUA,qDAEAqnB,kBACAmC;;;;;;;;;;;;;iCAgEA,sBACA,kBAGA,mBACAl9B,sBACA69B,eAEA,mDAIA79B,8BAYA,kCACA,oFAGA,GASA,8BACA07B,qCACAA,6FASA,gBACA,GAEA,GASAhoB,uFASA,8BACAqnB,kBACAmC;;;;;;;;;;;;;;;;GAwDA,sBACA,kBACAl9B,SACAm9B,WACAW,UACAn7B,cACAo7B,QAEA,8BACA,kCAEAp7B,YAEA4S,kCAKAyoB,+BACAC,2DAGAt7B,YACA3C,6DAcA,2BASA,kCACA,sIAIA,GASA,8BACA07B,yCAEA,GASAhoB,0FASA,qDAEAqnB,kBACAmC;;;;;;;;;;4BAwEA,sBACA,kBACAl9B,WACAk+B,oBACA3oB,MACAvU,sCACAm9B,GACAn9B,OACAA,OACAA,QAEAo9B,GACAp9B,OACAA,OACAA,MACA,EAGA,wBACAuU,yBAIAA,QACA+P,QACA1N,QACArC,QACA+P,QACA1N,oBAYA,kCACA,gFAGA,GASA,8BACA,0CACAsmB,4BACAC,0CAIA,GAEAC,GACAp9B,WACAA,WACAA,WACA,CACA,2GAWA,iBACA,sBACA,GAEA,GASA0S,6FASA,8BACAqnB,kBACAmC,wBAGA,8GAMA,+GAMA,0HAMA,2HAMA,uFAMA,2EAMA,yEAMA,EAEA,4CAiBA,0CAWA,uFASA,eACAnC,kBACAmC,4GAoDA;;;;;;;;;;;;;;;;;;;;;;;;;GAmCA,wBACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,uBACA;AAAA,IAUA,2BACA,wGAGAjvB,mDAEAA,mBASA,sBACA,sCAEAowB,MACA9oB,uBAGAvU,4FAKA,4BAEAuU,oCAKA,4BAEAvV,eACAA,eACA,MACA,aACAA,2FAGA,MACA,yCAIA,iBAEA,iBACAA,mBACAA,qBACAA,qBACA,MACA,8CAIA,MACA,aACAA,mBACAA,qBACAA,qBACA,MACA,cACAA,mBACAA,qBACAA,qBACA,MACA,cACAA,+CACAA,iDACAA,iDACA,MACA,gBACAA,6DAGA,MACA,sBAEAA,aACAA,eAWA,kCACA,8CAEA,GASA,8BACA,0CACAgB,yBACAA,yBACAA,uFAUA,OACA,eACA,iBACA,eACA,gBACA,EAEA,GASA0S,4FAQA,eACAqnB,kBACAmC;;;;;;;;GA0DA;;;;;;;;;;;;;;;;;;;;;;IAiCA,2BACA,yGAGAjvB,mDAEAA,mBAGA,yBAEA,gBACAqwB,iDACA,wHAKA,4BACA,6EAUA,iBACAlpB,mBACAE,oBACA,qCAGA,oBACA,GASA,sBACA,kBACAipB,gDAEAnpB,UACAE,WACA+oB,QACA9oB,2BAGAgpB,0DAGAC,oCAEAA,2BACAA,UACAA,YAGAvoB,wEAGAA,gCACAwoB,+BACA,4BAEAlpB,kCAKA8oB,6CAMA,4BAEAr+B,eACAA,eACAA,eACA,MACA,oBAEA,QAWA,kCACA,0GAGA,GASA,8BACA,qDAEA07B,iEAQA,OACA,uDAEA,eACA,gBACA,EAEA,GASAhoB,oDACAA,uCACA,6BACAzF,UACA8F,oCACA,EACA,uHAWA2qB,YACA3D,kBACAmC,kHA2DA,kCACA,oFAGA,GASA,8BACAxB,0EACAA,iCASA,2BACA,kHAGAztB,kDAEA,qDAIA,+EAOA,QAFA0wB,yDACAC,wCACAniC,aACAoiC,wBASA,2BAIA,QAHAC,eACAC,2BAEAtiC,oCAIA;AAAA;;;;;EAQAsiC;AAAA,CACA;;;;;EAuBA,oBACA9wB,SACAA,WACA,yBACA,mBACA,2CACA,kFAGAA,2BACA,0BACA,qBACA,sBACAA,iCAEA,2BACA,mBACA,wGAGAA,4BACA,0BACA,qBACA,sBACAA,oCAGA,6CAKA,yCAGA,iHAQA1C,WACA,UACA,oBACA,GAUA,sBACA,kBACAmL,cACAC,cAEA,mBACA,4CAGAqoB,kBACAC,EAEA,8BACAA,6BAEA,4BACAA,oCAEA,6BACAA,oCAEA,8BACAA,iCAEAhxB,eAYA,+BACA,kBACAixB,qBACAC,kCACAC,qBAgBA,IAfAb,8DAGAa,gBACAA,6BACAA,cACAA,iCAGAvhB,+CAGAmhB,OACAK,OAEA,wHAsBA,gCAYA,kCAEA,cACA,kBACAC,iDAOA,qFAIA,mBACAC,QACAA,mDAMAC,6BAEAD,iDAGAE,6HAiBA,YACAC,OAOA,oDAEAC,mFAGAC,4GAKA,aAYA,gEAEAza,0BACA0a,iBACAC,wBACAC,sCACAC,+DAKAC,QACAC,+DAOAC,wCAEAxxB,gBACAqxB,oBAgBA,sCAMA,0CAJAI,SACAC,gCAEAC,sCACA,YACA,gHAIAC,gBACAC,yCAEA,2CAOAf,mBACAA,mDAOAA,uIAwBA,OACA,eACA,mBACA,mBACA,2BACA,8BACA,EAEA,GASA/rB,wFASA,8BACAqnB,kBACAmC;;;;;;;;;uCA0DA,sBACA,gGAMAuD,4BAEA,iBACAzgC,4EAYA,kCACA,oDAEA,GASA,8BACA07B,uCAEA,GASAhoB,0FASA,8BACAqnB,kBACAmC;;;;;;;;;;;;2CAgEA,sBACA,uBAGA,8DAIA,4EAGAl9B,kCACAA,oCAUA,kCACA,wDAEA,GASA,8BACA07B,4CAEA,GASAhoB,4FASA,8BACAqnB,kBACAmC;;;;;;;;;;;;;uCAiEA,sBACA,qBAGA,uCAEAwD,yBAEA,yEAGAC,oDAEA3gC,kCACAA,oCAUA,kCACA,oDAEA,GASA,8BACA07B,wCAEA,GASAhoB,0FASA,8BACAqnB,kBACAmC;;;;;;;;;;;;;;;;;;;;+BA4EA,oBACAjvB,uDAGAA,WACA,0BACA,mBACA,qBACA,sBACA,0BACA,mBACA,qBACA,uBAGA,mBAIA,sDAMA,2DAEAmH,oBACAE,qBAEAipB,oGAIAC,eACAoC,gBACApC,6FAKAqC,0BAEAC,2BAOA,IAHAC,gCACAF,qBAEApkC,qCAEAukC,gBAEAH,kEAGAA,gBACAA,kCAEA,yCAEAG,gBAEAH,kEAGAA,gBACAA,kCAEA5yB,sEAEA,uBACA8yB,qCAUA,kCACA,6CAEA,GASA,8BACA,mFASA,kBACA,uBACA,qBAEAE,sBAIA,qBAEAA,sCAIA,gBACAC,OAGAA,SAIA,GAKAnG,wEASA,8BACAA,kBACAmC;;;;;;;;;;;;uCAyDA,0CAEAnC,gDASA,yEAGAoG,6BAcA,IAXA,2GAWA1kC,kBACA,oCACA,oCACA,oCAEA,4BACAuD,sBACAA,0BACAA,2BAUA,kCACA,8CAEA,GASA,8BACA07B,kCAEA,GASAhoB,uFASA,8BACAqnB,kBACAmC,8EAkBA,sDAGA,0CASA,2FAGAvsB,YACA,wBASA,wDACA,gEACA,kGAMA,GAKA+C,kDACA,2CAEA,qCACA,GACAxQ,+CACA,gBAEA,kBAQA,8BACA63B,kBACAmC,sIAyCA,6IAOA,EACA,qBACA,qBACA,qBACA,qBACA,qBACA,qBACA,sBACA,sBACA,uBASA,2BACA,8BACAnC,oDAgBA,oBACA,uBACAA,4CAGA,GASArnB,6FASA,oDAGA,WACAA,yCACA,OAGA,MACA,6LAEA,WAUAA,oCAOA,0BACA,WACA,aACA,aACA,YACA,aACA,OACA,cACA,YACA,SACA,OACA,kBACA,WACA,0QAyGA,oCAUA,wDAkBA,6DAMA,6KA4EA,oJAgEA,kBACA,SACA,cACA,OACA,aACA,WACA,aACA,YACA,YACA,WACA,cACA,SACA,4EA8BA,yBACA,8BACA,YACA,uDAEA,WACA,mBAEA,wBACA,sBACA,mGAUA,oBAEA2H,mFAeA,6BACA3H,0GAGAA,qFASA,8BACA,gCACA,2CACA,uDAUA,uBAGA,kBACA,mBACA,qEAKA,0GAGA,wCAEA,iHASA0tB,6OASAC,8BAEA,0DAEA,gCACAC,WACAA,iBACAA,gBAIAA,YAYA,+HAmBA,0CACA,+JAgBA5rB,iEAUA,oBACA,gBACA2F,mCACA,uBACA,6EAEA,0GASA,wBACA,4BACA,0BACA,0BAGA,wBACA,2DAgBA,GADAwC,8BACA,iCAEA,aACAA,wBACA,MACA,eACAA,qBACA,MACA,gBACAA,wBACA,MAGAA,+JAcA0jB,qBAgBA,sCACA,gCAQA,uCACA,gFAGAC,EACAC,oBAEAC,wBACAC,uBACAC,wBACAC,wCAIA,sGAEA,mEAMAC,uDACA,yDAEAC,0DAEAlkB,SACAA,wDAEAA,cACAkkB,cACA,WACA,sDAEAP,iBACA,EACA3jB,aAEAkkB,OACAF,QACA,2CAGAhkB,cACAikB,cACAD,EACAF,EACAK,EACAR,iBACA,EACAI,SACAI,eAIAA,iBAGAD,QACAF,QACA,2CAGAhkB,yBAEAgkB,EACAF,EACAK,EACAR,iBACA,QAIA3jB,cAGA,wBAWA,qMAOA,cACA8Y,SAEAA,qCAeA,yDACAsL,sFAcA,sBATAC,QAEAC,6CAIAC,OACAC,OAEAjtB,oCACA,6DAIA,oBACAitB,2BACAF,oDAIAA,QAEAG,yCAGAH,OACAE,OAEA,6BASA,gFASA,mDAEA,sEAGAE,YACAA,cAWA,yBACA,mCACAC,4BACAC,oBACAC,0BAGA,8CACAC,OACAH,gCACAI,OACAxtB,wBAKAwtB,MACA,8CAGA,oBACA,YAEAC,iDACAC,yGAIA,qBAEA,MACA,uBAEA,MACA,sBAEA,UAGAL,oEAGAC,UACAF,OACAC,SAGAA,2CAMAA,2GAgBApnB,YAGAV,+IAeA,gFAEA9C,+CACA8C,6BACA0nB,gBACAjtB,YAEA,uBACA2tB,iEAQA,gCAEA,eACA,EACA,YACA,gCACAtlB,sDAUA,4BACA,yBACA,6BAOA,gFACAulB,wCAGA,qGAOAhgB,qEAGA1N,mEAUA,mFAQA,sBAQA,gCACAuI,iBACAolB,uHAGAD,sEAGAhlB,EACAH,EACA,uBAEAR,MACA5gB,CACA,OAGAohB,aAOA,4BACA,0EAWA,+BACA,oGAKA,sBAGAA,mDAEAA,qDAEAA,cACAA,cAYA,iEAGAqlB,yCACAC,EACAC,OAEAC,MAEAC,EACAjoB,YACAkoB,sDACAC,uDACAC,oCACA5lB,SACA6lB,qBACA7lB,6LASAA,YACA,sEAIA8lB,kCAEA3B,OACA5kB,6BACA4kB,YAGAA,iBAEAkB,OACA,2CAMAC,2CACAC,0CACAE,yCAIAzlB,SACAA,6FAGAA,8DAQAT,YAIAS,aAcA,oFAGAzI,6DACA,iBACAmf,gCAEAC,wDACAA,4BACAA,sFAGAA,sEAKA,QACA,gBACAxgB,mMAaA6J,iEAMAA,+BAKA,+BACA,iCACAA,6BACAA,uCACAA,+BACAA,mCACA,6CAGA,6BACA,gDAcA,0IAIA+lB,gDAGA,SAGA/lB,SAEAgmB,gCACAD,qEAKAE,0BACA,sBAEAA,cACAzmB,iGAIAQ,cAUA,6BACA,8CAUA,2BACA,4GAcAnI,gEACA6qB,sJAWA,0DAEAwD,iDACAC,sDAEAC,0BACAA,yBACAA,0BAIAA,eACAvC,OAEAuC,mBAGAA,uBACAvC,OAEAuC,2BAGAC,6CAUA,qBACA,sBACA,4DAOA,+FAGA,cACA,6BAYA,0DAEA,sDAIA9uB,6EAMA,sKAgBA+uB,KAEA,SAOA,oCACA,2CAGA3C,MACAC,UAEAC,wBACA0C,yBACAxC,0BAEAmB,2FAKA,mEAEA,+BAGAC,0DAIAqB,oCACAC,yCACAjnB,8DAEAkjB,2CACA,+BAMA,8BAJAgE,oCACAC,sEAEAC,2CACAppB,QACAwC,SACAA,cACAA,mEAGA,iBACAmM,oBAEA,gBACA,EACAnM,qBAGA0mB,8CAIA,2CAGAF,OACAxmB,yBAEAgkB,EACAxkB,QACA2kB,EACA,gBACA,GAEAJ,SACAI,+BAOAA,6BAIA,2CAGAnkB,cACA0mB,iBACA1C,EACAxkB,YAEA,gBACA,OAKA,wBAQA,kEAEAqnB,kDACAzhB,cACA0hB,6FAGA,uFAKAC,4CACA3hB,CACA,aAOA,mBAEA,yFAMA,mCACA,mDAUA,gCAKA,yDAFA4hB;AAAA,QAEApoC,mBACAqoC,uCACAC,mBAEA,eACA,4DAQA,sEAGA,4DACAloC,yCAaA,4CAEA,SACAmoC,KACA,sBACA,eACAC,YACA,mBAEAC,mDACAF,qBAIAE,gDACAF,uBAGA,uBAGA,sBACA,uDAYA,qDAUA,gHAOAtxB,gCAUAA,yCAEA,eAGA,kDACAyxB,uBAKA,yFACA,qDAEAl3B,6CAGAA,gDAGAA,kBAEA,wBAEA,WACAA,cAEA,WACAA,aAEA,0DAIA,SAKA,kBAQAm3B,uDANA,kDACAA,qBAQAA,qDACA,oBACAn3B,qEAIAo3B,iDACAC,MACAC,4BAOAJ,uCAGAA,cACAK,6BAGA,0GAGA,GACAzxB,IACA,kCAWA,oBACA,qBACAL,0CACA+xB,mDAEA/xB,0DAEAK,cAIAA,aAGA,EAEAL,2EAEAA,2DAKA,WACAA,uCAMA,0BAIA,GAHA,cAGA,4FAIA,yEAkBA,uBAIA,GAHA,0BAGA,yFAKA,iCAGA,4CAkBA,uBACA,qCAGA,qCAGA,oFAaAgyB,iBAFAC,uBAOA,+DAeAC,OACA,YAKA,sEAGAC,WACA,UACA,sBAWA,wBACA,+BAGA,yBACA,YACAC,OACA,0BAEA,8BACA,uCAIA,eAQA,+HAOA,oDACA,kIAWA,kCACA,eACAC,uBAIA,qDADAlwB,WACApZ,+BAEA,8BAGA,EAEAspC,4CAEA,OACA,uDAEA,sCAYA,eACAC,0BAEA,eACAC,wBAGA,QADAluB,KACAtb,YACAsb,+CAYA,mEAEAiJ,8DACA,mDACA,iDAYA,eACAglB,0BAEA,eACAC,wBAEA,4CAIA,sCAUA,mCACA,2CAIAC,WAUA,0CAGA,QAFAllB,qCACA0kB,OACAjpC,wKAuBA,gEASA,kDASA,6CAQA,6BACA,sBAEA,EACA,IAGA,WAEA,cACA2T,mBACAA,2DACAA,gEACAA,yDACA,yBAkDAsD,mbAwIA,0DAEA,qBAOA,uFASA,4BACA/Q,sEASA,6BACA,cACA,6BACA,WAEA,yDAQA,+BACA,0IAYA,uBACA,kCAOA,mBACA,kDAIA,0BACA,gCAOA,iDAOA,4BACA,6DAGA,8DACAkb,SACAA,2CACA,kBACA,uBACAsoB,oDAOA,6DAGA,mCACAtoB,yBACA,kHAOAA,cAGA,2BAEA,mCACAA,4BASA,iCAKA,eACAuX,uBAGA,4BACA/X,6DAEA,oBAGA,kBACA,eACA,GAMA,kGAEA,8BAEA,MACA+oB,EACAnuB,UAGAouB,gCAEApuB,cACAmuB,cACA,4EAIA,mDAEA,sDACA1E,kCAEA2E,yBAGA,EACA,yBACAA,YAEA,yBACA,wBAQA,2BACA,iCACAD,cACAnuB,gHAGAquB,qBACAlC,cACA7D,0CACA6D,mGAGA,kDAGAvmB,oEACAA,iGAGAumB,UACAkC,MASA,8BAYA,QAVAP,gFACAQ,4EACArD,yCACAvU,8BACA0K,8BACAmN,cACAC,cACAC,8BACAC,8BAEAlqC,kDAEAumB,yCAGAvmB,QACAmlC,mHAKAnlC,MACA,SACAmqC,oCAGA,oCACAA,iCACA,uCAIA,+CACA5jB,qCAGA6jB,MACAC,QACA,4EAMAjpB,gCAEA,sDAIAgkB,sBAEAgF,KAEAR,mDAYA,kCACA,qFAYA,kCACA,kFAQA,uDACApuB,gCACA,0BAEA,oCAUA,8CAEA8uB,iCAEA,GADAC,KACAD,SACA,+CAEAC,kBAIAtzB,wCACA,CACA,IAGA,qCAIAA,gEAMA,wBACA,0BACA,mCACA,iCACA,iHAKA,8CAOA,WACA,2BACA,mBAEAoS,sBACAA,uBACA5B,4FAKA,kCAIA,WACA,6BACA,2DAGAxQ,2EAEAoS,uBACA5B,4BAGA,IAOA,gCACA4B,kCACAA,yDAEAjpB,kBACA,EAEA,2CAQA,6FAQA,iIAUA,wCAGA,kBAEA,EAEAA,sEAGAoqC,aACApqC,4BAKAA,6CACAA,8CAIA,mBAEA,iCASA,WAEA,sBACA,mCAEA,kIAQA,gEAIA,4BACA,6BACA,2CACAqnB,4GASA4B,4IAIA,mCACA,mCAEA,6BAGAohB,MACAphB,uEAWA,iEAEA,6BACA,iIAiBA,+CAIA,qCACA,gDAKA,6CAKA,YAQA,8CAIA,qCACA,4GAUA,YAQA,iCAGA,2DAKA,YAQA,0GAQA,YASA,iCAOA,QANAqhB,aACAxkC,iCACA6pB,OAEA4a,cAEA,kCAEA5a,OAEA,oCAUA,uBACAuZ,4FAIA,sBACA,oBACA,6BACA,uBACA,gCASA,uBACAA,4FAIA,6BACA,oBACA,6BACA,6BASA,8DAuBA,OAlBA,cACA,gEAIA,kBAEA,2BACA,gEAEA,uBACA,yBACA,wBACA,+BAEA,aACA,6BACA,6BACA,aAGA,uDACA,4BACA,2CAIA,gCACAjgB,yDAEAjpB,cACAA,aACAA,eAEA,oCAQA,oDAMA,wEAMA,wHAGAwqC,sBACAC,oEAIAD,gBAIAE,oCACA,qDACA,sBAGA,sBACA,qDAEA,kDACA,6BACA,6BACA,uBACA,+DAQA,wBAEA,cACA,yDAGA,wLAUAC,wCACA,oEAIAC,wCACA,gIASA,wFAKA,sEAQA,GADA,0BACA,sBAGA,6BACA,+LAIA,8DAOA,yBAGA,+DAEA,oCACA,sBACA,kBAEA,yCACA,oJAEA,yBACA,sCAEA,8GAQA,gJAWA,gCAGA,uEACApB,+BACAqB,8BACAtB,cACAnuB,cACA0vB,4DACAjG,eACA7V,6BACAzV,GACA,kCAGAwxB,iCACAC,4BACAC,YACAC,aACAC,MACAhF,MACAtsB,kBACAC,mBAEA,oCACAP,yDACAA,OACAA,OACAA,QACAA,OAEAA,QACAA,OAEAA,QACAA,OAEAA,QACAA,kEAOA,0GAQA,6BACA,6BACA,iCACA,iCACA,6BACA,8HAGA,mCAOA,8SAWA,2LAaA6xB,sBACA,wBACA,kBAEA,2DAIAA,2CAEA,yBACA,4BACA,4BACA,6BACA,oCACA,sBACA,kBAEA,qDAEA,cACA,oDACA,sDACAC,+FASA,6CAEA,uBAUA,sGAGAC,cACAC,cACAC,cACAC,kBAEA,UAEA,kBACA,0EAKA,kBACA,yEAGA,oCACA,yBAKA,mBACA,0DAOA,+DAIA,qDAIAC,mBAEA,eAYA,mDAIA,+CAEAC,MACA,8BAEA,kMAUA,qEAeA,gBAGAC,yCAEAC,mCAEA,iBACAC,iFAMAC,YAEAC,6DAOA,SAaA,IAZAC,wCAYAJ,gDAKA,sDAOA,kEAWA,cACA,iDAKAK,SAGA,qCAEAC,2BAIA,gBAIA,sCAGA,gEAMA,6BAEA,cAMA,QADAC,aACAA,QACA,8DAcA,sEACAC;AAAA,OAEAC,QAGAA,OAIAA,SACA,2DACAC,sBAEAC,iCACAC,gCACA,oBACAH,OACA,sDAOA,mCACA,oCAGAC,qBAGAD,QACA,kGASAI,MACAlQ,MACA,gCAEA,qCACA,gCACA,qBAEA,gCAGA,mCACA,oBAGA,uBAKAA,MACA,iCAEA,oCACA,iCACA,uBAEA,iFAMA,sBACA,sBAEA,wBACA,uBAEA,oBACA,oBAEA,sBACA,qBAGA,EACA,IAGA3lB,+IAYA,6DASA,wBACA,gDAIA,gBACA,yEAIA,8CACA,yCACA,qBACA,oCACA,oCAGA,0LAUA,2IASA,4BACA,0BACA,mBAMA,+BACA,iBAGA,yDAMA,+BACA,iBAGA,gLAmBA,yFAKA,sBAEA,gBACA,sDAIA,iBACA,8FAEA,4BAEA,kCASA,4VA4BA,8BACA,8FAGAzF,4BAIA,iDAEA,eAIA,4CAKA,iBACA,sFAGA,2BAGA,gCAIA,mBAQA,kHAGAsiB,sDAIA,sBACA,qBAEA,iBACA,6BACA,yBASA,+FAOAkR,EACAqE,oCAEAxwB,WACAA,2CAEA7Y,kGASA2Y,qCAMA,yBACAo0B,kCAEA,iCAGAp0B,mDACAA,QAJAvH,QAWA,wDAMA,oDAEA,YACA47B,QACAjgB,OACAigB,QACAlC,MAEA,oBACAA,6BAIAA,uBAKA,GAGA7zB,sEAMA,uYAOA,mCAGA,oEACA,wGACAsN,eAEA,2FAIAtN,82BAeA,mCAeA,yMAaA,4MAgBA,mCAQA,sGAcA,sBACA,oBAGA,2DACA,kBACA,8BAEA6c,0DACA,6CAGA,QAEAA,6BACAA,mBACAA,8BAEA,0BACA,uBACA,8EAaA,oBACA,4DACA,kBACA,OAEA,2DACA,2CAGA,QAEAA,6BACAA,gEAQA,oBACA,qBAGA,GAFA,kBACAA,uBACA,iBAIA,wEACAmZ,oBACAC,eAEAC,gDAEAC,QACAT,yCAEA,eACA,0BACA,qBACA,cACA,+CACA,gCAEA,OAGA,yCACA,mCACA,iCACA,yBACA,0BAIAU,wBACAF,QAEAD,QAEAG,0BAGAA,2BAGAZ,2CACAY,cACAZ,WAIAE,oCAEAA,mBAGA,WACA,mBAQAW,uBAKAC,2CAIAd,WACAe,yDACAb,sDAIA,0BACA,qBACA,cACA,+CACA,gEAOA,uDAOA,2BAMA,wHAGA,6HAcA11B,wBAIAA,uBAHAA,oFAKA,qCAQA,mBAQA,8BACA,mDAUA,uEAGA,aACAxP,kDAYA,yEAEAwjC,8BACAtB,oGAMA,kFAGA8D,8BACA,kDAUA,qCACA,8DACA,kBAGA,qBASA,uEAEAxC,8BACAtB,cACA,6CAIA,kFAGA+D,sHAWA,8BAOA,6BAJA1I,iCAEA2I,QAEAv8B,uBAGA,GAFAw8B,qCAEAC,UAEA,8CAKAF,YACA,iBAMAA,iBAWA,6IAWA,yBACA,kFAWA,kCAGA,6BACA5gB,gDACA+G,WACA,4BAGA,+BAEA/G,QACA,gCACA,4BACA,6BACA,yBACA,6BACA,yBAQA,gCACA,wCACA,sBACA,oBACA,mFACAA,OAOA,mCACA,YACA,uBACA,wCAGA,qBACA,uCAEAA,OAOA,2BACA,mHAYA,YACA+gB,8CAEAha,0CACAga,0CAGA,oCAGA,6BACA,qBAQA,uDAOA,yDAQA,uCACA,SACA,uCAIA,yGAIA,yCAQA,oCACA,uHAGA,2BACA,2EASA,kJAYA,iEAEA,6BAEAha,iDAOA,4BACA,yBACA,6BACA,yBAQA,qCACA,kKAIA,2EASA,wCACA,SACA,uHAIA,uCAGA,yCAYA,0BACA,eACA8I,mCAGA,yBACA,mDAEA,oCACA,sBACA,kBAEA,8DAgBA,oBAGAA,iCAGA,qEAEA,kEACA,mDAEA,oCACA,sBACA,kBAEA,+BAGA,GAIA,WACA,8BAGA3lB,yDAQA,mCACA82B,8CACA,kCAQA,iEAGA,oCACA,oCAOA,OACA,uBACA,uBACA,+BACA,GAMA,yEAGA,OACAA,uBACA,gCACA,0EACA,kDACA,qDACA,wFAEA,6DACAA,qBACA;AAAA,CACA,GASA,6CAGAl1B,MAEA,6FAKA,mEACA,kCAEA,+DAIA,gCAGA,yCAOA,mGAIA8W,0CAEAqe,uBAEA,4EAKA,UACA,gFAMAvH,yCACAC,EACAC,eAIA0C,qBACAxC,EAEAoH,4GAGA/G,kCAEA3B,gCAEAA,YAGAA,iBAEAkB,OACA,2CAMAC,2CACAC,0CACAE,sCAGAtiB,qCACA2pB,8DASA,gFAGA,WACA,2BACA,OACAzrB,OACA,QACAA,OACA,YACAA,OACA,aACAA;wCAWA,mFADA4iB,uDACAj0B,iDAEAk0B,uDACAA,OACAD,gCACA4I,OACA9I,SACAI,eAIAA,iBAGAD,gCACA2I,QAWA,6EAEA,2CACA,8EAQA,iCAEA,wFAIA,oGAGA,GAQA,yBACA,mDACA,8BAEA,EACA,gBAQA,8BAaAh3B,sJA+CA,uJAuBA,gEAIA,uBACA,mBAEA,uBAEA,kIAKA,wCAEA,kHAcA,8BAMA,0DACAk3B;AAAA,wGAWAC,2FAcA,wFAIAzE,UAGA,iDAQA,0BACA,yBAGA,uBACAyE,8CAEAzE,SACA5c,gBAGAshB,SACAC,QACAC,6DAGA,iCAEA,2DAgBA,kHAMA5E,SACAnuB,6HAaAmuB,SACAnuB,kCAUA,8DAEAmuB,SACAnuB,uCAYA,+EAWA,0EAcA,wBACA,WAEA,IADA,mBACAxb,wDAGA,yEAgBAwuC,OACA,2EAEA71B,iBACA81B,qDAgBAC,wGAOAC,4BAKAC,gCACAC,OAEAC,cACAA,gBAGA,sEAGAC,2BACAhiB,YAEAiiB,SACAA,SACAC,8BASA,QACA5F,wBAIA6F,0CAIAH,yFAmBA,2GAiBA,iCACA,2DAaA,gCAIA,QAHAzG,oDACA2G,2DAEAjvC,mBACAmvC,mBAEA,iBACA7G,4CAKA,wFAIA,SACA,4BACA,qBACA8G,6BAGA,yBACAA,MACA,uBAWA,qBACA,2EAEA,sCAUA,8CAEA9E,iCACA,iDACA,MAIA,WAEA,sBACA+E,gCACAC,4BACAC,mBACAC,uBACAC,uBACAC,wDAyEA,qFAhEA,oFAQA,oFAQA,qFAQA,uEAOA,sEAOA,sEAOA,qEAOA,kCAKA,qCACA,2FAIA,GAEAz4B,WAMA,sCAEA04B,YACAA,UACAA,UACAA,UACAA,UACAA,UACAA,uCAKA,sEAGA,iCAKA,sEAGA,GAEA,UC/88BA14B,kEACAA,wEACAA,gDACAA,iDACAA,iDACAA,iDACAA,gDACAA,yCCNAA,2EAEA,cACA,cACA,yBAIAzF,UAEA,0BAEA,mBACA,oBACA,cACA,WAEA,kCACA,oBAEA4P,mMACA,gBAEA,WACA,gBAEA0O,iDACA8f,+CACAnoB,yEAGAggB,2KAGA,iBACA,EACA,gBAEA,iCAEA,GAEAxwB,yCACAA,uCACAK,8BAEA,EAEAL,0CACA,oBACAA,uCACApV,8BACA,GAIAoV,0BCzDAA,qFACA,cACA,yBAGA,yBACA,iBACA,wBACA,EAEAzF,QAEA,mDACA,GACA,wBAEA,sBACAkyB,mBACA,iBACA,aACA,aACA,EAEAxxB,EACAkP,+CAOAA,8BACA,EACA,oBAsBA,gCAEA,GCpDA,YAEA,aACA,aACAiI,mDACA,gBACA,aAEA,uBACA,uBACA,GAGAA,8FACAA,cACA,EAGAwmB,eCzBAC,6CACA,uBACA,+DACA,gCACA,WACA,UACA,UACA,EACA,mBACA,UACA,UACA,CAEA,ECSAC,4BACA,gBACA,eACA,6BACA,WACA,gBACA,2BACA,QACA,QACA,EACA,UACA,YACA,iBACA,GACA,SACA,4BAMA,iCACAp3B,mCACAE,YAEA,4BACA,sHACA,qCACA,yBAGA,0FACA,mBACA,EAEA,SACA,OAEA,cAEA,wBACA,yBACA,aACA,qBACAwQ,uBACA,EACA,OAEA,cAEA,0BACA,2BACA,aACAA,SACA,EACA,6BAEA,cAEAA,oBACA,IAEAhY,aACAgY,YACAA,wBACAA,qBAEA,EACA,EACA,kBAEA,uBACA,iBACA,gBACA,kBACA,sFACA,8BAGA,uBACA/R,OACA,EACA,YAEA,cACA,0CACA,qCAEA,iBACA,yFACA,0FACA,qDACA,QACA,CACA,GAGA,0BACA,kDACA,CAEA,GClGA,eACA,eACA,4CACA,CAEA,UC7BA04B,mDAEAC,MCHAC,MAGAC,2DAGAC,qCAEAC,MCRAC,MAkBAC,cACA,oBACA,EAEAC,MCrBAC,QAUA,eAGA,QAFAvqC,WAEAA,4BACA,QACA,CAEA,UClBAwqC,MAGAC,UASA,eACA,UACA5+B,iCAEA,CAEA,UClBAmE,MAGA06B,aAEAC,MCLAC,MAGAC,oBAGAC,qBAOAC,eAGAC,4BASA,eACA,oBACAviC,QAEA,IACA1F,aACA,QACA,QAEA,iBACA,WACAwB,EACAxB,QAEA,cAGA9I,CACA,CAEA,UC5CAgxC,oBAOAC,eASA,eACA,iBACA,CAEA,UCrBAC,MACAC,MACAC,MAGAC,mBACAC,wBAGAC,4BASA,eACA,eACAzoC,iBAEAyoC,oBACAJ,MACAC,KACA,CAEA,UCHA,eACA,kCACA,CAEA,UC5BAI,MACAC,MAGAC,qBAmBA,eACA,2BACAD,gBACA,CAEA,UC5BAE,MACAC,MACAC,MAGAC,OAGAC,wBAGAC,gBAGAC,iBAGAC,YAyBA,eACA,sBACA,SAEA,SACA,UAEA,UACA,iDACAppC,cACA,CACA,sBACA,kBAEAA,QACA,iBACA,qBACAopC,qBACAH,gBACA,CAEA,UC/DAI,MACAC,MACAC,MAGAC,yBAGAC,YACAC,YAwDA,mBACA,MACAC,EACAC,EACA1yC,EACA2yC,EACAC,EACAC,IACAC,KACAC,KACAC,KAEA,wBACA,wBAEAC,WACAd,QACAW,cACAC,gBACAL,6BACAM,iCAGA,cACA,QACA1yC,IAEA,kBACAuyC,IACA7yC,eACAA,CACA,CAEA,cAEA,WAEA2yC,kBAEAG,QACA,CAEA,cACA,UACAI,MACAC,MAEA,SACAX,UACAW,CACA,CAEA,cACA,UACAD,MAKA,yBACAE,YACA,CAEA,aACA,WACA,QACA,YAGAT,oBACA,CAEA,cAKA,OAJAA,SAIAK,KACAK,MAEAC,WACAtzC,EACA,CAEA,aACA2yC,YACA,gBAEAE,IACAS,cACA,CAEA,aACA,2BACA,CAEA,aACA,WACAC,OAMA,GAJAD,YACAb,OACAG,IAEAW,GACA,cACA,YAEA,KAEA,uBACAZ,kBACAU,IAEA,CACA,oBACAV,mBAEA3yC,CACA,CACA,kBACAwzC,UACAA,CACA,CAEA,UC5LA,cACA,mBACA,yCACA,+EACAC,MAGA,4CACAC,GACA,CAEA,cAEA,sCACAC,4BACAA,0BACA,6BAGA,sCACAA,iBAGA,oCAGAA,cACAA,4BAGA,sEACA,+hRCjCA,i5BCGAC,cACAA,cCaA,mBACA,iCACA,0CACA,iCAEA,CCtBA,gCACA,eACA,aACA,kCACA,GCEAC,QACA,0DACAC,YAGA,iCACAA,mBAGA,qBACAA,aAIA,+CACAA,SAGA,2BACAA,CACA,EAEAC,QACA,oDAIA,OADA,2BACAC,oDACA,gDAEA,CACA,ECpCAC,+DACA,0CAEA,ECHA,cAEA,WACA5iC,4BACA,uBACA,EAmDA,gCAhDA,IACA6iC,EAgDA,kBA7CAC,IACA,4GACA,6EACA9iC,aAEA6iC,0BAyCA,gBANAliC,GACA,iCAMA,MAvCA,KACA,4DACAkiC,IACAA,UACA,oDACA,kDAmCA,KAhCA,IACA,oBACA,MAOA,GANAA,gDACA,kFACAxyC,OAGA,4CACAwyC,uBACAA,SACAA,OACA,+CACA,OAGA,qEAGArxC,GACA,EAaA,CAEA,CC7CA,mCACA,eACA,iBACA,qBACA,wBACA,wBACA,wBACA,uBACA,uBACA,oBACA,GACA,WAEA,SACA,sBAGA,GADA,6DACA,oFAGA,QADA+sC,qBACA,kDACAwE,0BACAC,uCAGA,qDACA,sLAEA,cACAC,gCACA16B,mCAEA,oBAEA,8DACAA,8BACA,iDAEA,uFAEA,2BACA26B,wDACAH,0BACAI,uCAEAC,mBAGAC,gCAGAC,iBAIAA,eAIA,iCAGAD,4BAGA,yCAGAE,aAGAH,oCAIA,QADA,wCACA,kBAGAI,yCAEA,aACAC,uBAEA,gEAEA,IACA,iCACAC,+FAEAC,2CAGAF,mBACA,cACAC,gGAEA,2CACAE,6CAGA,8BAEA,iDAEA,8BACA,EAEA,6BAEA,gEAEA,8CACA,0CAEA,oEACA,wBAEA,0BACA,yDAEA,0BACA,iCAEAC,eACAC,yCACAD,4CAEA,uBACA,MACA,EAGAE,IACA3yC,wCAGA,yCACA,8BAGA,QADA,kBACAy8B,EAEA,kFACA,CAGA,GCnKAmW,QCAA,kHAMA,mBACA,UACA,OACA,WACA,sBACA,6BACA,CACA,0BACA,CAyBA,cACA,0FACA,CAEA,mBACA,yBACA,EAGAC,GAEAC,6CACAA,qCAEAA,iCACAA,6BAEA,qDAEAC,eACA,IACA,WACA,OACA,QACA,CACA,EAGAC,kBAEA,mEACA,GAGAC,2BAEAC,mCAGAC,yBAIAC,kBACA,iBACA,uBACA,KAEAC,IACA,IACA,EAEAC,iBACA,OACA,kBACA,oBACA,gBACA,OACA,CACA,EAEAC,eAEAC,eACA,6BACA,EAEAC,YAGAC,iBAGA,0CACA,eACA,8CACA,SAIAC,eACA,sDACA,QACA,EAMAC,eACA,gBACA,EAEAC,eACA,uDACA,EAMAC,iBACA,mBACA,QAGA,GAFAC,uDACA,mDACA,gEACA,0DACA,EAIAC,eACA,oBACA,EAEAC,qBAEAC,iBACA,uBACA,EAEAC,eAEAC,gCAEAC,eACA,gCACA,EAGAC,uBAEA,4CACA,wBACA,OACA,GAGAC,mCAIAC,uBAGA,GAFAC,QACAC,WACAJ,OACA,cACA,QACA,0CACA,EAEAK,IACA,IACA,EAEAC,eACA,UACA,+CACA,QACA,EAGA1sC,yBAIA2sC,yBAIA,GAHAD,MACAF,WACAE,MACAN,OACA,gBACA,QACA,mEACA,kCACAG,CACA,EAEAK,IACA,IACA,EAEAC,sBACA,wBACA,kBACA,cACAhkC,CACA,EAEAikC,iBACA,IACAD,UACA,OACAlC,OACA,SACA,EAEAoC,wBACAC,qBAEAC,MAEAC,qBAGA,sCACAD,6BACA,iBACA,GAGA,wBAEAE,cAEAC,qDAIAC,mBACArxC,wBACA,qCACA,wBACA,iBACA,cACA,mDACA,EACA,GAEA8d,KACAwzB,iBAEAC,eACA,mEACA,EAEAC,cAEAC,eACA,2BACA,EAEAC,MAEAC,gCACAC,cACAC,SAEAC,eACA,2BACA,EAEAC,eACA,mBACA,MACA,8BACA,yDACA,QACA,CACA,EAEA,iBACA,mCACAC,UACAC,UACAC,UACAL,iBACA,yCACA,kBACAK,gBACAC,CACA,EACAC,eACA,wBACA,EACAC,eACA,oBACA,CACA,MACA,mBACAX,UACAG,iBACA,oCACA,kBACAhB,WACAsB,CACA,EACAC,eACA,wBACA,EACAC,eACA,eACA,CACA,CAEA,QACA,OACA,OACA,OACA,WACA,YACA,EAEAC,kBACA,aACAC,aACAC,kCAEAxyC,4BACA,sBACAyyC,sBACAC,uBACAC,EAUA,GATA,uBACA,mCACA9B,eAEA8B,OACAA,WACAA,2CAGApC,QACAkC,SACA3B,QACA,MACA,QAEA,WACA2B,MAFA,YAIAA,SACA5B,SAEA,4CACA,wDACA,EACA,GAEA/4B,MAEA86B,eACA,oCACA,EAEAC,iBACA,+CACA/6B,gCACA,EAEAqjB,aACA2X,cAIAC,eACA,mCACA,EAEAC,YAIAC,eACA,uCACA,EAEAxxB,YACAI,YAKAqxB,iBACA,YACA,4BACA,EAGAC,eACA,uBACA,YACA7xB,eACAliB,UACA+C,EAGA,sBAGA,GAFAA,SAEAA,kBAEA,cACA,wCACA,YACA,CACA,EAEAixC,IAGA,gBAGA,cACA,EAEAC,cAGAC,iBACA,YACAp6C,IACAG,KACAY,EACA,yCAEA,kCACA,qBAEA,QACA,EAGAs5C,IACA,cACA,iBACA,gBACA,uBACA,iBACA,WACA,SACA,EAEAC,mCAKAC,2CACA,eACA,EAEAC,IACA,IACA,EAGAC,gCAEAC,IACA,IACA,EAGAC,wCACA,kBACAC,OACA,yBACA,EAEAC,iBAIA,QAHA71C,QACA81C,OACAC,OACA/6C,oBACA,WACA82C,sBACA,CACA,EAEAkE,qBAEAC,iBACA,gBACA,gBACAhyC,SACA,2BACA,GACA,EAEAiyC,4BACA,8CACA,EAEA33C,cACA43C,iBACAC,mBAEAC,MAEAC,QAqBAC,iBACA,eACAC,WACAC,SACAC,YAQA,GAPAF,EACA1zC,KACA2zC,EACA3zC,kBAEAA,wBAEAA,cAQA,GAPA6zC,OACAnqC,eACAoqC,UACAC,cACAA,OACAH,mCAEA,gBACA,+BACAb,OACA,EAEArpC,oBACAmmC,gBAGAyB,WACA,CACA,EAEA0C,eACA,wBACA,gDACA,QACA,EAGAC,mBAEA,GADAD,MACAn0C,oBACA,UACA,yBACA,gBACA,EACA,0BACA,kBACA,EACA,4BACA,oBACA,EACA,8BACA,sBACA,CACA,CACA,kBACA,2BACA,CACA,EAKAq0C,8BACA,qBACA,EAEAC,mCAEAC,cACAC,mBACAC,aACA19B,MAEA09B,IACA19B,iBACA29B,0BACAJ,KACAv9B,4BACA,kBACAA,6BACAA,iBAIA,eAOA49B,kDACA,yBAGA,uBACA,GAKAC,OACA,cACA,iCAEAC,aACAC,aACAC,kCAEAC,eACA,mDACAL,aACAE,YAEAA,uBAEAA,KACA,EAEAI,iBAIAC,iBACA,MACA,eACAC,gBAEA,4DACArG,QACAqG,QACAA,uBAEA,kCACA,EAEAC,WAGAC,eACA,WACAC,OACAC,OACAC,OACAC,OACAC,OACAC,UACA,yBASA,QARAjG,QACAkG,QACAC,YACAp1B,eACAliB,IACAu3C,QACA31C,8BACAmB,IACAmf,yBACAnf,OACA9I,WACAu9C,GACA,oBACAv9C,YACA,gBACA,gBACA,gBACA,mBACA,gBACA,gBACA,mBACA,CAGA,oBACA,CACA,EAEAw9C,IAGA,cAGA,UAGA,aAGA,WAGA,YAGA,WAGA,gBAGA,eACA,EAKAC,iBACA,YACA,yBAEAr8B,qCACA,EACA,EAGAs8B,cAGAC,iBAIAC,MAGA,WAHA,YACA,wDAEA,EASAxC,oDACA,UACA,GAQA,QACA,cACA,sBACA,eACA,iBACA,cACA,gBACA,eACA,uBACA,WACA,oBACA,iBACA,kBACA,oBACA,YACA,gBACA,eACA,WACA,mBACA,SACA,cACA,gBACA,gBACA,iBACA,eACA,gBACA,mBACA,mBACA,iBACA,mBACA,gBACA,WACA,EAEA,kBACA,cACAyC,oBAEA,2BACArG,mBACA,OACAqG,aACA,CACA,CASA,gCACA,eACA,EAEAC,QAGAC,eACA,mBAOA,QANA7G,QACAryC,QACAojB,WACApoB,IACAG,KACAY,EACAqnB,KACArnB,UACA,oBACAZ,wBAGA,QACA,CACA,EAEAg+C,IAGA,eAGA,aACA,EAEAC,cAIA7C,8BACA,oBACA,YACA,CACA,GAMA,mBACA,oBACA,0DACA,QACA,EAUA8C,sDACA,SACAC,KACAC,EACA,IAEAA,oEACAA,aACAC,oBACA,QACA,qBACA,aACAC,MACAD,cACAnH,cACAA,CACA,CACA,YAGAqH,mBACA,QACA,OAEAL,IAEA,qCACAM,OACAlI,mBACAmI,iBACAP,QACAQ,CACA,EAKAC,4CACAtH,MAKA,QAJAxyC,QACAojB,WACAliB,IACAnF,EACAqnB,2BACA,QACA,EAEA22B,oCAEAC,OACAC,OACAC,eACAC,YACAC,kBAEAC,gBAEAC,eACA,8BACA,EAGAC,eACAC,gBACAA,UACA,4BACA,cACAC,CACA,EAGAC,cAEA,mBACAC,gBACAC,EACA,8BACAb,kBAEAc,gBACAD,2BACAA,SACAA,iCACAA,UACAA,GACA,EAOAJ,GACAM,cACA,IAEAN,iDACA,QACAM,kBAEA,QADA13B,YACAA,0BACA,WACA,EAEAowB,UAIA,oCACA,MACA,iBACA6G,aACAl/C,SACAk/C,YAEAl/C,SACAA,OACA4/C,oBACA,EAGAC;AAAA,yHAGAC,cACAC,yBACAC,sBAGAC,eACA,mBACA,oBACA,iCACA1C,0BACA3rC,CACA,CACA,EAEAsuC,IAGA,YAGA,UAGA,UACA,EAaAC,QACAvF,QACAwF,QACAC,WAEAC,YACAC,UACAC,gBAGAC,kBAIAC,eACA,eACAt2C,gBACA,mCAGA,GAFAu2C,QACAv2C,kBACAA,gBAEA,GADAw2C,kBACAA,mCACAx2C,QACA,wBACA,+BACA,gCACA,gBACA,CAGA,IAFAy2C,aACA54B,WACAliB,YAIA,GAHAvE,kBAGAA,qBACA,oBACA,EACA,QACA,EAIA,+CASA,QARAs/C,eACA,6BACAC,OACA,yBAEAN,iDACAlC,4BACA,EACA15C,aAEA,8LAMA,qCACA8xC,8BACAyJ,oBAGAU,gBACAN,kBACAvH,YACA,CAMA,yBACA+H,mBAIAA,cACAzJ,YACA,gBACA,cACA,GAIA,mBACAyJ,YACA,EAIAC,eAKA7F,8BACA,qBACA,wDACA,CACA,GAGA8F,eAMA,eAGA,mEACAC,eACA,eACA,EAEAA,eACA,mGACA,EAGAA,KACA,CAiCA,kBACA,qCACA,0CACApzC,eACA,qEACA,CACA,QACA,EACAqzC,wBACA,EAEA,iBACA,SACA,2EACA9oC,WACA,4DACA,6DACAqb,wEACArb,iBAEA,QACA,CA4LA,QAKA,UACA,qBACA,WACA,EAMA,OACA,YACA,iBACA,sBACA,0DACA,CACA,EAMA,MACA,YACA,iBACA,sBACA,0DACA,CACA,EAKA,QACA,aACA,WACA,EAQA,MACA,YACA,YACA,sBACA,qCACA,CACA,EAMA,OACA,aACA,WACA,EAMA,KACA,YACA,WACA,EAOA,WACA,aACA,WACA,CACA,EAEA+oC,OACA,iCACA,oBACA,MACA,YACA,aACA,WACA,CACA,GACA,oBACA,aAKAC,gBACAnmB,QACA,sBAEAomB,OACA,qBAEAC,QACA,sBAEA,QACA,GACAC,UACAC,gBACA,QAEAC,sBACAC,sBAEA,mCACAD,8DACAC,+DAGA,CACA,QACA,OACA,CACA,GAEAC,cACA,UAEA,MACA,WAGA,QAFAC,aAEAjiD,mBACA,0CACAiiD,yFAIAl8B,UACAA,iFAIAm8B,cACA,CACA,EAEAC,cACA,UAEA,MACA,WAGA,QAFAF,aAEAjiD,mBACA,0CACAiiD,yFAIAl8B,UACAA,iFAIAm8B,cACA,CACA,EAEA,OACA,YACA,iBACA,qBACA,CACA,CACA,GAEApH,QAEAsH,sBACAC,eACAC,2BACAC,UAIA3M,iBACAkF,UACA,gBACA,eACA,IACA,iCACA,OACA,QACA,CACA,CACA,GAOA,yBACA,+BACA,KACA,eACA,gCACA,8BACA,GACA,sCACA,mCACA,GACA,WACA,IACA,sBACA,8BACA,GACA,GACA,gCACA,KACA,eACA,gCACA,8BACA,GACA,sCACA,mCACA,GACA,WACA,IACA,sBACA,8BACA,GACA,GACA,eACA,CAEA0G,aAEA,WACA,mBACA,YACA,0BACA,EACA,OAKA,UACA,qBACA,WACA,EAMA,OACA,YACA,iBACA,sBACA,mCACA,CACA,EAMA,MACA,YACA,iBACA,sBACA,0DACA,CACA,EAKA,QACA,aACA,WACA,EAQA,MACA,YACA,YACA,sBACA,qCACA,CACA,EAMA,OACA,aACA,WACA,EAMA,KACA,YACA,WACA,EAOA,WACA,aACA,WACA,CACA,EACA,kBACA,gBAEAgB,cACA,uBACA,EAEAC,gBACA,gDACA,GACA,OACA,QACA,iBACA,gBACA,CACA,CACA,GAEA,yBACA,oCAEA,6BACA,qBACA,IACA,sBACA,8BACA,GACA,GACA,cACA,CAEA,iBACAC,mBACA,iBAEA,8BAEA,+DACAn+B,kCACAA,kBAEAo+B,WACAC,aACAA,+BAKAA,iBAGAr+B,aACAA,uBAEAA,0CAEA,CAEA,y5HAEAs+B,OAEAC,aAEA,WACA,oBACA,YACA,0BACA,EACA,OAKA,UACA,qBACA,WACA,EAMA,OACA,YACA,eACA,sBACA,kCACA,CACA,EAMA,MACA,YACA,eACA,sBACA,iDACA,CACA,EAKA,QACA,aACA,WACA,EAQA,MACA,YACA,YACA,sBACA,qCACA,CACA,EAMA,OACA,aACA,WACA,EAMA,KACA,YACA,WACA,EAOA,WACA,aACA,WACA,CACA,EACA,kBACA,gBAEAN,cACA,uBACA,EAEAC,gBACA,gDACA,GACA,OACA,QACA,iBACA,gBACA,CACA,CACA,GAEA,yBACA,oCAEA,6BACA,qBACA,IACA,sBACA,8BACA,GACA,GACA,cACA,CAEA,0+GAEAI,OAEAjjD,aC56DA,wCCAAmjD,kCCAAC,0HCeAC,UACI,WACA,eACIC,uBAEJA,WAAyB,khECwD7BC,WACA,MAEA,eAEAC,4BAEAC,aACI,qEACA,WACAC,wBAAsBH,QACZ,uDACmE,EAE7E7nB,SACIgoB,SACJ,GAGJC,QACI,UACAD,WAAsB,GAG1B,qBAEAE,eAEAC,OACIvB,UACAwB,UAAiB,EAErBC,eACIzB,YACA0B,2EAAmE,EAEvEC,gBACAC,OACI5B,YACAwB,UAAiB,EAGrBK,UACI,SACA,eACIb,eAEJ5nB,yBACI4nB,kCAEJ5nB,gBACI4nB,2BAEJA,WAAyB,GAG7Bc,UACI,SACA,0BACId,gCAEJA,CAAO,GAGX,y3BCxIAR,2CCJA,2BAIA,2DAYA,2CASA,gBACA,wGAOA,gCACA38B,iBAEAvP,aAGA,iDAUA,sCAGA,kGAgBA9V,UAEAA,iBAKA,8DAMA,aAYA,kBACA,aACAujD,+BAGA,iBACAC,wBAEA,WAIA,GAEAC,kCAcA,qCAGA,SAEAC,gDAKA,OACA,+EAoBA,mDAcA,yEAsBAr+B,cAGA,SACAs+B,iEAMA,mFAIAC,UACA,6CAIAA,uCAEA,6BAMAC,WAGAA,WAEAC,2BAIAN,2BACAlkD,MACAskD,+CAGAzqC,UACAyqC,SACA,uCAMA,GAEAJ,gBACAO,MACA,GAGA1+B,eACA0+B,iBAOA,gBACA,oDASAC,EACAC,EACA,mBAEA,6BAEA,gBAKAC,MAEA,OACA,gBACA,mFAIA,KAIA,gBAQAl3C,QACA,YAEA,uDACA,qBACA,wBAIA0T,wBACA,6CAEA,uBACA,YACA,WACAyjC,qBACAC,6BAEA1jC,0BAGA,iCAIA,iBASA1T,2BAEA,6BACAq3C,iBAIAA,SACAA,QAEA,kBACA,kCACA7yC,KAEA,uBACA,wBACAA,wBACA,gDAKA,gBACA,mBAIA,YAEA,OACA,gBACA,wCAEA,MAGA,QACAyyC,EACA,OACA,cACA,mCAEA,MAGA,OACAA,EACA,MACA,wCAGA,MAGA,OACAA,EACA,MACA,yCAGA,MAGA,OACA,eACA,kBAKAK,GACAL,EACAA,EACA,iGAOA,+DACA,oBACAj3C,iCAIAA,SACAy2C,mDAGAc,MACAprC,gDAMAqrC,kBACArrC,UAIA,gBAIA,MAGA,gBAEA,MACA,gBACA,aACA1Z,OAEA,oEAEA,KAIA,MAGA,mBAEA,MACA,gBACA,gBACAA,kDAIA,KAIA,MAGA,QACA,2BACA,OACA,gBAEA,aAEA,gEAkBA4kD,CAEA,8oBC/bAI,OACA,iCAEAC,OACAC,OACAC,OAGAC,eAEC,GADAC,SACAJ,WAAkC,OAElC,iBACAI,WACAJ,UACAlQ,UACA,cAEAuQ,EADA3xB,SACA,cAEA2xB,mBACC,+BAA4C,uBACrC,iDACsD,mDACC,aACjD,GAGbp8B,UACAA,oCAA2C,GAC3CA,SACA,UACAA,cACAm8B,WACA,mBACA,wGAAmI,CACpI,EAGDE,OAEC,aACAC,OAKA,GAHA,oBACA,2BAEAC,+CACC,YAA0B,OAC1BN,eACA,OAGDO,SAAY,EAGbC,YAEC,cAGAC,GAAyB,CACxB,uBACO,oBACE,UACD,WACC,UACC,QACA,EACV,CACA,kBACO,kBACE,SACD,UACC,SACC,QACA,EACV,CACA,eACO,eACE,UACD,WACC,SACC,QACA,EACV,CACA,mBACO,kBACE,SACD,WACC,SACC,QACA,EACV,CACA,gBACO,eACE,UACD,WACC,SACC,QACA,CACV,EAGDC,GAA2B,CAC1B,wBACO,kBACE,SACD,WACC,UACC,QACA,EACV,CACA,uBACO,mBACE,UACD,UACC,UACC,QACA,EACV,CACA,eACO,eACE,UACD,UACC,UACC,QACA,EACV,CACA,yBACO,kBACE,SACD,WACC,UACC,QACA,EACV,CACA,wBACO,mBACE,UACD,WACC,UACC,QACA,EACV,CACA,gBACO,eACE,UACD,WACC,UACC,QACA,CACV,EAkGD,WAEA9Q,YACC+Q,IAAe/Q,cAEf+Q,KAGDA,GAEAA,wBAEC,wBACC,mBACC,QACD,GAGD,MAAa,OAEb,iEAEAC,OAAe,iDACkD,kDACC,UACrD,cACA,6BACW,6BACA,4BACD,GAIvB78B,SACA68B,kBACAA,QAAgB,EAEhB,EAGF,oDACC,cACA78B,cACApS,kCAAmC,GAGpCosC,oBACC8C,2BAA8B,mqCC/T/BC,OACAC,OAoBA,kCAlBA,KACI,YAAkB,OAElBnE,YACAkE,gBACA,0EAEA,wCACI,eACI,kEACA,yBAEJxC,wDACAwC,UACA,yEAA4E,MACzE,CAGX,kOCfA,OACA,2BAuBcE,6HACd,0DAEA,eACA,qCACA,CAmKA,iBACA,MACA,sBACA,WACA,kEACAptC,oBACA/Y,kBACA,uBACA2H,EACA3H,GACA,CAgDA,eACA,aACAomD,MACA,IAEA,EACA,CAEA,cACA,gBACAC,MACAC,WACA,EAYA,OACA,GAZAnmD,IACAmmD,SACA,iBACA,aACA,CACA,KACA,CACA,EAMA,MACA,QANAC,GACA,uCAMA,CACA,CAqTA,eACA,uCACA,CCnhBA,0BACAC,6BACAC,8BACwBN,oBAodxB,cACA,eACA,eACAO,UACA,GACAA,CACA,CAEA,eACA,aACA,eACAA,QACA,aACA,CACA,CAqGA,oBACA,qBACA3nB,+DACA,MACA,eACA4nB,OACA,KAEA,0BACAC,kCAEAA,oBACA,EACAC,OACA,WAEAF,IACAC,4BACAE,kBACA,uBACAF,+BAEAA,iBACA,EACA,aACAG,YACAD,CACA,CASA,UACA,OACA,OACA,OACA,QACA,QACA,EA2CA,oBACA,gBACA,WACA,iBACAjmD,WACA,qBACAA,YACAA,CACA,CACA,qBACA,cACA,SAEAmmD,wBADA,EAEA,CACA,WACAC,6BAEAC,gCACA,2BACA,aACA,cACA,eACA,GACAC,GACA,IACA,wBACA,WACA,sCACA,EACA,iBACA,WACA,uCACA,EACA,kBACA,mCACA,EACA,aACA,gEACA,EACA,aACA,mCACA,EACA,oBACA,gCACA,EACA,aACA,oCACA,EACA,oBACA,gCACA,EACA,iBACA,6DACA,EACA,UACA,wCACA,sDACA,CACA,EACA,CA2NA,oHACAC,6BACAC,kBACiBA,OAioDjB,6BACAC,gCACAC,mCACAC,yCACAC,sFACAC,WACA,uBACAH,cACAE,aACA,MACA,mBACAD,cACAC,aAEA,QACA,EACA,UACA,YACA,UACA,EACA,kBACA,MACA,aACA,IACAE,WACA,sBACA,MACAC,IACAC,2BACAA,cACAA,eACA,iBACAF,gBACAG,UACA,GAEA,YACA,MACA,OACA,8BACAD,sBACAA,kBACAE,kBACAF,qBACAA,SACA,EACAG,OACAL,aACAE,IACAA,WACA,EACA,OACA,YACA,OACA,QACA,UACA,CACA,CAuhEA,6BACAI,gCACAC,mCACAC,yCACAC,sFACAC,WACA,uBACAH,cACAE,aACA,MACA,mBACAD,cACAC,aAEA,QACA,EACA,uBACA,wBACAE,IACAvpB,4BAWA,OACA,cACA,MAZA,cACA,YACA,+BACA,SAGA,GAFA37B,sBACAmlD,+BACAA,EACA,iBACA,CACA,CAIA,CACA,6kBCptJA,6BAAyD,+BAC7C,WACE,GAKdC,OACAC,OACAC,OACAC,SACA3D,OAGAtjC,YACI,wBACA,iCACA,MAAgB,OAEhB,YACA,+BACAgnC,8BACAE,IACAlD,cAAiB,GAGrB,kBACI,UACAmD,IACA,UAEAnD,cAAiB,EAGrBoD,gBACI,cAEA5/B,mEACI87B,6DACA+D,GACI,UAER,EAIJF,OACI,iCACA,4CACIJ,iCACAA,mCACApvC,sDAEA,uCACAqvC,6BAAsD,CAC1D,EAIJE,YAEI,cACAtD,wBAEA,2BACIA,2BACI,+BAA4C,qCAClC,iBACG,iBACA,4CACkB,8CACC,gBACO,aACvB,GAGhBkD,QAIIQ,cAHAA,gCACAA,aAKJ9/B,SACAA,kBACAs/B,UACIQ,wBAEJA,YACA9/B,cACAxnB,GAAQ,CACZ,EACH,EAILunD,OACI,0CAEAC,qCAA0D,4BAChD,iBACG,iBACA,QACF,SACC,SACD,aACK,GAGhB,oBACAA,CAAO,EAoDXC,YACI,SAAoB,SACT,OACA,iCACqC,mCACC,YAC5B,CACjB,EAGJ,gDAIQX,oBACAA,8BACIA,eACAA,8BAGA,gBACI,YACA,SACAt/B,yBACAggC,YACAA,sBACAP,UAA0B,MACxB,CACV,aAGA,wCAA2C,EAC9C,EAWTS,OACI,cACA,yCAA8C,EAIlD,oBACI,SAA0B,GAG9BC,QAEIrE,mDAA4D,wxCC7NhE,aACAsE,OACA,wEAEA/G,KAEA,aAEAyC,OACA,gDAOAuE,SACAC,SAGAC,YACIC,SAEA1E,sBACI2E,UACA,yDACAC,kCACAC,GAAmB,EACtB,EAGLA,YAEI,GADAH,SACA,mBAAmC,OAEnC,cAEAxgC,iEACI87B,2DACA,WAGJ0E,WACAI,IACA,cACAJ,iBACAF,WACA,0DAEAxE,oDACA,UACA,KAEA97B,yBACAggC,YAEA,gBACIxD,cAAiB,GACpB,EAILoE,YACI,YAA+B,OAE/B,aACAhV,uCACAA,mBACA,cACA,uBACAiV,+DACAC,gBAAmD,EAGvDf,OACI,mCAAkD,4BACxC,iBACG,iBACA,SACF,oBACmB,sBACC,iBACZ,aACH,GAGhB,mBACAC,CAAO,EAGXe,OACI,YAA+B,OAE/B,mCAAwD,mCAC9C,iBACG,iBACA,SACF,oBACmB,sBACC,aACf,GAGhB,mBAEAf,CAAO,EAGXC,YACI,SAAoB,SACT,OACA,iCACqC,mCACC,YAC5B,CACjB,EAGJ,gDAIQX,oBACAA,8BACIA,eAEA,UAEA,cACAt/B,yBACAggC,YACAA,sBAEAK,UAA2B,CAC/B,aAGA,wCAA2C,EAC9C,EAWT,oBACI,SAA0B,GAG9BF,QAEIrE,mDAA4D,o1BCjLhE,aACA,4BAEAkF,MACIC,UACA,wDAA2D,sqBCT/D,aACA,iDAEAnF,OAEAoF,YACI,cACA,gEACA,YACIlhC,oCACI87B,8BACJ,GAGJgF,gBACAA,sBAEAG,aAEAzE,SAAY,EAGhB,eACIsE,4BACIA,cACJ,GAGJX,QACIW,6BACIA,gBACAA,sBACJ,yUCrDJK,qCCAAC,mCCAAC,sOCwBA,cACArF,OACA,SACAF,OACA,wBAEAwF,mBACA,OAAa,IACN,GACA,EAGP,aAEI,6BAAwD,uBAC9C,UACC,YACG,oBACE,eACA,eACN,0CAC8C,yCACC,mBAC1C,gBACF,GAGbC,6BACI/rC,mBAAgC,GAGpC+rC,2BACI,wBACA,uBACI,iBACAC,iBAEAA,qBAA4B,CAChC,GAGJD,mCACI,0BACAxqD,aACIA,cACAA,UACAA,0BACAA,WACAA,cACAipB,cACJ,GAGJuhC,kCACI,0BACAxqD,cACIA,SACAA,WACAA,cACAipB,cACJ,GAGJA,QAAsB,EAG1Bk8B,UACIH,UAGA,QADAtxB,SACA,IACAqxB,iDACAluC,mCACI,yCAAiD,KAC1C,yBACG,8DACsF,GAIhG6zC,YACAzhC,qCAA+C,EAClD,EAILq8B,OACIr8B,oBACI,IACAhY,sEACIgY,WACJ,GAEJA,oCACAw8B,SAAY,EAGhB,sBACIM,4BAEA4E,GAAW,oqBCnHf,aAEA,WACA,oBAGA,eACEC,GAAW,0CACgC,uCACD,EACzC,mICjBH,cACA,yDACA,oCACA,mBAEA,eACA,4CACAljD,UAGA,CAEA,QACA,EACAmjD,wBACA,CAEA,kBACA,SAEAnvB,KAEAj6B,aACA,MAIA,MAEA,+BACAi6B,OAEA,EAEAovB,cACA,OACApvB,UACA,MACA,CAEAqvB,GACA,EAEAC,GACA,oBACA,QACA,EACA,UACA,SACA,MACA,CACA,EACA,QACA,EAEAC,mCACA,cACA,WACA,OACA,kBACAD,WACA,EACA,gBACA,gBACA,EACA,uBACA,4BACAD,gCACA,EACA,EACA,kBACA,eAIA,oBACA,4BACA,iCACA,GACA,EACA,oBACA,eAIA,oBACA,4BACA,mCACA,GACA,EACA,8BACAE,mEACA,aAEA,EACA,wBACA,iBACA,gDAEA,CACA,CACA,CACA,YAEA,oBACA,wCAGA,WACA,oBACA,OACA,SACA,YACA,WACA,EACA,OACA,WACA,EACA,OACA,WACA,EACA,MACA,WACA,EACA,MACA,WACA,EACA,UACA,WACA,EACA,qBACA,aACA,UACA,EACA,mBACA,YACA,4BACA,EACA,eACA,YACA,wBACA,EACA,UACA,YACA,UACA,CACA,EACA,4CACA,oBACA,cACAnJ,SACAhsC,WACAo1C,WAEAC,cACArJ,aACA,EAEAsJ,aACAtJ,YACA,EAEAuJ,aACAvJ,UACA,EAEA,qBAGA,GAFAwJ,wBAEApwB,uBACA,+CAEA,uCACA17B,yBACAA,iHACAA,WACAA,WACA,4BACA,CAGA,eACA,WACA,qBACA,kBACA,GAEA+rD,UACAhkC,4BACA+jC,0BACAJ,UACApJ,aACA,EACA,GACA,CACA,OACA,WACA,iBACAwJ,iBACA,EACA,mBACAA,mBACA,CACA,CACA,EACA,kBACA,0BACAE,EAEA,4BACAA,MAEAA,IAGAhjC,UACA,UACA,IACA,CACA,GC7NO,YACPijC,oDAEO,iBACP,kBACA,gBACA,CACO,6FACAC,kGAEAC,aACP,MACA,iCACA,uEACAvkC,WAEAA,OACA,EAEOwkC,OACP,iBACA,+CACA,EAkBOC,wECxCA,eACP,4BACA,8BACA,UACA,aACA,GAEA,sCACA,qCACAC,CACA,CCVA,YACA,2BAGO,cACP,MACA,MACA,0DACA5rD,+BAGAA,wBAGA6rD,KACA7rD,GACA,CAEA,aACOoU,OAEP,SADAy3C,KACA3yC,8BACA,QACAA,8BACAA,aACA,MACA,CACA,8BACA4yC,kCACAC,kCACA7yC,cACAA,0CACA9E,KACA,EACA,EC9BA43C,MACA,YAGA,UAFA,EAIAC,OACA,MACA,+DAEA,+CACA,EACAC,aACA,QACA,UACA,OAEA,qBACAC,cACAC,wCACAC,uCACA,gBACA,OAEA,8CACAprC,kDACA,0BACAA,OACA,MACA,CACA,aACA,sCACA,yCACA,EACAjK,OACAs1C,IACA,uBACA7sC,sBACA,EACAvG,6DACA,SACA,UACA,2BACA,aACAqzC,OACA,qCACAD,GACA,EACA,mCACA,WACA,OACA,GACA,uCACA,WACA,OACA,GACAl4C,KACA,EACAo4C,mBACAC,gBACA,iBACA,0CACA,cACAv7C,eACA,UACA,6BAEA,mBACA,wCAEAw7C,iBACAx7C,+BACAA,6BAEAg7C,SACA,EACOS,gBAGAC,MC/EPC,OACA,UACA,oBACA,SACA,YACA,SACA,YACA,SACA,kBACA,SACA,YACA,SACA,kBACA,YACA,SACA,kBACA,SACA,kBACA,QACA,CACA,QACA,EACAC,eAEA,QAeA,OAHAC,IACAC,MAEAC,GAYA,OAEAD,gBACA,YACA,MAYA,OACA,OAEAA,KACA,MAYA,OAEAA,KACA,KACA,CACA,aACA,EACAE,OACAJ,2DACA,OAGAK,aACA,0DACA,wBACA,UACA,aACA,SACA,cACA,SACA,SACA,eACA,0BACA,CACA,CACA,EACA,EAYAC,oBACA7yC,MACAA,EAqBA8yC,UACAA,SACA,KAyCAA,YACAC,WACA,EA0CAA,UACAD,SACA,EAEA,KAEAE,MACAC,0BAEAC,OACA,MACA,IACA,sFACA,MACA,CACA,WACA,CACA,EACAC,UACAjuC,2DACA8tC,iBACAA,iBACA9tC,UAEA,GAEAkuC,OACA,qBACAC,kBACA,uBACA,mBACA,cAEA,kBACA,YAEA,CACA,QACA,EACAC,YACAllD,IACA0f,EAEA1f,IACAsf,EAEAtf,EAEAmlD,MAEA,kFAEAC,aACA,uCACAC,sBACA,MACA,gBAEA,YACA,wCACA,wBACA,EACA,OACA1tC,WACA2tC,aACAC,cACA7tC,WACA,CACA,EACA8tC,aACA,UACA,OACA,cACA,OACA,SACA,OACA,OACA,QACA,CACA,EACAC,WACA,UACA,mFACA,oBACA,oIACA,4CACA/tC,iBACAC,gBACA2tC,MACAC,MACA,eACA,EACAG,WAEA,WACA,sBACAC,gBACA,MACA,SAEA,mCACAvB,sBACAE,oBACAsB,4CACAA,wCACA,gBACA,+CACA,kCACA,wBAGA,GAFAC,kBACAF,gBACA,GACA,MAEA,8CACAhuC,KACA2tC,KACAC,KACA7tC,IACA,CACA,8BACA,wBACA,MAEA,YACA,SAEA,kCACA,kBACAouC,kCACAC,mCACAC,iCACAC,iCACAtjC,QACAuiC,8DACAA,6DACAtiC,+DACAsjC,QACAC,EACA,2DACA,GACAxuC,kBACA2tC,kBACAC,kBACA7tC,iBACA,CACA,QACA,EACO0uC,aACP,cACA,mBACA,+DAEAV,QACA,kBACAzB,SACA,EACA,+ICzXA,aACA,SACA/H,OAEAwF,mBACA,OAAa,IACN,GACA,EAGP,aAEI,6BAAwD,uBAC9C,UACC,YACG,oBACE,eACA,eACN,8CACmD,yCACJ,mBAC1C,gBACF,GAGbC,6BACI/rC,mBAAgC,GAGpC+rC,2BACI,wBACA,uBACI,iBACAC,iBAEAA,qBAA4B,CAChC,GAGJD,mCACI,0BACAxqD,aACIA,cACAA,UACAA,0BACAA,WACAA,cACAipB,cACJ,GAGJuhC,kCACI,0BACAxqD,cACIA,SACAA,WACAA,cACAipB,cACJ,GAGJA,QAAsB,EAG1Bq8B,OACIr8B,oBACI,IAEAhY,sEACIgY,WACJ,GAGJA,oCACAw8B,qBAAwB,EAG5B,sBACIM,4BACA4E,GAAW,iuCCkBf,cACAuE,OACA7F,OACA,+HAGAtE,OACA,6DACAoK,OAEAC,YAEI,eACI,WAGJ,eACI,iBAGJ,SAAa,EAGjBC,OAEI,WAA6B,OAE7BC,aAA4B7J,UAE5B,cAKA,GAHAx8B,wBACAA,cAEAqmC,YACIvK,SAGAA,uDAAuDuK,YAEvDpF,qBAA0BpV,YAE1B,iBAGJ,SAAa,EAGjBya,kBACI,6BACIxJ,8BACA,OAGJyJ,GAAS,EAGbA,kBACI,IACIpK,WAEAtQ,aACI,mCAEA2a,kBACI,2BAGJ,+BAGJrK,WAEAK,aAAgB,UAEhBM,2BAA0B,CAC9B,EAGJ2J,MACI,kDACAC,6CACAV,mDAA0F,EAG9F,eACI,iBAAgB,OACP,iBACK,EACb,GAGL7F,QAAkB,+7EC5MlBwG,8BCAAC,8vBCgCAC,KACAxN,KAEA,aACImD,aAAgB,gRCpCpBsK,g+BC4DA,aACA,6BACAC,OACAC,OACAC,SAEA7G,OACA,sDACA8G,OACAC,SAEAC,OAEI,GADA,UACA,SAAsB,OAEtB,6CACA,qEAEAL,iBACAE,oBAEAF,8BACI,UACAA,cAA2B,EAG/BA,mCAEAG,sDAAqF,EAGzFG,OACI,UACA,WAEAL,oBACAC,oBAEAK,iDAEQJ,SAAoB,GACvB,EAITK,OACE,mEAAkE,EAGpEC,OACIC,aACAC,aACAzG,aACAzE,SAAY,EAGhBmL,YACI,YAAwB,OAExB,OAAkB,eACW,EAG7BC,IAAiB,EAGrB,oBACIH,SACII,gCACAT,MAGAS,gCACAR,KAGJF,UAAsB,kpCCxG1B,aACA,8CACAW,KAEAC,QAEA5B,OACI,SAAc,EAGlB6B,OACID,SAAoB,EAGxBE,YACI,iBAGA,SAA2B,CACvB,kBACY,YACC,UACC,EACd,CACA,oBACY,YACC,UACC,EACd,CACA,eACY,YACC,UACC,EACd,CACA,kBACY,YACC,UACC,EACd,CACA,mBACY,YACC,UACC,EACd,CACA,eACY,UACC,UACC,CACd,EAqCJ9L,WAEA,sBACI,4FAGA2L,SAA2B,CAG/B3L,WACA,mBACA,uGAAuI,EAG3I,eACI8L,GAAiB,GAIrBC,gBACI,YACI,+DACA14C,kCACA,sFACA,sCAAuC,CAG3C,yCACA,sFACA,oCAAuC,wdCrI3C24C,OAA+B,YACf,iBACR,eACA,EACJ,QAGI,QADAC,OACA,cAEA,eACIC,IAAiB,GAGrB,CAAO,cACH,CACJ,CAER,wCC7BAC,6BASA,eACA,mBACA,qBACA,yBACA,4BACA,SACA,QACA,kBACA,CACA,CAQA,iBACA,mCACA,CASA,eACA,yBACA,CASA,eACA,uBACA,CASA,eACA,2BACA,CASA,eACA,qBACA,CASA,eACA,yDACA,CASA,eACA,qBACA,CASA,eACA,oCACA,CASA,eACA,wCACA,CASA,eACA,qBACA,CAMA,eAEA,oDACA,CASA,eACA,4EACA,CASA,eACA,gCACA,CAUA,iBACA,IACA,qBACA,OACA,QACA,CACA,CCpJA,eACA,+BACA,CAGA,SACA,6CAEA,qCACA,iCACA,qCACA,WACA,WACA,KACA,GAKA,cACA,SACA,CAaA,mBACA,cACAC,gCAEA,OADAA,gBAEA,CC9DA,cAEAC,MAQA,YACAC,EACAtgD,KACA,CAMA,IACA,QACA,UACAS,KACA,QACAmH,IACA,cACA24C,WACA,MACA,sCACAC,2CAEA,gBACAC,UAKA,+CAIAhgD,UAEAmH,YACA84C,eAGA,0BACA,OACA,iBACA,CACA,CAOA,iBACA,UAIAjgD,KACA,MACAkgD,EACApxD,EACAoiB,EACA,EAEA,kBACA,SAGAlR,gCAGA,QACAmgD,YACAA,6DACA,KAEA,eACAC,cACApgD,6BACA,WAEA6/C,MACA7/C,mBAIAqgD,cACAA,SAEA,IADAH,iBACA,mBACAlgD,mBAIA,mDACA,uBACAlR,OACAoiB,oBACAA,GACAlR,wBAGA,iBACA,CAKA,cACA,IACA,gCACA,OACA,QACA,CACA,CAmBA,eACA,8CACAsgD,6BAEA,IACA,CCnJA,uBAGA,wBACA,wBACA,gDAIA,iDACA,eACA,CACA,CCVA,2EAEA,eACA,8BACA,CAWA,oBACA,wEACA,MACA,iCACAC,oCAEA,CAQA,eACA,mBAEA,MACA,yCAGA,oCACA,SACAC,IAEA,qBAMA,GALApc,aACAz3B,0BACA6zC,WAGAA,GACA,wBACAC,IACAD,OAEA,CAEA,2EACA,CAEA,eACA,OACA,oBACA,0BACA,gBACA,YACA,gBACA,gBACA,qBACA,CACA,CAEA,eACA,oDACA,OAGA,uCASA,GAPA,4CACA,YACA,SACA,gDAEA,GAEA,kBACA,2DAGA,UACA,0DAGA,4BACA,sDAGA,QACA,CAGA,eACA,uCACA,aACAE,CACA,CCtGA,0BAEAC,0DAQA,eACA,qBACA,WAGA,mBACAC,KAGAD,eAEA,QACAE,+BACAC,YACAF,UACAC,OAEA,GAEA,IACA,UACA,SAEA,2BACAA,SACA,EACA,CACA,CAEA,cACA,SACA,SACA,YACAE,IACA,EACA,aACAA,IACA,CACA,EAEA,qDACAJ,eAEAK,cACAD,GACAE,QACAC,kCACA,EAEA,CACA,GAEAP,eACAK,WACA,GAGAA,CACA,CAGA,OACA,8CACAA,mBAEAA,QCrEA,mBACA,kCAGA34B,YAFAA,EAEA,oBACA,CAoDA,iBACA,qBACA,SAGA,WAEA,4BACA,aACA,IACA84B,iBACA,OACAA,sCACA,CACA,CAEA,gBACA,CAUA,YACAnqD,EACAoqD,EACAC,KACA,CACA,aAIAC,MACAF,UAEAG,MACAF,sBAGA,GAVA,EAWA,CAYA,YACAG,EACAh6C,KACA65C,KACA,CACA,2BACA,CCjHA,mBACA,aACA,OAGA,aACAI,OAIA,wBACA,IACAC,OACA,OAGA,CAGApvD,MACA,CASA,mBACA,2BAEA,QACA,YACA,eACA,EACA,CASA,iBACA,wBACAmvD,0BACAE,6BACA,CASA,eACA,4BACA,CAQA,eACA,sBACA,+DACA,SACA,CAUA,cAEA,CACA,SACA,OACA,kBACA,YACA,cACA,QACA,EACA,UACA,QAEA,CACA,YACA,oBACA,kCACA,QACA,EAEA,mDACAh9C,mBAGAA,CACA,KACA,SAEA,CAGA,eACA,IACA,oDACA,OACA,iBACA,CACA,CAGA,eACA,iCACA,WACA,iBACA,4CACAi9C,WAGA,QACA,KACA,SAEA,CAOA,oBACA,2BAGA,GAFA7uD,SAEA,UACA,6BAGA,kBACA,kBAGA,4BACA,gCACA,iBAGA,oBACA8uD,EAEAC,OACA,CAEA,QACA,CAQA,eAOA,YAHA,OAGA,CACA,CAEA,iBACA,UAEA,iBACA,cACA,SAGA,WAEAC,WAEA,8BACA,kBACAC,iBAIA,QACA,CAEA,qBAEA,iBACA,cACA,SAGA,WAEA,kBAEAC,cACAD,eACA,GAEAA,CACA,CAEA,QACA,CC5OA,YAEAE,qBASA,kBACA,8CAEA,gBACA,WACAhlB;AAAA,GAEA,4BACA,aAKA,iBACA,SAKA,wCAIA,0BAIA,mBACA,aAEA,MACAilB,UACA,KACA,CACA,CAEA,gBACA,MAEA,CAEA,YACA,CACA,CAQA,eACA,wBACAC,SAEAC,CACA,CAQA,eACA,aACA,SAGA,sBAEAC,yBAEAA,4BACAC,QAIAA,YAEA,+BAEA,qDACAA,QAGAA,WACA,KACA,4CACA,wBACA,GACA,CAEA,uBAKA,eACA,IACA,+BACAC,GAEAn0D,UACA,OAGA,SACA,CACA,CCtHA,cAwDA,cACA,mBACA,SAGA,IACA,mBACA,sCACA,aACA,EACA,OACA,QACA,CACA,CAKA,eACA,+EACA,CAQA,cACA,SACA,SAKA,gBACA,SAKA,SACA,oBAEA,yCACA,IACA,kCACAo0D,YACA7zC,sBACA6zC,yCAEAv0D,6BAEA0gB,qBACA,WACA,gDACAoyC,4FACA,CAGA,QACA,CCpHA,cAQA,cAMA,kBACA0B,0BAEAC,oEAEA,WACA,CChBA,cAEAC,uBAaAC,MACAC,MAGA,eACA,UAMA,OAFAA,SAEAnnC,GACA,cACAonC,KACA,MACA,UACAC,KACA,MACA,UACAC,KACA,MACA,YACAC,KACA,MACA,cACAC,KACA,MACA,YACAC,KACA,MACA,yBACAC,KACA,MACA,SACA,2FACA,MACA,CACA,CAOA,iBACAR,gBACAA,cACAS,KACA,CAGA,iBACA,iBAIA,yBACA,IACAC,IACA,WACA,gDACAvC,SACA;AAAA;AAAA;AAAA,QACAn/B,CACA,CACA,CAEA,CAGA,cACA,gBAIA8+B,uBACAG,iBAIA5jC,4BACA,sBACAsmC,+BAGAC,GACAA,qBAEA,CACA,EACA,EACA,CAGA,cACA,OAIAvmC,0BACA,sBACA,4BAEAwmC,GACA,OACA,WACA,SACA,KACA,EACA,yBACA,EAEA,mBACA,IACA,GAGAC,mBACA9zD,IACA2zD,YACA,KACA,wBACA,UACA,GACA3zD,GAEAF,IACA,kBACA,KACA,wBACA,OACA,GAIAA,CACA,CACA,CACA,CACA,EACA,CAEA,iBACA,qCACA,CAEA,eACA,0BACAi0D,EAGAA,EAIAC,YACAD,MAGAA,WACAA,aAGA,GAXA,EAYA,CAKA,eACA,gBACA,4BAGA,iBACA,aAEA,OACA,UACA,0DACA,CACA,CAEA,aACA,OACA,UACA,0DACA,CACA,CAGA,cACA,4BACA,OAGA,iCAEA1mC,wBACA,sBACA,aACA4mC,YAEA,wCACA,SACA,kBACA,EAIAvC,kDACA,gCAGA,aAEA,iBAEA,QAIA,qBACA,IAGAuC,yBACA,OAEA,CAEAN,UACA,OACA,wBACA,0BACA,QACA,EACA,CACA,EAEA,8EACAtmC,yCACA,sBACA,WACAjE,eACA,CACA,GAEA,4CAMAiE,uCACA,sBACA,aAEA4mC,WAEA,WACAA,sCAGA7qC,eACA,CACA,GAEA8qC,eACA,CACA,GAEA7mC,wBACA,sBACA,iBACA,0BACA8mC,aAGAR,UACA,OACA,0BACA,QACA,GAEAS,eACA,CACA,EACA,CAEA,OAGA,cACA,SACA,OAGA,sBACAC,6BACA,yBAEAroD,KAMA,GALAsoD,KACAX,cACA,OACA,IACA,GACAY,EAIA,IACA,sBACA,OAEA,CAEA,EAGA,cACA,sBACA,+BACA,MAEA,WACAp6B,YAEAm6B,KACAX,cACA,OACA,IACA,EACA,CACA,sBACA,CACA,CAEAtmC,6BACAA,+BACA,CAEA,aACA,OACAmnC,GAOA,iBAOA,GALA,IAKA14C,gBACA,SAGA,IAGA,uBACA,QAEA,OAGA,CAKA,QACA,CAMA,eAEA,uBACA,SAGA,IACA,iBAEA,kBACA,SAKA,oEACA,QAEA,OAGA,CAEA,QACA,CASA,oBACA,WASA,GALA,YAKA24C,MACA,OAGA,2CAGAC,aACAhB,GACA,QACA,OACA,QACA,GACAc,MAIAG,WACAjB,GACA,QACA,OACA,QACA,GACAc,MAIA,iBACAE,sBACAA,SACA,KACA,CACA,CAGA,cACA,sBACA,OAMA,4BACAE,WACAP,2CACAA,8CAOA,mCAEA,+BAEA,+DAIAhnC,oCACA,gBAEAvB,EACA3nB,EACAuL,EACA,CACA,8BACA,IACA,aACAsjD,kFACA6B,0BAEA,eACA,cACAA,YACAC,kBACA,CAEAD,YACA,OAGA,CAGA,yBACA,CACA,GAEAxnC,GACA3H,EACA,sBACA,YACA,gBAEAoG,EACA3nB,EACAuL,EACA,CACA,8BACA,IACA,aACAsjD,4CACA6B,OAEAA,IACAA,aAEAA,gBACAE,2BACAF,iBACA,aAIA,2BACA,6CAGA,OAGA,CAGA,yBACA,CACA,CACA,EACA,EACA,CAEA,YAEA,cACAG,cAEAX,+BASA,OARAV,YACA,SACA,QACA,OACA,MACA,KACA,GAEAqB,0BAEAA,yBAGA,EACA,EAEAX,qCACA,CAEA,YAEA,cACAY,2BAEAZ,oCAGA,OAFAV,2BAEAsB,0BAEAA,yBAGA,EACA,EAEAZ,kDACA,CC7mBA,cACA,mCACAa,mBACA,cACA,KACA,gBACA,IAEAA,SACA,IAGA,2BAEA,GADAA,OACA52D,EACA,SAGA,iBACA,EACA,CAEA,cACA,KACA42D,gBAEA,4BACA,aACAA,cACA,KACA,CAGA,CACA,WACA,CChCA,cACA,WACAC,uBAEA,mBACA,uCAGA,QACAA,sFAIA,oDAEA/kD,6BACA,CACA,CAEA,eACA,mEACA,CAMA,eACA,8BACA,KACA,SAGA,cACA,SACAglD,gBACA,wBAEAA,gCAEAC,cACA,CASA,mBACA,oCACAC,wBACAF,gBACAA,UACAA,eAEAA,SACAA,kBAEA,CASA,iBACA,cACA,MACA,OAGA,oCACAG,cAGA,GAFAH,6BAEAI,eACA,iCACAJ,kBACA,CACA,CA4EA,eAEA,4BACA,SAGA,IAGAtD,8BACA,OAEA,CAEA,QACA,CAQA,eACA,6BACA,CC7KA,cACA,wEACA,CAKA,cAEA,WACA,CClBA,cAGA,MACA,OACA,iFAEA,CAQA,iBAEA,mBACA,CCLA,2BACA,IAEA,mBACA,UACA,2CACA,CACA,CAGA,YAEAjgD,EAEAhG,IAEA4pD,WACA,CACA,gBAEA,eACAC,YAGAC,CACA,CAWA,YACA12D,EACAkI,EACA0E,MACA+pD,MACAhxC,OACA,CACA,aAGA,sEACA,SAGA,gBAIA,6BACA,SAQA,mCACA,SAMA,QAOA,GALA,6DACAixC,6CAIAA,MAEA,+BAIA,QACA,qBAIA,UACA,kCACA,IACA,mBAEA,uBACA,OAEA,CAMA,+BACA,QAIA,cAEA,kBAEA,8CACA,SAGA,SACAF,yBACA,KACA,CAGA,aACAA,qBAEAG,GACA,CAGA,YAGAH,CACA,CAWA,YACA12D,EAGAkI,EACA,CACA,IACA,sDACA,WAGAlI,oBACA,kBAMA,8BACA,WAIA,8BACA,WAIA,kCACA,aAIA82D,MACA,mBAGA,0BACA,QAIA5uD,WACA,cAGA,qBACA,uBAGA,mBACA,iBAIA,mBACA,yBAOA,mBACA,UACA,mCACA,CACA,CAEA,eACA,iCAEA,4CACA,CAGA,eAEA,0CACA,CAIA,eACA,4BACA,CCxPA,oBAEA6uD,yBAEA,qCAEA,oCACA,gBAUA,eACA,kBACAj2D,IACA,EACA,CAQA,eACA,sBACAmB,IACA,EACA,CAMA,SACA,gCACA,4BAEA,YACA+C,EACA,gMACA,IACAA,6BACA,UACA,eACA,CACA,CAGA,KACAgyD,EACAC,EACA,CACA,sBACA,qBACA,GACA73D,IACA,MAGA0B,SAEA,KACAA,OACA,UACAmB,IACA,CAEA,EACAmB,IACA,MACAnB,SAEA,KACAnB,OACA,UACAmB,IACA,CAEA,CACA,GACA,uBACA,EACA,CAGA,MACAg1D,EACA,CACA,wBACA,CAGA,WACA,sBACA,MACAC,EAEA,iBACAhvD,IACAgvD,KACAn3D,IACAo3D,GACAA,GAEA,EACA/zD,IACA8zD,KACAn3D,IACAo3D,GACAA,GAEA,CACA,YACA,MACAl1D,KACA,MACA,CAEAnB,IACA,EACA,EACA,CAGA,4BACA,8BACA,EAGA,2BACA,8BACA,EAGA,kCACA,4BAIA,WACAoH,mCACA,MACA,CAEA,cACA,cAEA,wBACA,EAGA,qCACA,4BACA,OAGA,+BACA,kBAEAkvD,cACA3C,OAIA,2BAEAA,kBAGA,2BACAA,kBAGAA,QACA,EACA,EACA,CCpLA,eACA,WAEA,aACA,6BACA,CAQA,cACA,kCACA,CAYA,cACA,QACA,0EAIA,YACA,0BACAl1B,UAEA83B,EACA,eAIA,cACAC,oBAEA,EACA,EACAD,CACA,CAWA,cACA,sBACA,eAEA,MACA,aAIA,wBACAE,QACAz2D,KAEA,KAGAy+B,cACAi4B,gBACA,MACA,gBACA12D,MAEA,IACA,EACA,EACA,CAEA,OACA,IACA,MACA,OACA,CACA,CC3FA,eACA,MACA,SAGA,gFAEA,MACA,SAIA,iBACA22D,WACA,OACA,UACA,UACA,cACA,SACA,OACA,iBACA,CACA,CCnBA,0DAoBA,eACA,kDACA,CC5BA,cAaAC,IACA,6BACA,EAaA,cACA,wBACA,cACA,OAwBA,2BAEA,OACA,gBACA,YACA,CACA,CAMA,cACA,IAEA,OADAC,wBACA,WACA,OACA,MACA,CACA,CAKA,wBAEAC,GACAC,YACAH,GACA,CACA,2CACA,EAKAI,0BAaAC,0BAGAC,MAgBAC,SAKA,wBACA,cAEA,OAGA,iBACAC,UACAC,aAGAC,eACA,2BACAC,EACAC,MAQAC,qCAGAC,EAFA,mBAEA,kBACAC,MAEA,YAEAL,KAEAM,aAGAH,EAMAJ,CACA,KC9KAQ,cACA,2DAKA,EASA,eACA,oBAEA,UAEA,OAGA,MACA,kBACAC,KACA1S,aACA0S,MAGA,CACA,aACA,gBACA,iBACA,CACA,CC1BA,oBACA,WACA,CAOA,iBACA,aACA,kBACA,CAQA,YACAC,EACAtiD,EACA,CACA,aAEA,kBACA,kBAGA,GAFAA,OAGA,QAEA,CAEA,QACA,CAYA,iBAEA,OADAuiD,oBACA,SACA,CAKA,iBACA,aAGA,wBAEA,cACA,mBACA54D,qCAEAA,oCAEA,CAEA,kBACA,aAIA,GAFA64D;AAAA;AAAA,GAEA,4CACAA,SACA,CACA,MACA,IACAC,mBACA,OAIAA,uBACA,CACAD,IACA,CACA,CAEA,iCACA,CAEA,eACA,sCAEAE,oBACA,QACA,iBACAA,WACAjtC,YAGA,QACA,CA8CA,YACAktC,EACAJ,EACA,CACA,oDAEA,OACAK,IACA,kBACA,gBACA,oBACA,2BACA,gCACA,GACA55B,CACA,CACA,CAEA,UACA,kBACA,mBACA,wBACA,0BACA,cACA,yBACA,sBACA,kBACA,sBACA,0BACA,kBACA,EAKA,eACA,YACA,CAGA,eACA,cACA,OAEA,8BACA,wBACA,CAMA,YACA4rB,EACAiO,EACAC,EACAC,EACA,CACA,gFACA,OACA,oBACA,iCACA,cACA,oBACA,OACA,gBACA,CACA,CACA,CC5NA,YACAC,EACAD,EACAE,EACA,CACA,SACA,uBACA,CACA,kBACA,kBACA,CACA,EACA,2BACA,CCnBA,gBAQA,4BACA,4BACA,aACA,aAGA,2BACA,gBAIAC,GAHAC,GAIA,CASA,iBACA,qBACA,CAKA,8BACA,gBACA,CAOA,YACAC,EACA,yBACAvO,aACA,CACA,SACA,IACA,EAIAwO,+BACAC,sBAEA,KAaA,oCACA,0BACAC,iBACAC,sBACA,MACAC,cAEA,6BACAA,QAGA,MACAH,EACAG,gBACAC,UACAD,gBAGA,QACA,CC1FA,mBAEAE,aAEAC,cAOAC,QASA,YAEAC,EACA,CACA,6BACA,OAKA,SAEA,oBAEAC,mBACA,cACA,OACA,KACA,IACA,CACA,UACA,CAGA,MACA,OAGAA,OACA,CAGA,6CACA,gBACA,2BACA1pD,MACA,CACA,QACA,MAIA,2BACA,QAIA,CAWA,YAEA2pD,EACA,CAEA,iCACA,YACAC,IACA5pD,kBAEAA,GAEA,EACA,EAEA,YACA,CAQA,eACA,SACA,WACA,0DACA,mBACAA,OACAA,GACA,GACA,CASA,eACA,6BAKA,8CACA,4DACA6pD,sBACA,qBACA,gDACAvI,QACA,6FACA,EACAmI,GAEAI,CAEA,KACA,CC7IA,sBCUA,eAEA,aAEAC,GACA,SACA,QACA,YACA,UACA,WACA,YACA,SACA,kBACA,gBACA,EAEA,UACAC,QAGAD,CACA,CAcA,oBA6BA,GA5BAjiD,SACA,kCACAiiD,+BAGA,iBACAA,iDAIAA,8BAEAjiD,mBACAiiD,mCAEAjiD,QAEAiiD,oCAEAjiD,kBACAiiD,eAEA,gBACAA,kBAEA,6BACAA,qBAEAA,iBACAA,0BACA,4BACAA,0BACA,CACA,8BACAA,mBACA,CACAjiD,YACAiiD,qBAEAjiD,gBACAiiD,6BAEA,4BACAA,yBAEA,4BACAA,yBAEA,4BACAA,mBAEAjiD,WACAiiD,kBAEA,CAaA,iBACA,SACAE,EACAniD,aACAiiD,kBACAjiD,qBAGAkiD,OACA,CAWA,eACA,WACA,eACA,YAEA,8CACA,kDACA,gBACA,gBACA,qEACA,oBACA,OACA,kBACA,0BACA,uBACA,sBACA,CACA,EACA,CCjJA,aAMA,SAuCA,cACA,4BACA,wBACA,yBACA,qBACA,qBACA,cACA,cACA,eACA,kBACA,8BACA,CAMA,gBACA,eACA,WACAE,mCACAA,qBACAA,uBACAA,6BACAA,gBACAA,kBACAA,gBACAA,sBACAA,sCACAA,8BACAA,2CACAA,oCACAA,mCACAA,wDAEAA,CACA,CAMA,oBACA,4BACA,CAKA,qBACA,qCACA,IACA,CAKA,WACA,wBACA,eACAF,2BAEA,6BACA,IACA,CAKA,UACA,iBACA,CAKA,oBACA,2BACA,CAKA,qBACA,8BACA,IACA,CAKA,WACA,mBACA,cACA,IACA,EACA,6BACA,IACA,CAKA,YACA,wCACA,6BACA,IACA,CAKA,aACA,oBACA,eACA,IACA,EACA,6BACA,IACA,CAKA,cACA,0CACA,6BACA,IACA,CAKA,kBACA,2BACA,6BACA,IACA,CAKA,SAEA3I,EACA,CACA,qBACA,6BACA,IACA,CAKA,sBACA,+BACA,6BACA,IACA,CAKA,gBACA,gBAEA,yBAEA,oBAGA,6BACA,IACA,CAKA,WACA,oBACA,6BACA,IACA,CAKA,UACA,iBACA,CAKA,iBAGA,uBACA,uBACA,CAKA,cACA,SAGA,gBAFA,qBAIA,6BACA,IACA,CAKA,aACA,oBACA,CAKA,UACA,MACA,YAGA,yBACA,gBACA,6BACA,CAEA,wBACA,sCACA,yCACA,kDACA8I,uCACA,oBAEAA,WACA,sBAEAA,iBACA,kCAEAA,oBACA,yCAEAttD,QAEAstD,IACA,qCACA,wCACA,iDACAA,SACA,mBAEAA,UACA,qBAEAA,gBACA,iCAEAA,mBACA,wCAIA,IACA,CAKA,QACA,4BACA,cACA,eACA,cACA,kBACA,mBACA,6BACA,yBACA,4BACA,kBACA,qBACA,6BACA,qBACA,IACA,CAKA,mBACA,gCAGA,QACA,YAGA,SACA,eACA,IACA,EACA,4DACA,6BAEA,IACA,CAKA,oBACA,oDACA,CAKA,mBACA,4BACA,6BACA,IACA,CAKA,iBACA,iCACA,IACA,CAKA,iBACA,wBACA,CAKA,mBACA,4BACA,IACA,CASA,qBAuBA,GAtBA,+CACA3P,qCAEA,6CACAA,kCAEA,6CACAA,kCAEA,qDACAA,8CAEA,cACAA,qBAEA,wBACAA,qCAMA,YACAA,8DACA,+BACA,MACAA,yBACA,qDACA,0BACA,EACA,eACA4P,IACA5P,iCAEA,CACA,CAEA,iCAEAA,0DACAA,0DAEAA,oFAEA,mEACA,CAKA,4BACA,yEAEA,IACA,CAKA,uBACA6P,EACA7P,EACA8P,EACA91D,IACA,CACA,sBACA,aACA,kCACArE,SACA,CACA,qBAEA,gDACAo6D,MACA97D,UACA8yD,kDAEAiJ,MACA/7D,EACA,wDACA,aAEA,uCACA,QACA,YAEA,CACA,EACA,CAKA,wBAIA,2BACA,4BACA,iCACAmX,OACA,GACA,4BAEA,CAMA,qBAEA40C,iDAGA,oBACAA,uDAIAA,sCACA,oBAEA,CACA,CAKA,cACA,yCACA,CAMA,eACAiQ,YACA,CC1hBA,WAMAC,OAKA,SAaA,6CACA,wBACAC,GACA,kBAEA,CAKA,eACA,sBACA,CAKA,cACA,2BACAz7C,WACAy7C,wBACAA,qBAEA,CAKA,YAEA,kCACA,6BACA,wBACA,OACA,GACAC,CACA,CAKA,WACA,oCACA,uBACA,CAKA,aACA,yBACA,IACAhlD,IACA,SACA,eACA,CACA,CAKA,YACA,gCACA,CAGA,WACA,+BACA,CAGA,WACA,kBACA,CAGA,cACA,wCACA,CAKA,sBACA,wDACAilD,yCACA,gCACAF,mBACAG,EACA,CACA,oBACA,qBACA,KACA,UACA,EACAF,CACA,CACA,GACAnF,CACA,CAKA,eACAsF,EAEA1J,EACAiJ,EACA,CACA,wDACAO,eACA,gCACAF,iBACAI,EACA1J,EACA,CACA,oBACA,qBACA,KACA,UACA,EACAuJ,CACA,CACA,GACAnF,CACA,CAKA,kBACA,sCACA,gBACA,qBAGA,yBACAkF,qCACA,GACAlF,CACA,CAKA,cACA,wBACA,CAKA,mBACA,2CAEA,aAEA,mDACAkF,iCAEA,eAGA,mBADAxD,KACA,MACA6D,IACAxJ,eACAyJ,EAEAD,WAEAL,QACAA,kCAGAC,qBACA,CAKA,WACA,0BACA,CAKA,WACA,0BACA,CAKA,aACA,4BACA,CAKA,YACA,2BACA,CAKA,cACA,6BACA,CAMA,gBACA,+BACA,CAKA,kBACA,2CACAD,GACA/kD,IAEA,CAKA,OACA,iBACA,IACAA,OACA,SACAslD,KACA,CACA,CAKA,kBACA,yBACA,kBACA,IACA,0BACA,OACA,2HACA,IACA,CACA,CAKA,sBACA,0DAEA,2DAEA;AAAA;AAAA;AAAA,CAGA,EAGAz8D,CACA,CAKA,eACA,gDACA,CAKA,qBAEA,KACA,yBAIA,yBACA,CAKA,aAEA,QADA,mBACA,MACAs7D,iBACAA,GACAoB,MAEA,0BAGAP,cACA,CAKA,gBACA,2CACA,mDAGA,+BAEAb,MACA,UACA,cACA,iBACA,oBACA,IACA,GAGAqB,+BACA,2BACApB,wBAEA,kBAGAY,gBAEAb,CACA,CAMA,uBACA,yBACAjqD,oBACA,mCACA,CAKA,qBACA,2CAEAiqD,iBACAA,wBACAY,mBAEA,CAQA,eACA,2CACAA,GACA/kD,MAEA,CAOA,6BAEA,QADAylD,KACA,WACA,uDACA,sCAEA,kHACA,CACA,CASA,cACA,qCACA,cACA,UACA,EACA5J,EACA,CAOA,eACA,aACA6J,QACA,eACAA,CACA,CASA,cAEA,aAEA,mCACA,yCAEA,KACA,QAEA,CAGA,YACA,CAEA,oBAEA,uCACAC,aAIAC,KACA,CAiDA,eACA,2CACA,CAQA,eACA,6BACA,CAQA,iBACA,eACA,sCACA,eACA,EACA,CCviBA,YACAC,EACA,CACA,6DACA,SAGA,yBACA3rD,uBACA,yEACA,CCfA,eAGA,OAFA4rD,SACA,WACA,gBACA,CCLA,UAKA,cACAC,KAIAA,MACAC,eACAA,4BACA,CAKA,cACA,aACA,MACA,0BACA,8GACAC,cACA,CACA,CAIAC,qCCxBA,SACA,uBAEA,kDACA,cACA,CAQA,OACA,+BACAC,sBAEA,kBAEA,CACA,CAKA,SAIA,4BAKA,yCAiBA,mCAiBA,uBAMA,uBAaA,qCASA,eACA,GADAC,gMACA,GACA,YAEAC,YACA,wBAEAA,WACA,sBAEAA,iBACA,kCAGA,gBACA,wBAEAA,OACA,cAEAA,gBACA,gCAEAA,SACA,kBAEAA,SACA,kBAEAA,WACA,sBAEAA,mBACA,sCAEAA,iBACA,kCAEAA,iBACA,iCAEA,CAKA,WACAA,EACA,CACA,gBACA,KACA,yBACA,qBACA,oBACA,GASA,GAPAC,iCACAA,gBACAA,sBAGAA,gCAEA,+DACA,kCACAC,yCACAC,uBAEAC,iEACAH,6DACA3K,SACA,CAEA,QACA,CAKA,YACA,sCACA,IACA,CAMA,aACA,sCACA,IACA,CAKA,aACA,qBACA,IACA,CAKA,iBACA,0CACA,cACA,4BACA,kBAEA,IACA,CAKA,YACA,yBACA,CAKA,UACA,IACA,gDAEA,kBACA,sCACA,CACA,wEACA8K,GACA9K,yCAEA,CAEA,2CACA,CAKA,gBACA,SACA,+BACA+K,0BAEA,oCACA,CAKA,YACA,WACA,eACA,6BACA,+BACA,WACA,+BACA,qBACA,mBACA,mCACA,mBACA,eACA,oBACA,EACA,CAKA,qBACA,4BACA,+BACA,iCACA,aACA,iCACA,uBACA,kCACA,0DACA,qBACA,qBACA,qCAEA,IACA,CAKA,kBACA,WACA,sDACA,6BACA,WACA,iCACA,oBACA,mBACA,sDACA,qBACA,EACA,CAKA,QAEA,CACA,WACA,sDACA,6BACA,WACA,iCACA,oBACA,oCACA,mBACA,sDACA,4BACA,qBACA,EACA,CACA,CAQA,eACA,iBACA,WAGA,iBACA,UACA,SACA,wBACA,SACA,0BACA,SACA,kBACA,SACA,uBACA,SACA,4BACA,SACA,2BACA,QACA,wBACA,CAGA,iBACA,UACA,SACA,sBACA,SACA,oBACA,SACA,0BACA,QACA,sBACA,CAGA,qBACA,CC/WA,oBAMA,+BAEA,4BAEA,oDASA,iBACA,wGACA,kBAEA,sBAEA,eACA,gBACA,cACA,eACA,EAEA,wBAGA,sBAIA,6CACAC,IAEA,0CAEA,CAGA,WACA,iBACA,CAGA,YACA,eACA,CAKA,sBACA,aACA,sBACA,CAMA,wBACA,oBACA,6BAEA,2BACA,CAKA,gBACAzkD,SAEA,yBAEA,mBAEA,CAKA,yBACA,sCACA,CAKA,eACA,qCACA,CAKA,UAEA,8BACA,OAGA,aACA,+HACA,qCAIA,gBAEA,8BAKA,GAJA6iD,WACAA,iCAGA,oBAEA,2IAEAA,GACAA,kDAGA,MACA,CAEA,yFAEA,4BACA,kCACA6B,+BACAA,kCAEAA,CACA,gBAGA,sBAEAC,GACA,UACA,kBAEA,4BACA,EACA,QACA,oCACA,eACA,4BACA,sBACA,mBACA,uBACA,KACA,uDACA,EACA,cACA,kBACA,eACA,CACA,CACA,EAIA,OAFA,4CAGA,gDACAlL,OACA,oDACA,2CACA,EACAkL,oCAGA,oHAEA,yBACA,CAKA,YACA,0BAEA,WACA,KACA,eACA,qBACA,EACA,CAKA,qBACA,kCAEA,qBAEA,wBAEA,IACA,CAOA,4BACA,sCACA,0CAGA,wBACA9B,mBAEA,eAEA,kDACA,6BAEA+B,2BACAC,iCAEA,uCAEA95D,uBAGA45D,gCAEAG,MACA,kBACA,UACA,cACA,eACA,aACA,sBACA,aACA,GAKA,qCAEAA,CACA,CAQA,UACA,WACA,CACA,CC5QA,UACA,gBACA,iBACA,qBACA,EAEAC,kBAEAC,IACA,kBACA,cACA,iBACA,eACA,iBACA,WACA,EAKA,oBACA,YACAC,EACAC,EACAC,EACAC,EACA,CACA,2EAKA,OAGAnB,oCAEAA,aACAA,yCACA,2BACA,EAGAA,yBACA,8BAIA,YACA,CACA,CAOA,oBAEA,4BAKA,mCAGA,4BAGA,kDAEA,yCAMA,mCAEA,YACAoB,EACAC,EAKAC,iBAIAC,kBACAC,uBAEAC,KACA,CACA,6SACAA,KAGA,qHACAJ,sCAGA,2BACA,gBACA,iBACA,oCACA,yBACA,cAEA,qBACA,CAGA,eAQA,GAPA,kBACA,mBAEA,6BACA,mCAGA,oBACA,gDACA7L,oFAEA,2CACA37C,UAGA,2DAEA,0BACA,SAIAmmD,iBACAA,iBACAA,0BACA,gDACAxK,8FAGA,2BACA,WACA,gDACAA,OACA,6EACA,0BACA,EAEAkM,CACA,IAEA,4FACA,MACA,8FAIA,kBACA,iCACA7C,2BACAA,iBAEA,CAEA,sBACA,CASA,gCACA,mCACA,CAKA,oBACA,uBACA,YACA,gBAGA,qBACA,EACA8C,MACA,gBAGA,oBACA,EAEA,6CAGA,6EACA,qBACA,CACA,2BACA,CAQA,kBACAC,EACA,CACA,0BACA,EAEA,CACA,2BACA,EACA,CACA,4CACA,sBACA,kCACA,2BAEA,gFACA,yBACA,gBAGA,CAWA,mBACA,oBACA,CAKA,uBACA,yBACA,oCACA,2DACA,yBACA,eAEA,oBACA,CAMA,iBACA,iGACA,uFACA,uBACA,4HACA,CAMA,gBAQA,GAPA,sBACA,qFAEA,2BACA,8HAGA,yCACA,aACA,sCACA,yBACA,gBAIA,iDAEA,CACA,CAMA,QAEA,kBACA,OAGA,8CAEAC,8BACA,yBAEA,yBAGA,4BAEA,4BACA,gIACA,oCACA,yBACA,eAEA,qBAEA,CAKA,kBACA,0HACA,gBACA,YACA,0BACA,CACA,CC/UA,cAEA,QADA,gBACA,UAEA,SACA,CACA,gCACA,EACA,EACA,CAcA,YACAnB,EACA3sD,EACA+tD,EACA,CAEA,UACA,oBACApB,EAIA,sBACA,sBACA,4BACA,GACAA,EAKA,MAuBA,OAtBA,oCACAqB,qBACArB,eACA,oBACA,IACAoB,yBACAC,kBACA,+BACAA,qBACArB,eACA,oBACA,KAGAqB,IACArB,eACA,YACA,IAKAsB,MAOAD,GAeArB,0BAGAA,YAUA,6GACAA,KAVA,gDACAlL,OACA,2GACAuM,CACA,IACA,EACArB,MAxBA,gDACAlL,OACA,4CACA,mCACA,oCACA,8EAEA,EACAkL,aACAA,KAhBA,4HACAA,aACAA,EAkCA,CAKA,eAGA,2DACA,gDACAlL,QACA,yHACAyM,CACA,wCACA,EACA,IAIAA,WACA,gDACAzM,kGACA,IAEA,EACA,CAiBA,YAEA4L,EACAc,EACA,CACA,yBACAnuD,wBAEAouD,2BACAC,2BAEAD,SACA,gDACA3M,SACA;AAAA,sDACA2M,0CACA,EAEAf,cAGA,qBACA,iBACA,8BACA,qBACA,IACA,GACAV,WACAA,4DAEA9B,WACAA,6BAEA8B,CACA,CAKA,YACA2B,EACAjB,EACAkB,EACAC,EACAC,EACAN,EACAO,EACA,CACA,sBACA1uD,wBAEA,0BACA,iBACA,8BACA,qBACA,IACA,GACA2sD,WACAA,4DAEA9B,WACAA,6BAEA8B,CACA,CAKA,cACA,aACA,gBAGAgC,oDACAA,2CACAA,6CAEAA,uCACAA,yCAGAC,KACA,CC5NA,iBACA,kDACA,CA+CA,eACAC,qBACA,CAQA,iBACAA,oBACA,CA6DA,eACAA,iBACA,CC3IA,aAGA,eACA,uCACAC,yBACA,yDACA,CAGA,eACA,wCACA,CAGA,iBACA,WAGA,uBACA,kBACA,8CACA,EACA,CAOA,YACAjG,EAGAkG,KACA,CAKA,sCACApG,EACA,wDAEA,+BACA,CCzCA,iBACA,WAGAjO,gBACAA,8BACAA,uCACAA,qEACAA,0DACAA,CACA,CAGA,YACAuP,EACApB,EACAphB,EACAmhB,EACA,CACA,cACAoG,GACA,iCACA,cACA,mBACA,EAEAC,EACA,4DAEA,gBACA,CAKA,YACAvU,EACAmO,EACAphB,EACAmhB,EACA,CACA,cASA5lC,iDAEAksC,eAEA,oBAMA,sCAGAC,MADA,YACA,EACA,CClEA,YAUA,eACA,WAEA,qBACA,gBAEAC,OAIAA,+CAIAC,OACA,GAEA,2BACA,CAGA,eACA,kCACAC,iBAGAC,cACAC,sBACA,GAEA,MAEA,iBACAC,cACA,qBACAA,WAEAA,IAGA,cAMAC,4BACA,WACA,uBACAC,SACA,CAEA,QACA,CAQA,eACA,WAEA,qBAEAH,GACAI,OAEA,GAEAC,CACA,CAGA,iBACAA,YAEAC,0BACAN,mBACAM,iBACA,2FAEA,CAGA,iBACA,2BACA,gBACA,SAIA,QACA,CCvFA,YACA9vD,EACA06C,EACA8P,EACAM,EACA,CACA,sDACAiF,GACA,KACA,sCACA,2BACA,EACAN,gDAEAO,QACAC,QAGAvV,iBACAwV,oBAKA,QACA1F,mBACA2F,wCAIA,YASA,MAEA,qBACA,qDAEAC,WACA5F,gBAEA,CAGA77D,qBACA,CAEA,iBACA,wBACA0hE,UAEA7tC,CACA,CACA,CAQA,iBACA,6DAEA,oBACAk4B,sCAGAA,iCACAA,aAGAA,8BACAA,UAGAA,YACAA,2BAGA,+DACAsQ,aACAA,uBAGA,kBACA35D,WACAA,kBAEA,CAEA,qBAKA,iBACA,2BAEA,MACA,OAGA,MACA,kBACAi/D,EACAC,KAEAA,UACAC,aAIA,sCACA,MACA,iBACAC,EACAC,KAEAA,OACAH,YAGA,+BACA,aACA,eACApwD,mBACA,KACA,CACA,CACA,QACA,MAGAwwD,UACA,IAEAjW,+BAEAsQ,gCACApN,YACA+S,iBAEA,EACA,EACA,OAEA,CAGAjW,8BACAA,4CACA,4BACAiW,cACAC,MACAC,QACA,iBACA,YACA,aACA,EAEA,EACA,CAMA,iBACAC,aACApW,gBACAA,oDAEA,CAYA,mBACA,MACA,YAGA,SACA,KACA,mBACA,mCACA,KACA,YACA,mBACA,CACA,GACA,EACA,YACA,mBACA,EACA,gBACA,2BACA,EACA,aACA,qBACA,CACA,EASA,kDACAuL,kCAGAvL,wBACAuL,sDAKAvL,UACAuL,wBAEAgG,SACAA,uBAEAA,EACA,GAGAhG,CACA,CCnQA,uEAiCA,SAMA,+BAGA,2CAGA,gCAGA,4BAGA,yBAOA,eAEA,GAFA8K,+JACA,gBACA/wD,OACA,oBACA,wBACA,6BACA,sDACA,sBACA,KACA,EACA,MACA,wGAEA,CAMA,wBAEA,WACA,2DACA,MACA,CAEA,oBAEA,qBACA,6BACA,mCACA,SACA2lD,GACA,EACA,EAEAA,CACA,CAKA,eACAsF,EAEA1J,EACAiJ,EACAM,EACA,CACA,oBAEA,cACA,qCACA,6BAEA,qBACAkG,EACA,mCACA,SACArL,GACA,EACA,EAEAA,CACA,CAKA,oBAEA,qDACA,2DACA,MACA,CAEA,oBAEA,qBACA,mCACAA,GACA,EACA,EAEAA,CACA,CAKA,kBACA,wBACA,sGACA,MACA,CAEA,4BACA,uHAEA,oBAEAuE,gBAEA,CAKA,SACA,gBACA,CAKA,aACA,oBACA,CAOA,iBACA,8BACA,CAKA,eACA,sBACA,CAKA,SACA,wBACA,SACA,wCACA+G,wBACA,EAEAlK,MAEA,CAKA,SACA,8BACA,6BACAp4D,EACA,CACA,CAKA,oBACA,oDACA,kDACA,iCAEA,CAOA,sBACA,4BACA,CAKA,kBACA,IACA,qCACA,OACA,8HACA,IACA,CACA,CAKA,kBACAihE,wBACA,CAKA,kBACA,cACA,mEAEA,iCACAsB,KACAA,EACAC,GACA1I,EACA,0EACA,CACA,EAGA,8BACAv0D,GACAA,+CAEA,CACA,CAKA,eACA,cACA,qEACA,qBACA,CACA,CAKA,0BAGA,oCAOA,qBACA,iFAGA,wCACA,CACA,CAOA,QACA,iBACA,mBAIA,sBACA,CAKA,aACA,gBAEA,kCAEA,CAGA,6BACA,SACAk9D,KACA,wCAEA,MACAA,KAEA,kBACA,oBACA,sBACAC,KACA,KACA,CACA,CACA,CAKA,yBACAC,yBAGApH,MACA,yBACA,6BACA,GACA,uBAEA,CAYA,2BACA,kBACA,QACA,UAEAqH,mBACA,wBACA,iBACAlhE,QAEAmhE,KACA1K,UACA,iBACAz2D,OAGA,IACA,EACA,CAGA,aACA,yDACA,CAgBA,qBACA,0BACAo/D,kCACA,oCACAjF,kBAEAiH,WACA,CAQA,wBACA,sCACAC,GACAA,WAEA/+D,IACA,kDAGA,UACAg/D,mBACAlQ,kBAEAA,UAEA,CAEA,CACA,CACA,CAeA,qBACA,0BACA,iBAEA,sBACA,oEAGA,cACAmQ,QACA5uC,kBACA6uC,kCAKA,0CACA,wDACAC,GACA,OACA,yFACA,KACA,CACA,EAGA,sCAEA,iCACA,SACA,YACA,qDACA,yEAIA,GADAtH,+BAEA,SAGA,kBACA,cACA,GACA,SACA,YACA,iDACA,6DAGA,0BACA,OACA,kCAMA,2BACA,wCACA,iBACAuH,oBACA,KACA,QACA,CACA,CAEA,2BACAA,CACA,GACA,cACA,sBACAp/D,GAGA,yBACA,MACA,aACA,EACA,mBACA,GACA,OACA;AAAA,aACA,EACA,EACA,CAKA,YACA,sBACAuB,OACAuD,IACA,sBACAA,GAEA9E,IACA,sBACAA,EAEA,CACA,CAKA,iBACA,8BACA,qCAEA,uCACA,wFACA,IAEA,8EAEA,CAKA,iBACA,uBACA,yBACA,uBACA,wBACA,OACA,SACA,WACA,aACA,CACA,EACA,CAOA,CAKA,YACAq/D,EACAH,EACA,CACA,sDACA,SACA,cACAnX,IACA,oBACA,gBAEA,QACA,EACAp4B,IACA,uCACA,CACA,EACA,oBACA,gBAEA,QACA,CAKA,YACAtiB,EACA06C,EACA8P,EACA,CACA,8CAEA,gBACAyH,OAGAC,SACAC,OAGAzX,CACA,CAEA,eACA,sBACA,CAEA,eACA,6BACA,CC9oBA,YACA0X,EACApyD,EACA,CACAA,eACA,8CACAyhD,YAIA,8FAGA,aACA6M,aACA,uBAEA,iBACAA,eACA,CC7BA,YAQA,YACAtuD,EACAqyD,EACAvjC,KACA9uB,gBACA,EACA,CACA,SACA,sBAEA,cACA,WAcA,GAXAsyD,aACA,cACA,YACA,gBACAtyD,6CACA,MACAuyD,SAEA,GAGAA,aACA,YAIA,mBAGAC,MACAF,aACA,gBACAtyD,+BACA,EACA,EAEAyyD,MACAJ,mCACA/hE,IAEAA,+DACA,4HAGAoiE,UACApiE,GAEAF,IACA,yBACAA,CACA,CACA,EAEA,qBACAzB,KACAyB,IACA,mBACA,iHACAoiE,oBACAzL,KAEA,OAEA,CACA,CACA,CAIA,sCAEA,CACA,OACA,OACA,CACA,CAEA,iBACA,qCAIA,mCACA,CCjGA,kBCEA,OAGA,sDAIA,iDAKA,yBAKA,YAEA4L,+BAGA,2CACA,uBACA,oBACA,CACA,CACA,mBCzBA,+EAKA,SAIA,+CAKA,yBAEA,iEAKA,eACA,YACA,YACA,MACA,6BACA,MACA,sBACAC,sBACA5yD,mBACA,qBACA,CACA,CACA,QACA,EAEA6yD,eACAC,IACA,CACA,mBAGA,YACAC,KACAH,KACA,CACA,OACA,kDACA,+CACA,cACA,sBACA,sBACA,KACA,EACA,6EACA,4DACA,CACA,CAGA,iBACA,iCACA,gDACAnR;AAAA,kBACA,IAEAuR,uBACA,gDACAvR,QACA;AAAA,gBACA,EACA,IAEAwR,6BACA,gDACAxR,QACA;AAAA,gBACA,EACA,IAEAyR,mBACA,gDACAzR,QACA;AAAA,YACA/G,CACA;AAAA,cACA,EACA,IAEAyY,kBASA,KARA,gDACA1R,QACA;AAAA,YACA/G,CACA;AAAA,cACA,EACA,GAGA,CAEA,iBAEA,6BACA,GAGA0Y,sBACA,CAEA,iBACA,yCACA,SAGA,sBACA,mBACA,CAEA,iBAEA,iBACA,SAEA,cACA,mBACA,CAEA,iBAEA,iBACA,SAEA,cACA,mBACA,CAEA,eACA,aACA,kBAEA,eACA,IACA,0EACA,2BACA,OACA,6GACA,EACA,CAEA,QACA,CAEA,eACA,IAGA,iDACA,OAEA,CACA,QACA,CAEA,kBACA,+BACA,aAEA,+DACA,uBAEA,CAEA,WACA,CAEA,eACA,IACA,MACA,IAEAxQ,yCACA,OAEA,CACA,mBACA,OACA,yGACA,IACA,CACA,CC/LA,YAEA,SAKA,cACA,WACA,CAKA,cAEAyQ,KACA,gBACAA,IACA,EACA,CAWA,YACAvkE,EACAkR,EAEA,GACAszD,EAEA,CAQA,wBACA,SAGA,IAGA,6BACA,KACA,SAIA,SACA,QAEA,OAIA,QACA,CAIA,mBACA,8CAEA,IACAA,yBACAA,wBAIA,0BAMA,sBACA,UACA,WAEAC,OACAzI,wBACA9qD,cACAwzD,oBACAC,mBAGA/Y,SACA,WACA,WACA,EAEAA,EACA,EAEAgZ,KACA,GAEAC,CACA,CACA,EAKA,IACA,iBACA,4CACAC,UAGA,QAIAzR,QAEAC,6BAGA,IACA,0CACA,cACA,gCACA,MACA,aACA,CACA,EAGA,QAEA,QACA,CC5IA,iBAEA,gBAEA4I,GACA,eACA,WACA,EAEA,kBACAA,yBAGAA,gCACAA,sCAGAA,CACA,CAKA,YACAlI,EACAkI,EACAD,EACA8I,EACA,CAEA,QADAhF,KACA,YACAiF,mCAEApZ,GACA,WACA,QACA,CACA,6DACA,mBACAmZ,yDACAE,OACA,CACA,CACA,EACA,OACA,sBACA,CACA,EAEA,MACA,gBACAnR,WAEAlI,4CAEA,CAEA,QACA,CAKA,iBACA,OACA,WACA,gBACA,CACA,CACA,CAGA,YACAoI,EACA6Q,EACA,CAIA,kCAEAK,QAEA,IACA,aACA,OAEA,CAEA,QACA,CAGA,uCAEA,eACA,MACA,kCACA,qBAGA,sBACA,QAEA,CAEA,QACA,CAOA,eACA,qBACA,SAGA/I,0CACAA,gBAEAA,EALA,kBAMA,CAMA,YACAnI,EACAkI,EACAR,EACAyJ,EACA,CACA,wCACAvZ,cACA,aACAA,gBACA8P,gBACA9P,uBAEAqM,KACA,CAMA,YACAjE,EACAmI,EAEA1J,SACAiJ,EACAyJ,EACA,CACA,wCACAvZ,cACA,iBACA8P,gBACA9P,uBAEAqM,KACA,CAKA,YACAjE,EACAkI,EACAD,EACAkJ,EACAJ,EACA,CACA,MAEA,kBAGA,YADA7I,EACA,OAUA,iBACA,UAEA,eACAtQ,cACA,CACA,kDACAuQ,mCACAvQ,cACA8Y,OACA,CACA,mBACA9Y,oDAGAA,CACA,CACA,aAEAwZ,QAEAn3D,cAKA29C,OADAsQ,EACAD,KACA0I,MACA,YACA,GACA/Y,IAYAA,cACA8Y,oBACAC,MACA,YACA,GAEA/Y,EACA,CAKA,YACAoI,EACAtM,EACAuU,EACAkJ,EACA,CACA,SACA,SACA,EAEA,SACA,gBACArR,WACAlI,aACA,wCACA,EAEA,CAEA,QACA,CCxQA,cAEAyZ,iBAMA,SAIA,iCAKA,yBAUA,8CACA,cACA,WACA,OACA,SACA,WACA,UACA,OACA,IACA,CACA,CAUA,YACA,sBACArI,iBAEA,kBACAA,+BAEA,kBACAA,aAEA,oBACAA,eAEA,sBACAA,gBAEA,CAKA,uBACA,qBACA+C,mBACA,CACA,kEACA,oBACA,cACA,aACA,EACA,CACA,OACA,CACA,CAEA,CACA,mBAMA,eACA,cACA,MACAjO,iDAEAJ,EACA,gFACAA,WACA,gDACAiB,QACA,iHACA,EACAjB,MAGA,qBACAI,OAIA,IACA,gBACAtqD,QACA89D,4CACAA,oCACA,OACA99D,aACA,CAEAA,cAIAu4D,mBACA,CACA,wBACA,SACA,EACA,CACA,cACA,YACA,eACA,CACA,CACA,CAEA,QACA,CAKA,eAOA,gCACA,2BACA1K,sBACA,KACA,CAEA,SACA,mBACA,MACA,iBACA,gBACA,EACA,kBACA,sBACA,EAEA,sBACA,kBACAkQ,2EACAA,qCAGA,QAIAxF,sBACA,aACA,aACA,EACA,CAKA,eACA,yCAEApK,YAGA,cACA,OAGA,6CAEA1yD,GACA,SACA,MACA,aACA,EAEAy4D,GACA,UACA,QACA,iBACA,cACA,EAEAqE,mBACA,CACA,eACA,OACA,WACA,EACArE,CACA,CACA,CAKA,eACA,yCAGA,QAIA,oEAKA,YACA,oBACAA,GACA,aACA,aACA,iBACA,cACA,EAEAqE,mBACA,CACA,iBACA,OACA,cACA,WACA,EACArE,CACA,CACA,MACA,SACA,eACA,yCACA,EACAA,GACA,aACA,oBACA,iBACA,cACA,EACAqE,mBACA,CACA,iBACA,OACA,WACA,EACArE,CACA,CACA,CACA,CAKA,eACA,aACA//B,OACA,6BACA,YACA,cAGA6pC,SACAA,KAKAC,2CACA9pC,cAEA8pC,2CACAj4D,cAGAuyD,oBACA,sBACA,MACA,OACA,IACA,CACA,EACA,CAEA,eACA,oBACA,CCvTA,YACA2F,EACA,CACA,WACA,SACA,KACA,EAGA,CACA,SACA,oBACA,iCACA,MACA/sB,QACA,KACA,gBACA,qBACA,CACA,EACA,wBACA,EACA5nC,QAEA,gBACA,CAEA,eAIA,OAHA,CACA,kBACA,EACA20D,EACA,CCnBA,oBAMA,eACA,mCAEAx0D,4BACAA,kCACA,iCACA,UACA,CACA,4BACA,UACA,CACA,EACA,UACA,EAEA,SAEAA,kCACAy0D,qDACAA,wCACA,qBAEA,EAEA,CAKA,wBACA,uEACA,CAKA,iBACAxJ,EAEA1J,SACAiJ,EACA,CACA,yEACA,CAKA,eAOA,oCAGAkK,0BACAA,yBAGA,oBACA,CAKA,uBACA,wBACA,4GACA,MACA,CAEA,cACA,+BACA,kBACA,+BACA,GACA,qBACA,CAKA,qBACA,2CACA,0BACA,CAKA,iBACA,8BAEA,kBACA,8EACA,MACA,CAEA,gBACA,kGACA,MACA,EAEA,8EAEA,kDACA,qBACA,CACA,CCpIA,OAwCA,cACA,MACA,UAMA,gBACA,4BAGA,oBACA,eAEA,yCACA,IACA,kCACAxR,YACA3M,sBACA,wBACAoe,aACAC,WAEAre,qBACA,WACA,gDACAkL,4FACA,CAGA,oBAEA,CAGA,cACAoT,SACA,CC1EA,YACA70D,EACA80D,OACA,CACA,QACAC,IAEA,cACA,sBACAC,KACAD,IAEA,SACA,YACA,cACA,wBACA,kBAYA,uBACA,iBACA,EAEA,IACA,2BACAC,KACAD,IACA,CACA,oBACA,SACA,6DACA,0CACA,CACA,EACA,CACA,UACA,YACAC,KACAD,IACAjD,KACA,CACA,CAEA,cACA,CCjDA,WAKA,eACA,cACA,sBACA,2BAEAhiD,YAEAA,0BACAA,mBACAzf,GACA,oBACA,SACA,mEACA,gDACA,CACA,EAEA,EAEAyf,qBAEA,yBACA,mDACAA,mCAIAA,cACA,EACA,CAEA,cACA,CC7CA,aAIAmlD,MACAC,MACAC,MAEA,qBACA,SACA,WACA,WACA,SACA,EAEA,oBACAvX,YAGAwX,aACAxX,WAGAA,CACA,CAGA,SACA,iMACAyX,mCAEAC,OACA,mBAEA,MAGA,GAFA7lE,+BAEA,CACA,sBAEA8lE,IAEA9lE,UACAA,UACAA,UAEA,CAIA,6BAEA,kDACA,CAGA,EAEA+lE,WAKAC,GACA,sOACAC,mDAEAC,OACA,mBAEA,MAEA,GADAlmE,iCACA,CACA,sBAEA8lE,IAEA9lE,kBACAA,UACAA,UACAA,QAEA,CAEA,WACA+J,WACA,oBAEAo8D,2CACA,CAGA,EAEAC,WAEAC,GACA,gHAEAC,OACA,mBAEA,SACAH,0CACA,MACA,EAEAI,WAqBAC,cAEAC,aAsBAC,WACA,2CACAC,yCAEA,YACA,CACA58D,uCACA68D,qDACA,EACA,KACA,EC7JA,SAIA,+CAKA,yBAQA,6BACA,WACA,uBACA,EAGA,8EACA,eACA,WACA,wBACA,IACA,CACA,CAIA,YACA,yBACA,sBAKA,kBACA,6BACAC,UACAC,MACAD,IACA,4BAEA,CACA,CACA,mBAGA,cACAxK,GACA,QAEA/5D,IACA,kBACA,yBACA,OAEA,6CACA,qCACA,OAGA,QACA3B,kBACAomE,YACAC,GACAC,uBACA/mE,EACAkoC,EACAuG,CACA,EAEAsc,gBAEAic,mBACA,CACA,CACA,CAGA,cACA7K,GACA,qBAEA,IACA,kBACA,yBACA,OAEA,QAGA,IAGA,aACA17D,WAOA,oCACAA,kBAEA,OAEA,CAEA,qCACA,SAGA,cACAwmE,MACAF,oBAEAhc,gBAEAic,gCAEA,CACA,CACA,CAQA,eACA,OACA,WACA,QACA,CACA,0BAEA,qEACA,CACA,CACA,CACA,CACA,CAMA,qBACA,QACA,2GAGA,wBACA3mE,UAEA,mBACA,WACAA,OACAi7D,QAcAwL,GAXA,CACA,WACA,QACA,CACA,OACA,OACA,CACA,CACA,CACA,EAEA9mE,MACA,CAIA,qBAEA,oCAEAknE,wBAEAC,gBAEAC,gCAEAC,wBAEA5B,iCACA6B,iCACAC,2BAGA,qBACAF,QACA,QACA,WACA,aACA,UACA,QACA,GAGAtc,CACA,CAEA,gBACA,uFACA,CAEA,qBACA+Y,MACA,WACA,MACA,GACAnF,kBACA,mBACA,EACA,CAEA,cACA,aACAzD,gBACA7qD,sBACA,mBACA,mBACA,EACA,0CACA,CCjPA,UACA,cACA,SACA,OACA,mBACA,iBACA,oBACA,kBACA,cACA,aACA,qBACA,cACA,aACA,iBACA,eACA,kBACA,cACA,cACA,eACA,qBACA,SACA,YACA,eACA,gBACA,YACA,kBACA,SACA,iBACA,4BACA,sBACA,EAGA,SAIA,yCAKA,yBAOA,8CACA,eACA,kBACA,eACA,yBACA,eACA,cACA,IACA,CACA,CAMA,YACA,0BACA2d,uBAGA,2BACAA,wBAGA,qCACAA,kCAGA,qDACAA,uCAGA,kCACAw5C,IACA,uBACA,WAEA,CACA,mBAGA,eAEA,sBACA,aACA,kBACA,WACA,sBACA,WACA,iBACA,CACA,GACAz9C,eACA,CACA,CAIA,eAEA,mBAEA,qBACA09C,MACA,WACA,MACA,iCACA,aACA,EACA,WACA,iBACA,CACA,EACA,EACA,CACA,CAGA,eAEA,sBAEA,aAGA,MAFA,uDAEA,YACAroD,iCAEA4O,mBACA,SACA,WACA,MACA,WACA,aACA,EACA,WACA,iBACA,CACA,EAGA05C,QACA,WACAC,gCAIAF,OACA,EAEA,GAEA1S,eACA,CACA,CAGA,eAEA,WAEA1uC,uBAGA,+DAIA2H,mCAEA,CACA,gBAGA45C,EACAzoE,EACAkR,EACA,CACA,IACA,mCAOAlR,gCACA,WACA,MACA,uBACA,cACA,QACA,EACA,WACA,iBACA,CACA,GAEA,OAEA,CAEA,qBACAyoE,EAEAH,MACA,WACA,MACA,4BACA,cACA,QACA,EACA,WACA,iBACA,CACA,GACAp3D,CACA,EACA,CACA,GAEA2d,GACA3H,EACA,sBACA,SACAqvC,EAEA,CACA,gBAGAkS,EACAzoE,EACAkR,EACA,CAkBA,UACA,IACA,gCACAw3D,GACAnS,kBAEA,OAEA,CACA,yBACA,CACA,CACA,EACA,CCjRA,iBACAoS,KAGA,SAIA,6CAKA,yBAaA,iDACA,oBACA,uBACA,CAKA,YACA,yBACA,IAGA3E,WACA,gCACA,6DACA,EACA,CACA,mBAKA,YACA4E,EACAnoE,EACA6U,EACAs2C,EACA8P,EACA,CACA,yEACA,SAEA,sCACA,uDACA9P,CACA,CAKA,YACAgd,EACAtzD,EACAhU,EACAb,EACAooE,KACA,CACA,kCACA,SAEA,mBACA,8BACA,CC/EA,sDAIA,4CAKA,yBAKA,YACA7E,OACA,4BAEA,6CACA,SAIA,gEACA,6BACA,+BAEA7iE,GACA,gCACA,kBACA,sBACA,EACAoB,yCAEA,sBACA,CACA,QACA,EACA,CACA,mBCxCA,sDAIA,uCAKA,yBASA,eACA,YAGA,UACA,SAGA,+BACA,MAEA,IACA,0BACA,uIACA,IAEA,OACA,yBACA,CAEA,yBACA,CACA,QACA,EAEAumE,eACA9E,IACA,CACA,mBAGA,iBACA,SAIA,YAIA+E,SAPA,EAYA,CAGA,iBACA,kBACAC,YAoBA,MAjBA,UAKAC,cAIAA,OAIA,UAIA,SAKA,CAGA,iBACA,cACAC,QAcA,MAZA,UAIAC,oCAIA,UAIA,SAKA,CAGA,iBACA,YACAC,QAGA,UACA,SAYA,GARAC,eAIAA,IACAD,IAGAA,qBACA,SAIA,4BACA,aACAE,OAEA,GACAC,yBACAA,qBACAA,mBACAA,wBAEA,QAEA,CAEA,QACA,CAGA,iBACA,oBACAC,gBAGA,UACA,SAIA,gBACA,SAGAC,IACAD,IAGA,IACA,8BACA,OACA,QACA,CACA,CAGA,eACA,6DACA,CAGA,eACA,oBAEA,KACA,IAEA,oCACA,OACA,MACA,CAGA,CCjMA,UACA,OACA,OACA,OACA,OACA,OACA,OACA,OACA,MACA,EA+DA,kBACAt4D,iCACAA,0BAEAA,qBAEA,sCACAA,8BAIAy0D,0CACAz0D,iCAGAA,iCACAA,0BAEAA,+BACAA,wBAGA,SACA,KACA,kCACA,mBACA,mCACA,EAEAw4D,SAEAx4D,uBACAy4D,IAEA,CAuHA,eACAnK,oCACAA,kBACA,CAKA,cACA,4BACA,gDACA7M,8FACA,MACA,CAEA,aAQA,oBAQAiX,MAGA5M,+BAEAxvD,mBACAo8D,QAEA,GACA,CChRA,YAEAC,yBACAC,kBACAC,2BAGAC,OAGAC,QAGAC,OAGAC,QAGAC,OAEAC,OACAC,KAGAC,OAEA,QACA,YACAC,2BACAA,mCACAA,yBACAA,mBACAA,qBACAA,wBACA,gBAEA,eACA,kCACA,CACA,eACA,8BACA,iDACA,CACA,mDACAC,6BACAA,YAEA,kDACA,2BACAC,SACAA,gBACAD,uBACA,CACA,uEACA,mDACA,CACA,2HACA,YACA,yBAGA/iB,mCACAp6B,eAEAq9C,2CACAC,mBACAC,EACAzgC,OAGAA,yBAGAA,CACA,CACA,8BACA,eACA,2BACA,MACA,SACA,WACA,2BACA,6BACA,uBACA0gC,UACAC,MACAA,EAEA,GADA,wFACA,eACA,QACA,CAEA,QACA,CAEA,SACA,oCACAC,MACA,eACA,kCACA,CACA,cACA,WACA,CACA,eACA,gCACA,aAEA,uCACA,kBACA,MAEAC,CACA,CACA,eACA,IACA,4BACA,4CACA,MACA,CACA,WACA,CACA,CACA,eACA,gBACA,SACA,IACAC,qBACA,MACA,CACA,CAEA,QACA,CACA,eACA,sBACA,CACA,eACA,kBACA,uBACA,sBACA,SACA,EACA,CACA,eACA,SACA,0BACA35C,oCAGAA,kBAEAA,kBACAA,CACA,CACA,OACA45C,GACA,sDACAC,yDACAC,2BACA,iBACA,yCACA,gBACAC,WACA,MACA,SAEA,eACA,0BAEA,cACA,0BAEA,cACA,gCAEA,qBACA3qE,eACAkoE,QACA,iBACA3+D,UAGAA,SACA2+D,QAGAA,WAGA,mCACA,EACA,CACA,8BACA0C,wBACA,iBACA,iBACA,SAEA,QACA,cACA,MACAntD,yBACA,UACAotD,OACA/1D,YACA+1D,GAEA,EACA,CACA,SACA,KACAC,MACA,gBAFA,CAKA,YACA,qBACA5qE,kCACAiyD,cAEA,CACA,SACAjyD,UACA,SACA,QACA,kBACA,WACAiyD,qBACA,KACA,SACA4Y,EAWA95D,UACA85D,cAXA95D,SACA6D,KACAq9C,qBACA,KACA,MACAlhD,UACA85D,MAQAC,KACAl2D,IACA,CACA,CACA,CACA,mBACA,CACA,iBACA,qBACA,SAEA,6BACA,gBACArV,MACA,CACA,eACA,oDACA,CACA,cACA,oCACA,iBACAA,MACA,CACA,6BACA,MACA,SAEA,wBACAqqE,kBACA,8BAGAvpE,8BAGAA,mBACAupE,iCANAmB,QASA1qE,aACA2qE,QAEA3qE,YACA4qE,WAEArB,yBACAmB,QAEAG,GACAC,YACAC,aAEAtjE,CACA,CACA,qBACA,uBACA,GAEA,oDACA8hE,aACAyB,aACAzsD,wBACA,oEACA,CACA,qBACA,mBACA,SAEA,uBACA,2BACA,aAIA,uCACA,uBACA,aACA,QAEA,CAEA,SACAA,aAEA,EACA,CACA,uBACA,MACA,SAEA,+BACA,gCAEA,OACArgB,cACAA,cACA,SAGA,KACA,SAEA,uBACA,2BACA,aAIA,uCACA,uBACA,aACA,QAEA,CAEA,UACAA,aACA,GAGA+sE,wBACA,CACA,mBACA,wBACA,MACA,OAEA,SACAC,EACA,IACAA,uBACA,MACA,CACA,MACA,CACA,mBACA,wBACAC,IACA1mE,IACA0mE,KAEA,KACAC,+BACA,gBACAD,KACA1mE,GACA,GACA,MACA,CACA,sBACA,wBACA2mE,WACAA,YACA,gBACA,MACA,CACAA,4BACA,CACA,iBACA,MACA,sTACA,MACA,WACA,kBACAC,gBACA,CACA,mBACA,qBACA,mCACA,CACA,iBACA,cACA,wBACA,QACA,EAGA,CACA,iBACA,cACA,QACA,EAEA,0BACA,OACA,qBACA,YACA,oBACA,oBACA,QACA,EACA,oBACA,oBACA9B,QACA,SACA,qDACA+B,UACA3zD,0BAGA,kBACA,0CACAjL,eACA,EACA,WACA6+D,IACAC,SAEAA,IACA,aACA,cACA7zD,wBAEA,CACA,gBACA8zD,SACA,eACAA,eACA,mBACA,oBACAD,IACA7zD,sBAEA,CACA,gBACA4xD,gBACAA,cACAA,cACA,UACA9hE,YACAikE,YACA/zD,mBACAA,mBACAlQ,IACAkQ,YACA,QACA,YACA,UACA,QACA,oBACA,sBACA,mBACA,aACA,IAEA+zD,IACA/zD,YAEA,CASA,GARA4xD,eACAkC,sBACA9zD,cAGA,mBAGA4xD,iBACA,sBACAoC,QACAh0D,oDAGA,oBACA,sCACAi0D,mCACAA,gBACAA,kBACA,sCACAC,QACAl0D,eAEA,EAEA,iBACAm0D,KACAA,6BACA7B,wBAEA,UACA8B,gBACAC,0BACA,aACA,IACAF,wBACAA,0BACA7B,oBACAtyD,2CACA,OACAs0D,GACA,kEACA,CACAF,EACAp0D,gBACA,oBACA,EACAq0D,+BACAE,IAEAF,UACA,CAaA,IAZAzC,4BACA5xD,yBACA,SACA,SACAA,qCAEA8zD,eACA9zD,8BAEA8zD,cACA9zD,4BAEAw0D,GACA,kDACAx0D,GACA,cACA,kBACA,kBACA,CACA,CACA,iCACA8zD,oBACA9zD,gBAEA,cAEA,CACA,gBACA,UACA,aACA,cACA,oBACA,YACA,QACA,EACA,iBACA,2CACA,oBACA,8BACAy0D,yBACA,SACA,IACAX,kCAEA,2DACAtkC,yBAEA,OACA8kC,GACA,2EACA,CACA9kC,YACA,CAIA,GAHAilC,IACAjlC,wBAEAklC,kBACAllC,aAEAklC,iBACA,qBACAllC,MACA,QACA,UACA,UACA,QACA,oBACA,sBACA,mBACA,aACA,EACA,KACA,IACA,IACA8jC,eACA9jC,IACAA,IACA4jC,KACAuB,OAEA,OACA,aACA,kBACA,UACA,QACA,EACA,0BACA,OACA,cACA,eACA,QACA,EACA,oBACA,OACA,gBACA,8BACA,QACA,EACA,QACA,QACA,CACA,CACA,eACA,eACA,GAGAC,eAEA,CACA,iBACA,kCACA,SAEA,wBACA,cACAC,sBACAA,qBACAA,8BACAA,qCACAA,4BACAA,oBACAA,+BACA,oCACAA,mCACA,SAEA,mBACAA,wDACAA,qBACAC,kEACAA,4CACAA,+BACAA,2CACAA,yCACA,SAEA,uBACA,2BACAA,sDACA,SAEA,sBACAA,sDACAA,+CACAA,qCACA,SAEA,sBACAA,kCACAA,qCACAA,mCACA,SAEA,wBACAD,oCACA,SAEA,0BACAC,kCACAA,qCACAA,qCACAA,qCACAA,kCACAA,8CACAA,8CACA,SAEA,4BACAA,oDACAA,+CACAA,sCACAA,2CACAA,qCACAA,wCACAA,sDACA,QAEA,CACA,CACA,QACA,CACA,iBACA,iaACA,+BACA,cACA,MACA,aACA,gBACA,kBACA,gBACA,mBACA,qBACA,mBACA,oBACA,sBACA,cACA,mBACA,aACA,cACA,iBACA,eACA,eACA,iBACA,GACA,MACA,wCACA,KAEA,MACA,WACArpD,YAEAspD,SACA,IACAC,kBACA,YACA,gDACAvpD,KAGAA,OAEA,gCAEA,GADAqoD,SACAroD,OACA,YAEAwpB,OACAggC,GACAA,KAEA,SAOA,GANAC,sBACAC,kBACA,mBACArB,eACAoB,qBAEAA,sBACAA,sBACAC,GACAC,kBACAJ,qBACAA,qBACAK,MAEA,SACA,MACA,MACA,aACA,gBACA,kBACA,gBACA,mBACA,qBACA,YACA,mBACA,oBACA,sBACA,cACA,mBACA,aACA,cACA,iBACA,iBACA,eACA,eACA,qBACA,cACA,eACA,oBACA,iBACA,EACA,yCACA,gBACAC,GACAJ,oBAEA,CACA,uBACA,oDACA,gBACAI,IACAA,cACAJ,qBAEA,CAEA,CACA,wCACAA,eAEAA,qBACAA,sBACAK,UACA,0BACA,SACA,cACA,MACA,MACA,aACA,gBACA,kBACA,gBACA,mBACA,qBACA,aACA,mBACA,oBACA,sBACA,cACA,mBACA,aACA,cACA,iBACA,iBACA,eACA,eACA,qBACA,cACA,eACA,oBACA,iBACA,GACAC,GACAC,MAEA,CACA,KAEAP,CACA,CACA,iBACA,ucACAQ,KAuCA,OACAC,MACA,MACA,MACA,aACA,gBACA,kBACA,gBACA,mBACA,qBACA,aACA,mBACA,oBACA,sBACA,cACA,iBArDAC,OACA,CACA,SACA,QACA,oBACA,SACA,SACA,UACA,SACA,UACA,OACA,QACA,QACA,OACA,QACA,YACA,SACA,EACAA,OACA,GACAA,EAkCA,aACA,cACA,eAnCAC,kBAEA,CACA,UACA,WACA,eACA,kBACA,+BACA,kBACA,kBACA,qBACA,sBACA,uBACA,EACAA,OACA,GACAA,EAoBA,iBACA,eACA,eACA,qBACA,cACA,eACA,oBACA,iBACA,GACAH,CACA,CACA,CACA,mBACA,gDACA,CACA,mBACA,qBACA11D,uCACA4M,4BAEAA,OACA,CAEA,QACA,YACAkpD,2CACAA,mBACAA,mCACAA,iDACAA,mBACAA,uBACAA,sBACA,gBACA,QACA,YACAC,2BACAA,6BACAA,2CACAA,uBACAA,uCACAA,qBACAA,6BACAA,2CACAA,uCACAA,uCACAA,oBACAA,kBACAA,oBACAA,2CACA,gBACA,QACA,YACAC,yBACAA,6BACAA,qBACAA,iCACAA,2BACAA,qBACAA,mBACAA,+BACAA,+CACAA,2BACAA,iCACA,gBACA,QACA,YACAC,kBACAA,qBACAA,sBACA,gBACA,QACA,YACAC,mBACAA,qBACAA,uBACAA,kCACA,gBACA,QACA,YACAC,gBACAA,gBACAA,kBACAA,kBACAA,kBACAA,iDACAA,8CACAA,0CACAA,yBACAA,qBACAA,uCACAA,yBACAA,6BACAA,gBACAA,6BACAA,sBACA,gBAEA,4BACA,gCACA,iCACA,gCACA,CACA,cACA,OACA,OACA,SACA,kBACA,GAEArC,SACA,EACA,WACA,wBACA,EACA,qBACA,0BACA,mBACAA,cACAA,kDAEA,EACA,OACA,iCACA,EACA,QACA,WACA,CACA,CACA,CACA;AAAA;AAAA,8EAKA,QACA,OACA,QACA,yBACA,EACA,EACA,UACA,yBACA,IACA,EACA,oBACA,iBACA,EACA,MACA,yBACA,EACA,EACA,QACA,iBACA,CACA,EACA,kDACAsC,iBACA,WACA,kBACA,kBAEA,kBACA,CACA,IAEA,sBACA,WACA3xD,IACA,mBACA,iBACA,qBACAA,KAEA,cACApE,OACAzZ,YACAyvE,WACAlX,IACA,gBACAA,QAEA16C,IACA5S,cAEA,sBACAstD,kBACA16C,8BACA06C,OACAttD,YACA,KAEA,CACA,CACA,8BACA,+CACA,qCACA04B,EACA,CACA,OACA,gBACAA,kBACA,KACAxY,UACAA,kBAEA,CACA,GACA,oBACA,CACA,mBACA,IACA,aACA,aAEA,aACAwoC,OACA,8BACAA,4BACA,2BACA,oBACA,cACA,OACA,CACA,IAEAnvD,OACA,KACAA,MACA,CACA,MACA,CACA,YACA,CACA,CACA,cACA,2BACA,iEACA,yCACA,CACA,cACA,0BACA,gEACA,wCACA,CACA,qBACA,MACA,SAEA,gCACA,SACA,wBACA,0BACA7E,mBACAiuE,EACA,IACAjuE,wBAGAiuE,EACA,4BAIA,IACAjuE,wBACA+vE,YACA9B,KAEA,GAEA,QACAA,gBAEA,OACA+B,sBACA,CACA,gCACAA,sBAGA,CACA,eACA,iBACAzC,eAEA,EACA,CACA,iBACA,SACA,SAEA,mBACA,gBAGAnlE,cACAA,wCACA,GAEAA,aAGA6nE,mBAFA,GAPA,EAUA,CACA,eACA,gCACA,CACA,sBACA,gDACAC,6CACA,SAEA,wDACAA,iDACA,SAEA,0BACA,oCACA,qBACA,8CAEA,EACA,aACA,eAEAlwE,mBACA,QACA,EAEA,CACA,eACA,iBACAA,oDAEA,EACA,CACA,eACA,2CACA,CAEA,eACA,gBACA,CACA,SACA,cACA,cACA,cACA,CACA,OACA,kBACA,kDAEA,gBACA,oBACA8d,gCAEA,QACA,CACA,WACA,SACA,QACA,cACA,SACA,EAEA,GADAyvD,SACAA,0CACA,oCACAvtE,SACAA,kCACAutE,8BACAzvD,IACAA,aAEA,SACAyvD,eACA4C,mBACA5C,6BACA,oCACAvtE,aACAA,0BACAutE,8BACAzvD,IACAA,SAEA,MAEA,YACA,sBAEA9d,iBACA,YAEA,aACA,CACA,cACA,eACA,aAGA8d,YAOAA,uBACAA,SACAA,8BARA,iBACA,YACA,0BASAyvD,QACA,cAEA,cACA,CACA,CACA,4BACA,eACA,gBACA,CACA,SACA,cACA,eACA,eACA,cACA,mBACA,gBACA,mBACA,iBACA,sBACA,sBACA,wBACA,0BACA6C,gCACA,WACA,EACA,eACA,4BACA,OAEA,WACAC,SACAC,MACA,QACAC,KACA,aACAC,mBACAD,0BAEA,QACA,EACAE,MACA,cACA,uBACAhqB,oDACA,KACA,QACA,6GACAiqB,IACAC,2GACA,KACA,gCACA,2BACA,oBACA,OAEA,yBACA,qBACA,gCACAJ,OACA,kBACA,oBAEA,YACA,aACA,oBACA,2BACA,iCACA,qCACA,iCACA,uCACA,2CACA,yCACA,6CACA,aACA,uCACA,6BACA,uCACA,2BACA,6BACA,mCACA,+BACA,+BACA,gBACAK,OACA,gCAEAC,OACA,0DAEA,EACA,qBACA,qCACA,4CACA,CACA,GACAvC,GACAwC,QACA,WACA,SACA,MACA,EAEA,EACA,6BACA,uDAEA,6BACAC,gCACA,kCAGAN,KAEA,6BACA,wBACA,iCAGAO,oBAFAP,KAMA,uBAGA,WACA,gBACA,WACA,MACA,8CACAF,aACAU,iBACAjxE,IAEA,CACA,MACA,+BACA,iBACA,MACA,8CACAuwE,aACA,mBACAvwE,IACA,KACA,CACA,CACA,CAEA,OACA,aACAqwE,2BAEA,KACA,CACAa,aACAb,sBACAI,UACA,CACA,SACA,iBACA,SACA,6BACA,aACA,IACA,iCACA,2BACA,SACA,6BACA,uBACA,IACA,iCACA,qBACA,MACA,EACA,iBACA,sBACA,mBACA,iBAGA,cACA,mBACA,gBACA,sBACA,sBACA,wBACA,iBACA,mBACA,EACA,yBACA,iBAGA,eACA,qBACA,6BACA,uFACA,iBACA,wGACA,gBACA,mBACAlnE,uBACAA,EACA,aACA,GAEA,KACA,CACA,kBACA,iBACA,sCAaA,GAZAmmB,4BACAnmB,MACA,QACA,yCACA,6CACA,uCACA,kBACA,4BACA,QACA,4BACA,IAEAymE,qFACA,OAEA,iDAaA,GAZAr+D,IACAA,GACA,cACA,aACA,EACA,yBAEA+d,0BACAA,6BACAA,4CACAA,+CAEAA,2BACA,uCACAA,YACAyhD,oCAEAx/D,6BACAA,6BACAA,uBAEA,IACA,2BACA,oCACA,oCACAy/D,kCACAhjC,iCACAgjC,sCACAA,OACAC,OAGAA,WAGA,CACA,mCACAjpE,mCACAipE,QAGA,OACAnvE,GACA,uEACA,CACA,KACA,CACA,iBACAyP,iIACA,CACA,KACA,CACA,iBACA+d,kDACAA,2BACA,6BACAuhD,eACA,iCACA,4BACAjB,8EAGA,sBACAsB,oBACA,wBAEA,qCACArB,2BACA,sBACA,uBACAqB,oBAGA,mBACA,WACA,KACA,+BACA,IAEA,wBACA,GACA,KACA,CACA,CACA,EACA,qBACA,uEAGA,WACA,SACA,OAEA,qBACA,WACAlpE,WACAmpE,aAEAA,IACA,kCAEA,MAEA,qBACA,0BAEAvB,+DACAzC,yCACA,CACA,CACA,QACA,CACA,aACA,aACA,gBACA,kBACA,gBACA,mBACA,qBACA,oBACA,sBACA,mBACA,cACA,mBACA,aACA,cACA,eACA,eACA,iBACA,MACA,SACA,gBACA,mBACA,eACA,cACA,YACA,EACA,CACA,SACA,eACA,2BACA,CACA,WACA,eACA,8BACA,WACA,CACA,WACA,kBACA,CACA,OACA,eACA,yBACA,CACA,SACA,eACA,4BACA,WACA,CACA,QACA,8BACA,0BACA,CACA,CACA,iBACAiE,YACAjE,gCACA,CACA,mBACA,sBACA,MACA,SAEA,mBACA,2BACA,GAEAwD,SACA,CACA,iBACA,sBACA,SAGA93B,SACA,GAEA+3B,QALA,EAMA,CAEA,YACA,SACA,IACA,cACA,OACA9uE,GACA,IACAA,cACA,MACA,CACA,CACA,OACA,CACA,EAIAuvE,MACA,eACA,IACA,uBACA,yBACA,YACA,WAEA,SACA,0BACA,gBAEA,MACA,EACA,kBACA,CACA,iBACA,QACA,eACAA,WACAC,UACA,+BACA,4BACA,8IACAC,GACA,YACAC,aAEA,qBACA9/D,oCAGA4/D,qBACA,IACA,oBACA,cACA,qBACA,iBACA,yBACA,aACA,UACA,GACAG,CACA,CACA,uDACA,oBACA,aAEA,oDACAC,uCACAC,oBACA,IACA,SACAC,EACA,eACA,qBACAC,gBACAh4D,gBACAA,EACA,KACAi4D,KACAF,MACA,KACAG,SACA,cACA,4BACA79C,oBACAA,EACA09C,IACAA,cAEAE,QACA,IACA,IACA,cACA,uBACA,GACAE,+CACA5C,QACAl7C,wBACAk7C,aACAA,aACA,KACA,WACA,GACApa,GACAid,wBACAA,wBACAA,kBACA,EACA,eACAjd,iBACA,EACA,CACA,6GACA,2BACA,aAEA,iCACA2c,4BACA,GACAA,mBACA3c,KACAkd,KACA9lB,IACA,cACA,eACA,OAEA,oCACA,MACA,OAEA,mBACA,wBACAylB,OACA,WACA,KACA,IACA,GACA,EACA,EAEA,uBACA,mCACA,0BACAM,WACA,YACA,wBACAzc,WACAV,iBACA,GACA6c,QACA7c,iBACA,EACA,CACA,mGACA,eACA,cACA,OACA4a,YACA,OAEA,mBACA,UACA,8CACAiC,OACA,KACA,eACA,aACA,EACA,MAEAA,OACA,KACA,eACA,aACA,EAEA,iBACA,2BACA,CACA,kCACA,SACAO,KACA,gBACA,aACAv5D,QACAw5D,gBACAR,OACA,gBACA,gBACA,GACAQ,IACAD,IAEA,OACA,gCACA,CACA,iBACA,4BACA,UACA,uBACAjpE,CACA,CACA,uCACAmpE,eACA,mOACA,cACA,YACA,qBACAC,cAGA,GAFAtH,eACAjjE,mBACA,IACA,IACAwqE,iBACA5C,YACA,OAEA,aACA,4BACA6C,gBACA,OAEA,cACAC,KACA1qE,mCACA8lB,cAEAA,4BACA4kD,YAEAC,IACA,mBACA,oBACA,UACA,MACA,KACA/nC,MACA,QACA,mBACA,oBACA,sBACA,UACA,OACA,QACA,aACA,IAEAgoC,oDACA,eACA9kD,mBACA/M,EACA,qDACA,YACAkF,OACA2sD,YACA,aACA,aACA,gBACA,KAEA,EAEA,CACA,gBACA,kBACA,OACAC,iBACAA,2BACAP,YACA,mBACAQ,4CACA,CACA,CAEA,SADAnB,gDACA,sBACAoB,sEACAC,GACA,qCACA,uCACA,sCACA,wCACA,8CACA,wCACA,EACA,iBACAhe,iCACA,MACA6c,oBACA,CACA,KAEAA,QACA7c,iBACA,EACA,CACA,eACA,WACA,gBACA,0BACAie,yCACAC,oBACAD,sCACAC,uBACAD,yCACAC,wBACAD,0CAEA,QADA,kCACA,WACAh9D,YACA,KACA,CAEA,QADA,wCACA,WACAA,YACA,CACA,QACA,CACA,aACA,CACA,mDACA,gDACA,aAEA,6CACA65D,kDACA,mBACA,aACAhrD,uBACA,eACAquD,GACA,KACA,uBACA,GAEAnrE,YACA,EACA,GACA,6CACA8nE,kDACA,mBACA,WACAhrD,uBACA,eACAquD,GACA,KACA,mBACA,GAEAnrE,YACA,EACA,GACA,WACAorE,sBACAC,qCAGAD,qBACAC,+BAEAD,yBACAC,uCAEAD,wBACAC,sCAGA,WACA,2CACAC,MACA,kCACA,iCACA,EACAxlD,kDACA,mBACA,aACAhJ,wCACA,eACAquD,GACA,KACA,MACA,CACA,OACA,OACA,SACA/sE,IACA,CACA,CACA,CACA,GAEA4B,YACA,EACA,GACA8lB,kDACA,mBACA,WACAhJ,wCACA,eACAquD,GACA,KACA,SACA,oBACA,CACA,GAEAnrE,YACA,EACA,EACA,GACA6pE,QACA/B,uCACAA,uCACA,oCACAhiD,uCACAA,sCACA,EACA,EACA,CACA,qDACA,oDACAgiD,yDACA,mBACA,QACA,eACAhrD,mHACA,eACAyuD,GACA,KACA,KACA,WACA,QACA,UACA,EACA,sBACA,GAEAvrE,YACA,EACA,GACA,uDACA,mEACA,mBACA,QACA,WACA8c,mHACA,eACAyuD,GACA,KACA,QACA,UACA,EACA,sBACA,GAEAvrE,YACA,EACA,GACA6pE,QACA/B,8CACAA,gDACA,EACA,CACA,uGACA,qBACA,cACA,OACAF,YACA,OAEA,wCACA4D,GACA,OACA,cACA,cACA,SACA,OACA,EACA,iBACAxe,GACAid,gBACAA,iBACAA,kBACAA,uBACA,EACA,eACAjd,iBACA,EACA,CACA,8BACA,sBACA,MACA,aAEA,WACAye,cACAC,aACA5D,2BACA,qBACA,gBACA,SACA,0BACA,cACA,8BACArrE,EAEA,6CACA,GACAkvE,CACA,EACA,qCACA,mBACA,uBACA,iBACA95D,IACA+5D,KACAH,YAEA,KACAroD,iBACA,CACA,GACA,mBACA0kD,YACA,GACA9a,UACA6c,QACA7c,iBACA,EACA,CACA,iBACA,0LACA/7C,sBACA46D,YACAA,iBAEAC,OACA,EACA76D,uBACA46D,aACAA,kBAEAE,OACA,EACA96D,8BACA46D,oBACAA,yBAEAG,OACA,EACA/6D,oBACA46D,UACAA,eAEAI,OACA,EACAh7D,4BACA46D,kBACAA,uBAEAK,OACA,EACAj7D,mBACA46D,SACAA,cAEAf,OACA,EACA75D,8BACA46D,mBACAA,wBAEAL,OACA,EACAv6D,4BACA46D,kBACAA,uBAEAV,OACA,EACAl6D,8BACA46D,oBACAA,yBAEAN,OACA,EACAt6D,4BACA46D,kBACAA,uBAEAM,OACA,EACAl7D,kBACA46D,QACAA,aAEAD,OACA,CACA,CACA,oBACA,0BACA,MACA,aAEAQ,QACA,oBACAC,QACAC,QACAC,QACAC,QACAC,QACAC,QACAC,gBACAC,QACA,KACA,GACAC,8BACAC,KACA,yBACAA,2CAEA,eACAzD,yBACA0D,eACAV,IACAC,IACAC,IACAC,IACAC,IACAC,IACA,IACAC,IACAC,GACA,MACA,CACA,CACAC,IACAC,iBACA,EACA,CACA,eACA,2BACA,CACA,eACA,qCACA,qBACA,oCACA,mCACA,CAEA,SACA,eACA,yBACA,4BACA,CACA,aACA,sBACA,CACA,mBACA,mBACA,CACA,kBACA,MACA,iBACA,MACA,CACA,mBACA,YACA,MACA,CACA,EACA,WACA,SACA,cACA,iBACA,IACAzuB,uDACA,CACA,CAEA,SACA,eACA,uBACA,6BACA,yBACA,mCACA,qBACA,aACA,6EACA,kBACA,gCACA,wBACA2uB,oDACAC,CACA,CACA,GACA,CACA,mBACAC,sIACAC,yGACA,CACA,uBACA,oBACA,aACA,6FACA,kBACA,gCACA,wBACAH,mDACAC,CACA,CACA,GACA,CACA,CACA,QACA,mCACA,CACA,CAiBA,iBACA,SACA,2EACAt8D,WACA,4DACA,6DACAqb,wEACArb,iBAEA,QACA,CAEA,yBACA,WACAy8D,mEACA,iBACA,IACA,8DACA,SAEA,8DACA,sBACA,8BACA,gBACA,eACA,oBACAC,MACAA,kCACA,aACA/zD,qBACA,0DACAg0D,wBACAD,sBACA,CAEAhqB,eACA,cACA,WACA,MACA,EACA,KAEAjgC,eACA,CACA,GACA4pC,SACA,MACA,CACA,mDACA,OACA3J,eACA,cACA,WACA,SACA,SACA,EACA,CACA,GACA2J,SACA,CAEA,WACAA,iBACA,CACA,CAEA,qBACA,WACA,IACA,kEACA,wBACA,uBACA,qBACA,kBAEA5pC,sBACA,CACA,GACA4pC,SACA,MACA,CACA,uEACA,CACA,WACAA,iBACA,CACA,CAOA,0EAEAugB,gDACA,+BACAA,yBAEA,mBACA,0CACA,iBACAC,eACAA,6BACAA,gCACAA,iBAEA,eACAA,gCAEAl8D,UACAk8D,kCAEAA,CACA,EAEA,iBACA,iBACA,gBACA,WACAC,UACAC,aAEAD,UACAA,YAEAA,QACA,CACA,mBACA,OACA,+BACA,OACA,2BACAvlE,UACA,mBACA,gBACA9J,WACA8J,WAEA9J,CACA,EACA,mBACA,sBACA,2BAEA,YACA,SAEA,8BACA+C,2BACAA,yBACAA,0BACAA,yBACAA,0BACAA,yBACAA,wBACAA,+BAEA,OACA,QAFAA,mBAGA,uBACA,EAEA,6BACA,2BACAqsE,QACA,OACA,UACA,QACA,CACA,KACA,0BAEA,OACA,QAFArsE,mBAGA,MACAwsE,iBACAxsE,aACAA,YACA,CACA,EAEA,kCACA,2BACA,UACA,OACA,UACA,KACA,CACA,KACA,2BAEA,OACA,QAFAA,mBAGA,sCACA,EAEA,gCACA,2BACA/C,YACA,OACA,UACA,OACA,CACA,GACA,QACA,CACA,kBACA,yBAEAwvE,WAcA,QAbA,CACA,kBACA,cACA,mBACA,eACA,oBACA,cACA,6BACA,eACA,uBACA,yBACA,2BACA,EACA,mCACA,4CACA,EAEA,6BACA,WACAp6C,gCACA,iBACA,IACA,2BACA,SAEA,2BACA,sBACA,wBAEA,GADAq6C,UACA,wBACA,6BACAR,iBACAS,GACA,OACA,WACA,MACA,EACAzqB,gBACA,CACA,QACA,CACA,GACA2J,SACA,MACA,CACA,gBACA,OACA3J,eACA,OACA,WACA,SACA,SACA,EACA,CACA,GACA2J,SACA,CAEA,QACA,CACA,yBACA,WACA,6EACA,qCACAA,wEAEA,KACAA,iBACA,CACA,CAEA,SACA,QACA,oCACA,0CACA,CACA,SACA,cACA,CACA,WACA,cACA,CACA,OACA,cACA,CACA,SACA,cACA,CACA,eACA,oCACA,0CACA,eACA,eACA,oCACA,yBACA,mDACA,4BACA,iDACA,oCACA,sCAEA,0CACA,EACA,6BACA,qBACAtjD,qBACA,qFACA,CACA,oCACA,4BACA,yCACA,oBACAqkE,0DACAC,0DACA,yBACAC,IACAF,IACAC,GACA,CACA,CACA,oCACA,6DACA,CACA,uBACA,YACA,0BACA,wBACA,EACA,wBACA,CACA,8BACA,4CACA,6BACA,uCACA,GACA,6DACA,CACA,mCACA,4BACA,OAEA,2CACA,cACA,OACA,iBACAE,cAEA,EACA,cACA,0CACA,qCACA,CACA,CAEA,eACA,gEACA,CACA,OACAC,GACA,cACA,kBACA,+kBACA,MACA,6CAEAC,mCACAzE,eAEA,eACA,CACA,SACA,QACA,oBACA,SACA,SACA,UACA,SACA,UACA,OACA,QACA,QACA,OACA,QACA,YACA,UACA,SACA,WACA,EACA0E,WACAA,EACA,GACA5H,oBACA,CACA,UACA,WACA,eACA,kBACA,kBACA,kBACA,qBACA,wBACA,6BACA,8BACA,EACA6H,GAEA,GACAC,KACA,OACAC,IACA,YACA,qBACAC,mBACAziD,uBAGA,WACAA,QAEAA,CACA,EACA0iD,WACA,MAQA,KAPArwB,kDACAryB,0BACA,mCACAA,8BACAq9C,4BAEAjvB,UACApuB,yBACA2iD,KACAH,YAEAxiD,iCACA,gCACAA,sBACA,OAEAwiD,IACA,gBACAI,KACA5iD,4BACA6iD,OACAV,MAEA,CACA,EACA,YACAO,OACA,4BACA,0CACA,GACA,EACAI,YACA,4BACA,wCACA,IACAC,YACA,4BACA,gDACA,IACAC,UACA,YACA,GACAC,UACA,eACA,aACA,WACA,aACA,gBACA,kBACA,SACA,GACAC,UACA,aACA,WACA,eACA,aACA,aACA,gBACA,kBACA,gBACA,mBACA,qBACA,oBACA,sBACA,mBACA,cACA,mBACA,aACA,cACA,eACA,eACA,WACA,iBACA,gBACA,eACA,EACA,SACA,GACAf,YACA,YACAO,OACA,aACA,MACA,0BACA,WACA,WACA,CACA,MACArF,wBACA,wBACA,aACA,gBACA,kBACA,gBACA,mBACA,qBACA,oBACA,sBACA,mBACA,cACA,gBACA,aACA,UACA,eACA,eACA,gBACAb,OACAwG,eAEAvG,OACAyG,sCAEA,EACA,qBACAF,oBACAE,wBACA,EACA,iBACA,GACA,MACA,uDAEAC,SACAT,OACA,qBACA,MACA,OACA,eACA,iCACA,oBACA,8DACA5yB,+HACA,iDACA,EACA,gCACA,oBACA,6DACAszB,8HACA,gDACA,CACA,CACA,CACA,IACA/F,yBACA,EACA,IACA,WACArc,kCACA0hB,OACA,yBACA,OACA,GACA,IACA,YACA,MACA,eACA,aACA,aACA,0BACA,4BACA,MACA,SACA,WACA,CACA,IACA,6BACA,4BACA,kDACA,IACA,WACA,2BACA,4BACA,gDACA,IACA,kBACA,4BACA,uCACA,IACA,6BACA,4BACA,kDACA,IACA,2BACA,4BACA,gDACA,IACA,6BACA,4BACA,kDACA,IACA,mBACA,iBACA,4BACA,sCACA,IACA,aACA,cACA,iBACA,gBACA,mBACA,qBACA,oBACA,sBACA,mBACA,mBACA,WACA,eACA,eACA,uBACA,eACA,MACA,cACA,cACA,aACA,gBACA,kBACA,iBACA,UACA,gBACA,mBACA,gBACA,yFACA,oBACA,kBACA,mBACA,eACA,MACA,cACA,SACA,CACA,GACA,QACA,IACA,EACAM,sBACA,IACAhiB,4BACA,OACAlzD,GACA,eACA,CACA,GACA,aACAq0E,KACAnhB,mBACA,EACA,4CACA,iCACAqiB,IAGAriB,sBACA0hB,OACA,aACA,OACA,IACAW,GACA,WAEA,KACAriB,iBACA,CACA,OACAlzD,GACA,eACA,CACA,CACAw1E,0BACA,OACA,iEAEAZ,OACA,eACA,MACA,MACA,SACA,CACA,GACA,EACAY,mBACAjG,yBACA,EACAiG,wBACA,OACA,mEAEAnB,KACA,EACAmB,aAEA,UACA,OACA,OACA,YACA,eACA,UACA,EAEA,eACA,mBACA,+BACA,CACA,CAaA,YACAC,EACAC,EACA,CAEA,sBACA,QACAC,2BACA5lE,aACA4lE,yCACA5lE,aAEAA,aAEAA,GAEA,UACA,EAEA6lE,KACAC,KACA,eACAC,cACA,OAEA,qBACA,8CAEA,+BACAC,KAEA,MACA,CAEA,+BACA,UAKAJ,cAEA,gBAEA,gBAEAE,UAIA,MACA,CAEAD,SACA,GAGA,CACA,YACA,KACA,KACA,KACA,IACA,sCACA,CAKA,eACA,YAGA,WACAI,oBACA5nE,cACA,EACA4nE,qBACA,EAEAC,6BAEA,OACA,UACA,QACA,cACA,2BACA,eACA,WACA,aACA,QACA,UACA,cACA,IACAA,WACA,OACA,WACA,EACA,OAGA,CACA,GAEAA,CACA,CAEA;AAAA,mw7CAGA,mEAMA,SAGA,cACA,cACA,CAGA,gBACA,2BACA,CAGA,UACA,cACA,CAGA,oBACA,MACA,gBACA,MACA,CAEA,mBAEA,CAGA,SACA,uBAIA,oBACA,eACAh2E,oBACA,EACA,CACA,CAMA,SAEA,eACA,eACA,UACA,CAMA,cAEA,gCACA,0BAGA,6CACA,8BACA,UACA,aACA0B,UACA1B,IAEAmB,GAEA,EACA,SACA,EAEA,8BACA,QACApB,IACAoB,IACA,EACA,SACA,CACA,GAEA,yBACA,CAKA,WACA,iGACA,wBACA,CAKA,iBACA,kCAEA,2BACA,qBACA,UACA,iBAMAlB,SAOA,IAFA,8CAEA,aAEA,gFAEAkB,4CACA,MACA,CAEAnB,cACA,EAIA,2CACA,+CACA,EACA,CAGA,qBACA,iBACA,CACA,CAMA,SAGA,eACA,uBACA,iBACA,CAMA,cACA,iCACA,CAKA,UACA,sBACA,CAOA,oBACA,yBAEAi2E,GAGA,oBAGA,0BACA,CAKA,SACA,4BACA,CAKA,sBACA,6DACA,CAKA,uBACA,iDAEA,yBAEAh2E,CACA,CAGA,SACA,wCACA,CACA,CAOA,SAEA,eACA,sBACA,4BACA,0BAEA,8DACA,CAGA,gBACA,2BACA,CAGA,UACA,yBACA,2BACA,CAOA,cACA,+BACA,CAGA,eAEA,yCAEA,mBACA,CAGA,uBACA,wCACA,CAGA,8BACA,IACA,qCACA,QAGA,wIACA,MACA,CAGA,uCACA,CAGA,mCACA,+BAEAi2E,KACA,iBACAA,sCAKA,6BAGA,IACA,oBACA,WACA,kHACA,CACA,CACA,CAKA,gCAEA,oBACA,IACA,cAEA,4FACA,sBACA,gBACA,QACA,sGAEA,CAGA,8FACA,MACA,CAMA,YACAC,EACAC,EACAC,YACA,CAEA,iCACA,GAIAD,MACA,GAGAD,MACA,CAKA,6BACA,OAEAG,kCAGAA,kCAEA,CAKA,eAEA,GADA,sBAKA,IACAC,+CACA,OAEA,CACA,CAQA,eACA,kBACA,GAIA,eACA,CAKA,eACA,mBACAxzD,aAEAyzD,eACAC,oBACAC,iBACAC,YAEA,OACA,KACA,UACA,eACA,YACA,SACA,CACA,CAKA,iBACA,uCACA,CAOA,wEACA,gBACA/c,MACA,SACA,GAEA,wGAEAgd,GACAC,MAGAjd,CACA,CAKA,cAGA,KAFA,uBAGA,YAGA,IAEA,sCAEA,MACA,YAGA,sBAEA,YACA,OACA,WACA,CACA,CAKA,aACA,WACA,iBACA,gBACA,oBACA,iBACA,GAEA,mBAEA,KAMA,GAFAkd,QAIA,wBAGA,0BADAC,gBACA,GAEA,2FANA,gCAiBA,0BANAC,IACA,gBACA,oBACA,iBACA,EAEA,CACA,CAMA,kBACAjB,EACA1rB,EACA4rB,EACA,CAMA,GALA,gBAKAF,aAEA,YAMA,QADA1rB,uBACAA,4BAMA,uCACA,YAKA,qCACA0rB,gDACAA,gCAGA,IACA,wCACA,WACA,4DACAA,mBAEA,yBAEAvb,GACAA,mDAEA,CACA,CAGA,eACA,aACA,CAGA,eACA,6BACA,CAGA,eACA,8BACA,CAKA,eAGA,aAEA,cACA,kBACA,OAGA,wBAKA,6BAMA,oEACAub,uDACA,MACA,CAGA,SAKA1rB,YACA0rB,wCAMAA,2BACA1rB,aACAA,gBAEA,qBAKA,yBAEA0rB,oBAGAA,0BACAA,mBAEA,IAEA,CACA,CAEA,cACA,yBACA,MACA,SAGA,yBACA,UAKAnV,oCAEA,CAEA,QACA,YACAqI,2BACAA,mCACAA,yBACAA,mBACAA,qBACAA,wBACA,gBAKA,YACAjF,EACA,CACA,OACA,yBACA,eACA,IACA,CACA,CAKA,iBACAA,oCAIA,6CACA+R,wBAEAA,iCAGAA,iBACAkB,MACA,eAGA,+BACA,MACA,iBACA,aACA,CACA,GAGAjT,uBACA,EACA,CAIA,kBACA,KACA,QACA,aACA,OACA,OACA,MACA,QACA,eACA,aACA,GAKA,eACA,WACA,iBACA,cACA,SAEA9kE,yCACAg4E,YAGA34E,SACA,CAGA,QACA,CAEA,SACAw3E,GACAjiB,IACA,kBACA,OAGA,cAEA,IAIAqjB,OACA,EAKA,eACA,MACAC,EAGA,IACAA,QACAnxE,OACA,OACAA,aACA,CAGA,QACAmxE,oDAEA,WACA,wBACA,UACA,OACA,CACA,YACA,MACA,QACA,kBACA,cACA,yBACA,IACAv5E,wDACA,EACA,gBACA,iBACA,SACA,GACA,2BACA,CACA,EACA,EACA,EACA,CAEA,eACA,mBACAi2D,eAGAA,OACA,CAEA,eACA,gBACA,CAKA,iBACA,6EACA,GAIAqG,mDACA,GAIA9P,2BACA,iEACA,GAGAsQ,2EACA,CACA,CAKA,YACAob,EACAsB,KACA,CACA,uBAEA,cACA,SAGA,4BACAhtB,EAIA,kBACA,SAKA,2DACA,gHACA,KAQA,IAJAitB,6CACAjtB,+CAGA,mGACA,cACAktB,IACA,8EACA,EACA,CAIA,UAEAC,sBAGAntB,CACA,CACA,CAEA,eACA,2CAEAotB,IACA,sBACA,iBACA,wBACA,IACA,EACA,CAEA,eACA,OACA,eACA,YACA,yDACA,CACA,CAKA,YACA1B,EACA2B,EACA,CACA,qDACAT,MACA,eACA,YACA,MACA,sBACA,SACA,KACA,cACA,iBACA,eACA,MACA,CACA,CACA,EACA,CACA,CAEA,eACA,qBAEA3sB,iBAEA,OACA,uBACA,QACA,MACA,OACA,MACA,UACA,CACA,CACA,CAKA,eACA,WACA,kBACA,OAGA,cAEAhsD,WAKAy3E,iCACAA,wBAEAA,iBACA4B,UAEA,GACA,EACA,CACA,CAMA,iBAEA,kGACA,GAGAC,KACA,CAKA,eACA,yBACApf,gBACA,8BACA,CAGA,YACAud,EACAz3E,EACA,CACA,gBAIAA,WAIAu5E,cAIA9B,iBACA4B,UAIA,GACA,EACA,CAGA,eACA,gEAEA,MACA,YAIA,wBAEA,OACA,sBACA,YACA,UACA,OACA,MACA,SACA,sBACA,CACA,CACA,CAKA,eACA,WACA,kBACA,OAGA,cAEAG,OACA,CACA,CAGA,eACA,+CAEA1jB,QAEA,cACA,YAIA,sCAEA,kBACA,KAGA,CACA,oBACA,OACA,YACA,UACA,MACA,SACA,YACA,CACA,CACA,CAKA,eACA,WACA,kBACA,OAGA,cAEA0jB,OACA,CACA,CAGA,YACAj5D,EACAm5C,EACA,CACA,OAIA,IACA,sBACA,0BAGA,gCACA,qCAGA,0BACA,cACA,yBACA,CAEA,qBACA,cAGA,4BACA,mBAIA,OAEA,CAGA,CAGA,eACA,MACA,OAGA,uBACA,wBACA,CAGA,eACA,sBACA,SAGA,gCACA,oBAGA,yBACA,YAIA,CAGA,YACAjsC,EACArqB,EACA,CACA,MACA,YAGA,0FAeA,MAbA,CACA,OACA,YACA,UACA,OACA,SACA,SACA,aACA,UACA,UACA,EACA,CAGA,CAGA,eACA,OAIA,KACA,oBACA,OAEA,CAEA,SACA,CAGA,YACA9B,EACAm4E,EACAl5D,EACA,CACA,iCACA,OAGA,MACA,OACA,SACA,EAGA,MACA,OACA,UACA,MACA,EAGA,SACA,UACA,MACA,EAEA,YACAxC,SAEAA,SACA,iCACA,EAGAA,CACA,CAGA,iBACA,qCACA,wBAEA,6BACA27D,WAEAA,CACA,KACA,CAEA,eAIA,wCACA,CAMA,kBACAhU,EACA7J,EACAxqD,EAGA,CACA,IACA,wBAGArR,yBACAw5E,cACA,WACA,yGACA,CACA,CAOA,YACA9T,EACA7J,EACAxqD,EACA,CACA,4BAEAkP,QACAo5D,sBAEAC,+CAEAD,aACAjU,4BAEAkU,aACAlU,4BAEA,CAEA,kBACAA,EACA7J,EACAxqD,EAGA,CACA,yCAEA,CACA,MACA,SACA,cACA,oBACA,oBACA,SAEA3O,kBACAf,2BAEA,OACA,iBACA,eACA,MACA,SACA,gBACA,UACA,UACA,CACA,CAEA,YACA,mCACAkmD,EACAgyB,EACA,CACA,gBAEA,MACA,sBAIA,cACAt5D,YACA,gBACA,CAEA,kBACA,CACA,gBACA,cACA,iBACA,EAGA5e,EACAm4E,EACA,CACA,wBAEA,kBACA,sBAIA,IAEA,kBACA,gCAEAC,EACAC,wBACAC,QACAH,EAEA,SACAI,UAGAA,cACA,OAEA,qBACA,CACA,CAEA,kBACAv4E,EACA,CACA,MAEA,IACAq4E,gBACA,OACA,QACA,CAEA,IAEA,YADA,cACA,WACA,OAEA,CAEA,yBACA,CAEA,kBAEA,0CAIA,gBACA,CAEA,iBACA,WAEA,qBACA14E,WACA64E,cAEA,GAEAA,CACA,CAEA,iBACA,2CACAC,WAGAC,aACAD,WAGA,EACA,CAEA,YACAvyB,EACAyyB,EACA,CACA,MACA,SAGA,kBAEA,SAIAh5E,qBACAi5E,QAIA,iBACA,GAGAC,QAZA,EAaA,CAMA,kBACA9U,EACA7J,EACAxqD,EACA,CACA,IACA,kBAGArR,uBACAw5E,cACA,WACA,yGACA,CACA,CAOA,YACA9T,EACA7J,EACAxqD,EACA,CACA,uBAEAsoE,sBACAC,wCACAa,0CACAR,6BAEAN,aACAjU,4BAEAkU,aACAlU,4BAEA,CAEA,YACAA,EACA7J,EACAxqD,EACA,CACA,uDAEA,CACA,MACA,SACA,cACA,oBACA,oBACA,SAEAukD,QACArzD,8CACAm4E,8BAEA,MACA,YAGA,WACAn4E,EACAs3E,EACAxoE,gCACA,EACA1P,KACA+4E,EACAZ,EACAzoE,6CACA,EAEA,OACA,iBACA,eACA,MACA,SACA,gBACA,UACA,UACA,CACA,CAEA,eACA,kCAEA,SAIA/P;AAAA,kBACA,yBACA,4BACAkQ,CACA,MAPA,EAQA,CAQA,eACA,yBAEA,IACA,wBAEAH,GACA,SACA,cACA,qCACA,EAEA6qD,QACAA,8CAGAiB,kBACAA,gBAEA,OAEA,CACA,CAGA,YACA9rD,EACAq0D,EACA7J,EACA,CACA,YAIA,IACA8e,eAIAC,UAEAC,WAGAC,eAIAC,UAEAC,UAEA,QACA,kGACA,CACA,CAEA,eACA,yBACA,CAEA,eACA,2BACA,CAEA,eACA,eACA,CAEA,eACA,oBACA,CAEA,YAEA,SACAvD,GACAtb,IACA,kBACA,OAGA,cAEA,IAIA0c,OACA,EAKA,eAKA,mDAUA,OANAoC,aAIAA,KAGAC,aACA,0EACAA,+BAEA,KAGAC,KACA,CAKA,eAEA,wBACAjf,mBAEAC,GACAA,0BAEAgB,gBACAA,oBACAie,MAIAjX,iBAGAkX,QACAnf,6BACAA,qBACA,yBACAof,IACAnd,cAEA,GAEA,CAGA,eACA,iBACA,CAMA,qBAEA,IACA,mBACAkb,MAEAkC,yBACA,EACA,CACA,OAEA,QACA,CACA,CAEA,eACA,8DAGAC,iBACA,OACA,cACA,cACA,QACA,MACA,MACA,QACA,kBACA,kBACA,gBACA,CACA,CACA,CACA,CAIA,SAEA,CAEA,YACA,SAEA,cAEA,+BACA,EAKA,YACApC,EACA,CACA,gCACA,CAEA,eACA,gCACA,KAGAqC,kBACA,CAEA,eAGA,6CACA,CAEA,eACA,mDAEA1pD,QACA,OACA,OACA,OACA,QACA,QACA,WACA,CACA,CAEA,eACA,MACA,YACA,OACA,kBACA,WACA,cACA,kBACA,6BACA,2BACA,iBACA,iBACA,eACA,gBACA,YACA,eACA,MACA,IAGA,aACA,KAGA,CACA,iBACA,YACA,UACA,OACA,MACA,OACA,kBACA,kBACA,WACA,iBACA,6BACA,2BACA,iBACA,eACA,cACA,eACA,CACA,CACA,CAEA,YACAqlD,EACA,CACA,MACA,YACA,gBACA,OACA,cACA,YACA,kBACA,kBACA,iBACA,cACA,IAGA,6CACA,KAGA,CACA,iBACA,YACA,UACA,OACA,MACA,OACA,aACA,kBACA,iBACA,CACA,CACA,CAEA,YACAA,EACA,CACA,wCAEA,QAEA,mBACA,yDAKAsE,yBACA,CAGA,wBAGAj/C,cAEA,OACA,OACA,OACA,QACA,MACA,MACA,QACA,OAGA,iCACA,CACA,CACA,CAoBA,mBACA,MAEAkW,EACAgpC,EAEA,6CAEA,aACA,WACAC,MACAA,CACA,CAEA,aACAjpC,4BACAgpC,4BACAhpC,UACA,CAEA,aACA,8BACAU,IAEAuoC,CACA,CAEA,aACA,UACA,gBAEAjpC,kBAEAD,gBACAipC,mBAGAC,CACA,CAEA,kBACApoC,UACAA,CACA,CAOA,eACA,SAEA,cAEA,uCACA,iHAEA,MACA,CAIA,cACAqoC,KAGApE,iBAgBA,GAVAA,8BACAA,oBAKAkB,UAIA,GACA,SASA,0CACA,SAKA,yCACA,sCACAmD,IACArE,oBAEAA,8BACAc,cAGA,CAMA,oCAEAd,mBAGA,EACA,EACA,CACA,CAMA,YACAsE,EACAC,EACA9hB,EACAD,EACA,CACA,UACAgiB,gBACA,CACA,0BACA,CACA,CACA,wBAIA,OACA,8DACA,EACAD,CACA,CACA,CACA,CACA,CAKA,aACA,gBACA,SACA,EAEA,CACA,MAGA;AAAA,EAGA,sBACAE,iBACA,CAGA,QAFA,kBAEA,UAEAA,oCACAA,SACAA,iBACA,CAEA,QACA,CAKA,mBACA,SACA,QACA,WACA,OACA,EAEA,CACA,QACA,0FACA,6BACA,OACAC,WACAjgB,eACAnQ,EACA,4BACAoQ,CACA,EAGA,MACA,YAMAggB,oCAGA,6CACA,gCAEA,cACA,SACA,oCACA,kBACA,EAEAA,CACA,CAKA,mBACA,gBACA,WACA,YACA,eACA,YACA,UACA,SACA,GACA,YACA,gBACA,SACA,YACA,CACA,GAEA,oDAEAxc,OACAzD,gBACAC,eACAmG,sBACApI,gBAEA,8BACA,OAGA,SACA,QACA,6BACA,gBACA,YACA,YACA,OACA,YACA,aACA,qBACA,EAEA6hB,kDAEA,OAEA7f,oDACA,mHACA,MACA,CAEA6f,YACA,cACA,QACA,iCACA,wCACA,mCACA,CACA,EAwCA,wCAEA,MAEA,IACAp6E,iBACA,UACA,sBAEA,IAGAF,SACA,OAEA,CACA,OACA,CAGA,MACA,SAIA,wEACA,2BAGA,QACA,CAKA,uBACA,eACA,4CACA,CACA,CAKA,kBACA26E,EACAC,GACA,QACA,WACA,EACA,CACA,mCAGA,cAIA,IACA,mBACA,EACA,UACA,mBACA,QAcA,GAVAC,cACA,mBACA,IAEA,kGACAvX,MAKAsX,aACA,kDAEA,IAGA56E,SACA,OAEA,CAEA,OACA,CAGA,6BAEA,0BACA,qBACA,IACA,cACAC,KACA,UACAmB,IACA,CACA,aACA,EACA,CACA,CAOA,SACA,+BAKA,oCAOA,uCAMA,yBACA,eACA,iBACA,EAMA,yCAEA,+BAKA,wCAKA,6BAOA,4BAMA,gDAKA,oCAEA,0BACA,iBACA,iBACA,QACA,mBACA,4BACA,aACA,EAEA,aACA,UACA,kBACA,EAEA,wiBACA,yBACA,gBAEA,uEACA,mCACA,GAEA,+BACA,CAGA,aACA,oBACA,CAGA,YACA,sBACA,CAGA,WACA,qBACA,CAGA,aACA,oBACA,CAOA,yBACA,gCACA,CAQA,QAGA,GAFA,uBAEA,8BAKA,mBACA,qDACA,MACA,CAEA,wBAOA,iCACA,4BAKA,8BAEA,qBACA,2CACA,GAEA,qBAGA,mBAEA,uBACA,CAOA,iBACA,IACA,wBACA,0BAIA,uDACA,cACA,kCACA,EACA,UACA,wBACA,CACA,CAMA,gBACA,IACA,4BACA,sBACA,2BACA,IAGA,EACA,UACA,gCACA,EACA,CACA,CAMA,QACA,qBAIA,IACA,kDACA,gEAKA,mEACA05E,EACA,CAEA,mBACA,wBACA,qBACA,6CACA,sBACA,6BACA,UACA,wBACA,CACA,CAOA,QACA,kBACA,oBACA,CAQA,SACA,+BAIA,kBACA,sBACA,CAUA,aAEA,YAIA,8BAMAC,QAMA,sBACA,CAOA,sBAKA,GAJA,2BAIA,sBAGA,gCACA,OAIA,cACA,MACA,CAGA,oCAEA,6BACA,CAQA,iBACA,8BAEA,4BACA,CAGA,eACA,oCACA,CAUA,+BACA,4BAMA,GACA,oBACAxE,kDACA,cACA,iCACA,CAKA,aACA,MACA,CAIA,mCAKAyE,yBAOA,4BAEA,IANA,GAPA,MAcA,CAOA,kBACA,0EACAz7E,8BAEA,0BAGA,qBAEA,2BACA,0CACA,0BACA,CAGA,qBACA,wEAEA,0HACA+jE,KAEA,CAMA,uBACA,4BACA,uBACA,mDACA,4BACA,kDACA,6CACA,GAIAt3C,WACA,uBAGA,4BAOA,OANA6tC,WACAA,uBAGA,eAEA,qBAKA,IAJA,+BACA,GAIA,CAKA,gBACA,IACA2c,8EACAA,mDACAA,qDAGA,oCACAyE,SAEA,qCAEA,UACA,wBACA,CAGA,6BAIA,mCACA,CAKA,mBACA,IACAzE,iFAEAA,sDACAA,wDAEA,4BACA,uCACA,+BAEA,UACA,wBACA,CACA,CAQA,6CACAA,wCACA,kCAEA,iCAEA,EAKA,uCACA,YACA,kBACA,GAIA,kCACA,EAKA,wCACA,YACA,mBACA,GAIA,kCACA,EAKA,8BACA,iBACA,OAGA,uCAEAvS,OACA,gCAMA,wBACA,CAKA,8BACA,iBACA,OAKA,IAFA,oCAEA,EAIA,uHACA,MACA,CAEAA,GACA,+BAEA,CAMA,2BACA,KACA,8FACAuR,sBACA,UACA,wBACA,CACA,CAKA,kCACA,oBACA,CAKA,qCACA,eACA,4BACA,yBAEA,CAKA,2BACA,oBACA0B,SACA,eACA,yBACA,MACA,iBACA,SACA,CACA,EACA,EACA,CAMA,yBAEA,oCACA,iCAEA,2BACA,CAKA,oBACA,8BAIA,qBACA,CAKA,gBAEA,+BACA,+BACA,sBACA,gCACA,CAKA,mBACA,0FACA,4DAGA,SACA,gDACA,oCACA,4DACA,4DACA,uBACA,EAEA,4BAEAgE,CACA,CAUA,kBACA,sCACA,+GACA,MACA,CAKA,GAHA,oCAGA,oDAKA,eAGA,oBAIA,IAEA,wCAIArB,kBACAsB,0BAEAxE,2BACA,yBAEA,UACA,WACA,gBACA,YACA,eACA,qBACA,0BACA,oBACA,EACA,UACA,yBAKA,wBAEA,yBAEAlc,GACAA,2CAEA,CACA,CAMA,iCACA,qBAKA,2CACA,8HACA,MACA,CAEA,mBACA,gGACA,MACA,CAOA,GAJA,8BAIA,kBACA,iCACA,sBACA,qBACA,MACA,CAQA,IACA,qBACA,WACA,2DACA,SACA,sBACA,EACA,EAGA,oBACA,2CACAqc,gBAEA,CAGA,uCACA,iBAEAsE,8CACAC,0DACAC,SAIA,WACA,YACA,4BACA,MACA,OACA,CACA,GACA,+BACA,CAEA,UAGA,8BACA,IAIA,EACA,EACA,CAEA,eACA,iDACArC,4CACAsC,0CAGAC,6CAEA,OACA,SACA,gBACA,mDACA,mDACA,CACA,CACA,CAEA,YACAC,EACAC,EACAC,EACAC,EACA,CACA,2CAEAC,GACA,KAEA,KAGA,IACA,EAGA,sBAEA,oBACAA,gBAIA,aACA,yIACA,GAGAA,WACA,CAKA,aACA,OACA,SACA,QACA,UACA,SAGA,aAEA,gBAEA,gBAEA,mBAEA,aACA,GACA,2BAEAC,kDACAC,kDAEAnsE,GAEA,mBACA,qBACA,oBACA,sBAEA,iBACAosE,EACA,6CACAnO,EACAoO,CACA,EACA,kEACA,qFACA,EAEA,6BACArsE,gBAGAssE,sBACAtsE,mBAGAA,CACA,CAKA,cAEA,uCACA,CAGA,cACA,oDACA,CAEA,SACA,mGAEA,UAKA,SAIA,uCAKA,yBAcA,aACA,mBACA,mBACA,mBACA,oBACA,kBACA,oBACA,kBACA,iBACA,mBACA,mBAEA,UACA,YACA,WACA,aACA,YACA,SAGA,aAEA,gBAEA,mBAEA,gBAEA,mBAEA,aACA,MA0EA,GA1EAusE,+BACA,wBACA,gBACA,cACA,wCACA,aACA,cAEA,OACA,OACA,SACA,QACA,UACA,SACA,aACA,gBACA,gBACA,mBACA,aACA,GAGA,qBACA,oBAEA,gBAGA,eACA,EAEA,sBACA,gBACA,gBACA,gBACA,oBACA,kBACA,iBACA,gBACA,cACA,EAEA,qBAEA,aACA;AAAA;AAAA;AAAA,0CAGAC,MACA,EAEA,0CAGA,qBAEA,aACA;AAAA;AAAA;AAAA,0CAGAC,MACA,EAEA,wCAGA,qCAGA,0EAEA,gDADAC,IAIA,0BACA,8EAGA,sBACA,CAGA,qBACA,SACA,CAGA,sBACAC,IACA,CAYA,YACA,QAIA,cAGA,6BACA,CAQA,QACA,eAIA,oBACA,CAMA,OACA,eAIA,mBACA,CAKA,QACA,+CAIA,oCACA,CAKA,cACA,+CAIA,kCACA,CAGA,SAEA,iCAEA,qBACA,UACA,uCACA,EACA,CACA,mBAGA,eACA,yBACAr5E,oBAEAs5E,mDAEA,UAOAC,2BACAA,yBACAv5E,kCACAA,kCAGA,aACA,uGACA,EAGA,8CACAs5E,gDAGA,8CACAA,8CAGAA,IAxBA,6CACAA,EAwBA,CC/0NA,YCMA,cACAE,gBACAA,qDACA,aACA,0BACA,qBAEA,gDACArrB,OACA,+EACA,EAGAsK,UACAA,eAEAA,+CACAA,UACA,CACA,IAEA,gDACAtK,6FAEA,CChCA,UACA37C,EACAinE,EACAC,IACA,CACA,MACA/5C,EACA,WACA85C,aACAE,QACAh6C,kBAMAA,iBACAi6C,UACAH,UACAjnE,MAIA,CACA,ECHAqnE,OACA,8DCJAC,QAEA,8BAEAhxD,iCAEAixD,GACA,uBACA,YACA,kDACA,EAEA,iBACA99E,sCACA89E,yCAGA,QACA,EAEAC,OACAR,2BAEAA,iBACA,6EACAM,MAGAN,4FC5BAS,QACA,aACA,8BACA,ECAAC,WACA,aACA,iBAEA,WACAV,iCACAW,cAEAA,4BAIA,CACA,OACA,wBACA,cACA,QACA,WACA,QACA,gBACA,CACA,EClCAC,IACAtxD,EACAtW,EACA5J,IACA,CACA,IACA,wDACA,oCACA4J,iBACA,GACA,iBACA,cACA,CACA,OACA,WACA,EACA5J,KACA,CACA,EACAyxE,CACA,CACA,OAEA,CAEA,ECfAr7B,WACA,aACAoI,+DACAf,KACAi0B,IACA,6CACA,sCAGA,EACA,0CAGA,iCACA,ECUAC,OACA,oBACA,MAEAC,IACAC,KAGA,YACAhG,cAEA,sBACA,aACAiG,gBAMAF,GACAC,cACAhI,6BACAA,6BAEA+H,WACAC,YAEAD,UACAC,OAKAD,YACAf,UACAA,YACAkB,GACAA,IAGA,CACA,EACA,EAEAN,uBACA,MACAM,UAEA,aACAC,mBACAD,KACA,EAEA,aAEAE,CACA,CAGA,EClFA,UAEA,aAGArB,wEAGAsB,QAEA97B,qBACA+7B,IACA,KACA,EAEAC,QAGAD,OAKAA,QACAD,MAEA,CACA,sBACA,SACA,CACA,GClBAG,OACA,aACAxB,YAEA,MAEA,YAEAhH,gCACAgH,sCACAA,kBACAkB,MAEA,EAEAC,MACAnG,YACA,EAEA4F,sBACAM,UAEAN,GACAr7B,QACA47B,mBACAP,cACA,KAEA,ECpCAa,MAQAC,OACA,aACA1B,YACA,MAEA,YACA,sBACA,MAKA,qCAGAt1E,sBACAs1E,UACAA,cACAkB,IAEA,CACA,EAEAN,mCAEA,MACAM,UAEA,aACAO,WACAN,mBACAP,eACAa,YACAP,MAEA,EAKA,sCACA,0CACA,GAEA37B,SAEA67B,CACA,CAGA,EC9EA,eACA,sCACA,CAOA,uCACA,+BACAxhB,oBAGAA,cACA,iBACA,IACA,EACA,CCPA,eACA,YACA,CAEA,cACA,8CACA,CAEA,SAEA+hB,MACAC,GACAC,GAOA,cACA,aACA,UACA3mB,QACA6kB,2CAEA+B,KACA,aACAC,OAEA,WACAC,GACAA,IAEAD,GACAA,GAEA,CACA,CAEA,YACA,CAKA,cAmBApB,cAlBA3F,IACA,kBACA,aACA,MACA,OAEA,2BACA53D,iBAEAw8C,cACA,qCACA,kBACA,iBACA,gBACA,EACA,CACA,CAEA,CACA,CAKA,cAsBA+gB,WArBA3F,IACA,kBACA,aACA,MACA,OAGA,qBACA,2BACA53D,iBAEAw8C,cACA,yBACA,8BACA,iBACA,gBACA,EACA,CACA,CACA,EAEA,sBACA,CAGA,cAIA,cACA,wBACA,MAIA,oFACA+hB,+BACAE,KACA,EACA,CAGA,cACA,cACA,wBACA,MAIA,oFACAF,0CACAC,KACA,EACA,CAGA,cACAJ,OACA,wBACA,MACA,OAGA,eACA1gD,mBACA,oFACA6gD,0CACAA,wCACA,EACA,CAGA,eACA,aACA,uCAEA,QAGA,mHACA,eAEAM,iBAEA,MACAC,EAoDA,GAjDAD,wBACA,wBACA7+D,iBAEA,gDAIA,oBACA,kBACA++D,UACAC,wBACAF,uBACA,KACA,CACA,WACA,YACA,eACAG,cAGA,aAEAC,gCAEAtJ,6BACA,mFACA2I,8CAEA3I,wCACA,oFACA2I,+CAEA,KACA,CACA,gBACA,8CACAY,gBACA,KACA,CAEA,CACA,GAEAC,0BAEAC,MAGA7iB,mBAGA,sBACA,qFACA+hB,SACA,+BACA,kBACA,EAEA,2BAGAA,wBACA,gBACA,kBACA,IAIA,+BACA,+BACA,OAKA,oBACAe,UAGAl6D,qCACA0d,OAEA,gDACAwuB,kEACAitB,aACA,GAEA,uBACAgB,YAEAC,MACA,gCACA,sCACA,eACA,sBACA,GAGA,uBAKA,YACA,cAGA,4BACAhjB,iBACAijB,EACAlB,YACAA,UACA,CACA,GAEAmB,KACA,CAEAlB,UACAC,UACAF,KACA,CAGA,YACA/hB,EAEAoZ,EACAl4C,EACA1d,EACA2/D,EACA,CACA,YACAC,MAEA,aACA,mBACA,eACA,eACA,gBACA,GAEAC,CACA,CAIA,mBACA,qFACAC,WACA,GACAA,oDACAA,8CACAA,+BACAC,SACA,CAGA,YACAvjB,EAEAoZ,EACArrB,EACAo1B,EACAK,EACAC,EACA,CACA,4BACA1vD,iBACA,QAGAivD,MACA,aACA,iBACA,uBACA,oBACA,EACA,CAIA,mBACAA,MACA,aACA,sBACA,oCACA,gCACA,GAEAA,MACA,aACA,uBACA,qCACA,gCACA,EACA,CAGA,YACAhjB,EACAoZ,EACAsK,EACAxiD,EACA1d,EACA2/D,EACA,CAGA,iEACA,OAIA,WACA,qBACA/9E,mCAEA,wBACAA,0CAEA,wBACAA,0CAEA,6BACAA,6DAGA,YACA87D,MAEA8hB,MACA,cACA,eACA,kEACA,iBACA,MACA,EACA,CAKA,eACA,qBACA,MACA,OAIA,qBACAW,IACAA,iBACA3jB,oDAGA2jB,QACA3jB,kCAGA4jB,YACA7B,wDAIA6B,oBACA5jB,gDAGA4jB,2BACA5jB,6DAEA,CAGA,eACAgiB,MACA,yFAIAA,YACAhiB,uCAGAgiB,OACAhiB,yBAGAgiB,QAEAhiB,+CAGAA,8BAIAiiB,kBACA,yFACAA,0BACAjiB,wCACA,EAEA,CCzdA,6BAIA6jB,IACA,cACA,YAEA,kBACA,0BACA,EAGA,eAEA,wGACA,yBACA,qBACA,IACA,EAEAC,EACA,6BAKAC,KACAC,WAEAC,KAEAC,GACA/kB,eACAglB,WACA,GAGAC,GACAjlB,aACAklB,WACA,EAEA,CAOA,iBACA,kBACA,CAKA,YACA7sB,EACAssB,EACAE,EACAC,EACA,CACA,6CACA,OAGA,mBACA,2BACA,aAEA,aACA3kB,IACA9H,WAGA8H,mCACA9H,SACA8H,8BAEAA,WAGA,aAEA,MACA,CAEA,wBACAglB,iBACAllB,mBAEA,SACA,sBACA,MACA,eACA,YACA,EACA,uDACA,gBACA,GAEA5H,4BACAysB,cAEA,kBAGAzsB,wBAGA,kBAEAwsB,qBACA3wE,aACA3O,EACA06D,8BACAE,EACAjsD,CACA,EAEA,CACA,CAKA,YACA3O,EACAy4D,EACAmC,EACAjsD,EAGA,CACA,cACAkxE,oBAEAjhF,EACA,sDAEA,KAEA,sCACA,uBAEA,kCAEAkhF,GAGAC,eAGAA,CACA,2BACA,kCAEA,UAGAA,eAGAA,CACA,MACA,uCACAC,KAEA,wBACAA,aACAC,GACAD,UAGAF,GACAE,UAGA,CACA,KACA,iBACA,qCACA,CACA,KA1CA,mCA2CA,CAKA,YACAltB,EACAssB,EACAE,EACAC,EACA,CACA,cACAnsB,WAEA,GACA,OACA30C,6BACA,kBAEA,OAIA,mBACA,iCACA,aAEA,aACAm8C,IACAA,+BACAA,WAGA,aAEA,MACA,CAEA,wBACAglB,iBACAllB,mBAEA,SACA,sBACA,MACA,UACA,WACA,gBACA,SACA,EACA,mCACA,gBACA,GAKA,GAHAj8C,kCACA8gE,8BAEA9gE,6BACA,IACAA,qDAEA,sCACAqhE,QAEAA,GAIArhE,wBAEA,OAEA,CAEA,CACA,CCnQA,YACAyhE,EACAC,KACAC,KACA,CACA,uBACA,gIACA,MACA,CAEA,uBAEA1lB,EACAylB,IACAzlB,KACA,0BAEA,kBACA,cACA,uBACA,IAGA0lB,GACA3lB,+BAUA,qCACA4lB,SACA,MACA,CAEAp1E,QACAo1E,SACA3lB,KACA,mHAEAA,YAEAA,KACA,0BACA,gBACA,uBACA,GAEA,EAEA,CCpDA,0BAIA4lB,IACA,MACA,8BACA,0BACA,oCACA,8BACA,kBACA,gBACA,KACA,EASA,SAWA,sBAEA,8CACAC,KAEA,cACA,MACA,IACA,EAIA,oDACA,sEAOAC,kDAEA,uDAGA,4BACA,6BACAC,KAEA,8CACAC,IAEA,CAKA,eACA,sBAEA,MACA,yBACA,mCACA,6BACA,6BACA,aACA,WACA,0BACA,6BACA,cACA,eAEAC,EACAhqE,IACA,wCAEA,0DACA,yDAEA2kD,CACA,EACA6kB,EACAC,CACA,EAEAQ,GACAC,KAGAC,sBACA,oCAGAC,IACA,aACA,WACA,0BACA,4BACA,EACA,CAGA,2BACA,0BACA,gDACA3wB,2FACA,MACA,CAEA,sFAEA4wB,oBAEAC,4BACAC,uBAEAC,iBACA1oB,IACA2oB,MACA,OAEAC,GACA,KACA,KACA,UACA,cACA,iCACA,EACA,UACA,EAEAC,8BAIAC,iCAGAA,WACAA,gBACA,gCACAA,WAEA,6BACA,sDAEAA,iBACA,gDACAnxB,kFAGA,0GAEA,8BACA,gBAEAoxB,KACAvkB,EACAskB,EACArkB,EACAC,EACA,GACA,aACAE,CACA,EACA,0CACA,yBACAokB,KACA,GAEAD,CACA,CAGA,+BACA,MACA,aACA,qEACAE,oBAEAC,OACA,uDACA,gDACAvxB,QACA,wGACA,EACA,MACA,CAQA,GANAwxB,IACAA,4CACAA,WACAA,UAGA,uBACA,wIACA,MACA,CAEA,4BACA,gDACAxxB,0FACA,MACA,CAEA,8BACA,gBAEAz5C,GACA,2BACA,KACA,WACA,UACA,qCACA,CACA,EAEAirE,KACA3kB,EACAtmD,EACAumD,EACAC,EACA,GACA,aACAE,CACA,CACA,EAEA,sBACA,0CACA,EACA,CACA,CAGA,eAIA,8BAEA,uCACA,CCxQA,uCCyBAwkB,qBACAC,2DAEAC,YACAC,iBAEA30D,UAGAoK,uBAGAwqD,WACA,MACA,UAGA,eACA,UAIA,eACA,UAGA,mBAEA,8BACA,iBACA,UACA,mCACApmE,IACAld,OAEA,CAEA,OACAA,4CAEA,EAEAujF,OACA,wCACA,WACA,QACA,SACA,eAEA,sBAEA,kCACAC,IACAC,YACA,QACA,YACAC,oBACAF,IAEA,CACAE,UACAD,WACA,CAcA;AAAA;AAAA;AAAA;AAAA,EAZAC,EACA,IACA,OACA,IACAllF,8BACA,iBACA,2CACA8kF,QAEA,EACA;AAAA,IAGA,CAEA;AAAA;AAAA,oBACA,ECtGAK,WACA,sDAEAC,gCACA,iBACAC,aACApsC,GACA,gBACA,gBACA,OACA,EAwBA,GAtBAznC,mBAGAyzE,iCACAhsC,iCACAgsC,WACAhsC,uBAKA,gBACAonB,mBACA/D,sBACA+D,wBACA,EACA,GAEA,sBACAilB,gBAGA9zE,aACA,2BACAirD,wCAEA8oB,EACAA,mBACAC,OAEA,qCAEA,CACA,CACA,EC5CAC,YAGAC,IACA,qCACA,kCACA,sCACA,gCACA,iCACA,EAGA,cACA,wBACA,4BACA,CAGA,mBACAT,yBACA,sCAGAA,wCACAA,oCACAA,mCACAA,gCAEA,IACA,CAEA,aACA,sBACA,WAEA,kCAEAU,KAEA,kBAGA,cACA,QACA,8EACA,QACA,CAEA,iBACAA,gBACA,0BAEA,MACA,aACApoB,IACA,sBACA,uBACAA,cACA,iCACA,iBACA,GAEA,CAGA,oBACAqoB,mCACAp0E,gCACAA,kBAGA,aAQA,GAJA,0CAIAq0E,SACA,sDACA,MAIA,8BACAC,oBACAA,WAGA,oCACA,yBACA,eACA,EACA,CACA,MAEA,8BAGA,aACAroB,WAEAsoB,uBACA,CACA,CAEA,CAEA,QACA,EC5GAC,MAEAC,IACA,WACA,eACA,aACA,SACA,YACA,mBACA,WACA,KACA,6BACA,UACA,CACA,uBACA,UACA,CACA,EACA,UACA,CACA,CACA,EAKA,YACArjF,KACA,CACA,SACA,MACA,IACA,EAIA,GAFAsjF,MAEA,gBAEA,aACA,0NAGA,EACA,MACA,CAEA10E,MACA20E,UACA,oBACA30E,OACA40E,WAEA,CAEA,iBAIA,WAIAC,sCACA,IAEA,aACA,sHACA,EAGAlB,QAEAmB,OACAlB,QACAmB,IACA,KACA,mBACA,EACA,CAEA,ECzEAnB,UAGAjO,WACA,mGACA,yBACA,cACA,QACA,8GACA,GACA,MACA,EACA,oBAIA,4BACA,0BACA,GAKAiO,WAGAoB,KAEApB","names":["processPreload","node","fetchOpts","script","link","bind$4","args","i","bind$3","toString$1","result","obj","isArray$5","fn","isPlainObject$1","forEach","thisArg","a","content","utils$a","serializedParams","val","key","v","parts","hashmarkIndex","url","utils$9","InterceptorManager","utils$8","normalizeHeaderName","name","headers","enhanceError","code","error","resolve","response","cookie","utils","secure","isAbsoluteURL","combineURLs","baseURL","ignoreDuplicateOf","href","parsed","Cancel","Cancel_1","requestHeaders","responseType","config","request","responseData","settle","reject","timeoutErrorMessage","transitional","cookies","onCanceled","DEFAULT_CONTENT_TYPE","normalizeHeaderName$1","data","setContentTypeIfUnset","stringifySafely","defaults","defaults_1","defaults$4","isCancel$1","transformData","isCancel","defaults$3","throwIfCancellationRequested","utils$6","reason","utils$5","mergeConfig$2","config2","source","configValue","data$1","validators$1","validators","deprecatedWarnings","formatMessage","opt","validator","keys","utils$4","buildURL","dispatchRequest","mergeConfig$1","Axios","synchronousRequestInterceptors","requestInterceptorChain","responseInterceptorChain","chain","promise","newConfig","onRejected","Axios$1","token","executor","resolvePromise","listener","index","CancelToken","CancelToken_1","spread","bind$2","mergeConfig","defaults$2","instance","utils$3","axios","axiosModule","axios_1","module","sym","symObj","syms","origSymbol","hasSymbolSham","ERROR_MESSAGE","slice","toStr$1","funcType","implementation$1","bound","binder","that","boundLength","boundArgs","target","Empty","implementation","functionBind","bind$1","src","undefined$1","$SyntaxError","$Function","$TypeError$1","getEvalledConstructor","$gOPD","ThrowTypeError","throwTypeError","hasSymbols","getProto","needsEval","TypedArray","INTRINSICS","value","gen","LEGACY_ALIASES","bind","hasOwn$2","$concat$1","$spliceApply","$replace$1","$strSlice","$exec","rePropName","reEscapeChar","stringToPath","last","getBaseIntrinsic","alias","intrinsicName","getIntrinsic","intrinsicBaseName","intrinsic","intrinsicRealName","skipFurtherCaching","first","part","isOwn","$apply","$call","$reflectApply","$max","$defineProperty","desc","func","callBind","$indexOf","callBound$1","mapSizeDescriptor","mapSize","mapForEach","hasSet","setSizeDescriptor","setSize","setForEach","hasWeakMap","weakMapHas","hasWeakSet","weakSetHas","hasWeakRef","weakRefDeref","booleanValueOf","objectToString$3","functionToString$1","$match","$slice","$replace","$toUpperCase","$toLowerCase","$test","$concat","$join","$arrSlice","$floor","bigIntValueOf","gOPS","symToString","hasShammedSymbols","toStringTag","isEnumerable","gPO","num","dec","inspectCustom","inspectSymbol","has$5","opts","depth","seen","indexOf$1","from","noIndent","newOpts","inspect_","s","attrs","mapParts","collectionOf","setParts","isPlainObject","protoTag","stringTag","constructorTag","tag","indent","trailer","x","baseIndent","xs","symMap","isArr","callBound","inspect","$TypeError","$WeakMap","$Map","$weakMapGet","$weakMapSet","$weakMapHas","$mapGet","$mapSet","$mapHas","listGetNode","curr","list","listGet","listSet","objects","listHas","$m","$o","channel","$wm","replace","percentTwenties","Format","formats$3","formats$2","has$4","isArray$3","hexTable","array","compactQueue","compacted","j","item","arrayToObject","merge","options","mergeTarget","targetItem","acc","assign","decode","encode$1","string","charset","out","c","format","compact","queue","refs","isRegExp$1","isBuffer","combine","maybeMap","mapped","utils$2","getSideChannel","utils$1","formats$1","has$3","arrayPrefixGenerators","isArray$2","push$1","pushToArray","toISO","defaultFormat","defaults$1","isNonNullishPrimitive","sentinel","stringify$1","object","prefix","generateArrayPrefix","commaRoundTrip","strictNullHandling","skipNulls","encoder","filter","sort","allowDots","serializeDate","formatter","encodeValuesOnly","sideChannel","tmpSc","step","findFlag","objKeys","adjustedPrefix","valueSideChannel","keyPrefix","normalizeStringifyOptions","stringify_1","arrayFormat","joined","has$2","isArray$1","interpretNumericEntities","parseArrayValue","isoSentinel","charsetSentinel","parseValues","cleanStr","limit","skipIndex","bracketEqualsPos","pos","parseObject","leaf","root","cleanRoot","parseKeys","brackets","child","segment","parent","normalizeParseOptions","parse$1","tempObj","newObj","stringify","parse","formats","lib","fabric","virtualWindow","_once","_removeEventListener","listenersForEvent","callback","filler","atan2","pow","PiBy180","PiBy2","angle","sign","angleSlice","rx","ry","alpha","phi","strokeUniformScalar","getStrokeHatVector","B","bisectorVector","scalar","miterVector","t","points","width","yPoints","height","r","o","number","fontSize","unit","attributes","len","img","div","numTotalObjects","context","patterns","numPatterns","p","enlivenedPatterns","elements","properties","destination","newCanvas","scaleX","scaleY","scaleMatrix","multiply","degreesToRadians","matrix","tolerance","y","l","_isTransparent","meetOrSlice","aspectRatioAttrs","align","alignX","alignY","finalTransform","center","bbox","b","prevStyle","forTextSpans","styles","textLines","charIndex","commandLengths","repeatedCommands","toX","toY","cp1X","cp1Y","cp2X","cp2Y","fromX","py","pl","cx1","cy1","dtheta","segments","mT","th3","tb","bounds","abs","tvalues","sqrtb2ac","t1","t2","mt","rot","large","sweep","tx","ty","x1","current","y1","controlX","controlY","previous","destinationPath","perc","nextLen","tempInfo","totalLength","info","infos","command","segPercent","currentPath","re","rArcSeq","rNumberCommaWsp","match","coordsStr","path","coords","coordsParsed","correction","multSignX","multSignY","p1","transform","newSegment","point","k","condition","firstLetterOnly","chr","graphemes","property","parentMethod","klass","Subclass","element","touchProp","_evt","setOpacity","es","toArray","sliceCanConvertNodelists","arr","prop","wrapper","docElement","body","left","top","doc","scrollLeftTop","offsetAttributes","box","getElementStyle","selectProp","impl","ctx","onComplete","xhr","method","RUNNING_ANIMATIONS","animation","requestAnimFrame","duration","finish","onChange","abort","easing","isMany","byValue","timePerc","_cancelAnimFrame","originalOnComplete","originalOnChange","calculateColor","valuePerc","easeInBounce","toFixed","parseUnit","multiplyTransformMatrices","svgValidTagNames","svgViewBoxElements","svgInvalidAncestors","svgValidParents","attributesMap","colorAttributes","fSize","attr","parentAttributes","fillIndex","nodeName","nodeArray","multiplierY","commaWsp","skewX","skewY","rotate","scale","translate","transforms","transformList","reTransformList","operation","translateMatrix","rotateMatrix","combinedMatrix","matrices","style","oStyle","firstMatching","selector","classNames","id","matcher","nodelist","xlinkAttribute","el2","parentNode","oldLength","namespace","applyViewboxTransform","el3","viewBoxWidth","widthAttr","heightAttr","missingViewBox","missingDimAttr","toBeParsed","parsedDim","preserveAspectRatio","minX","el","descendants","xLink","recursivelyParseGradientsXlink","gradientsAttrs","referencedGradient","gradient","fontWeight","lineHeight","fontFamily","elList","memo","getGlobalStylesForElement","ownAttributes","cssAttrs","normalizedAttr","normalizedValue","normalizedStyle","parseStyleString","parseStyleObject","allRules","styleContents","rules","ruleObj","_rule","proto","_this","_newObj","container","objTransformInv","clipPathOwner","clipPath","gTransform","uaT","ubT","uB","ub","length","b1","inter","max","topRight","bottomLeft","color","min","h","g","average","currentAlpha","otherColor","isShortNotation","isRGBa","LEFT","opposite","canvas","canvasOptions","uniformIsToggled","lockX","lockY","scaleProportionally","control","constraint","actionPerformed","fireEvent","zoom","padding","localPoint","totalSkewSize","currentSkew","newSkew","targetHasOneFlip","compensateScaleForSkew","localPointFromCenter","pivotPoint","curAngle","snapThreshold","leftAngleLocked","hasRotated","by","newPoint","signX","signY","dim","original","originalDistance","isTransformCentered","oldScaleX","controls","strokePadding","oldWidth","newWidth","newLeft","newTop","moveX","moveY","styleOverride","ySize","transparentCorners","methodName","stroke","myTop","xSize","myLeft","xSizeBy2","objectVisibility","sinHalfOffset","cosHalfOffsetComp","sinHalfOffsetComp","cornerHypotenuse","newTheta","newThetaComp","cosHalfOffset","offset","keyValuePairs","colorAlpha","opacity","markup","offsetX","withViewport","gradientUnits","offsetY","commonAttributes","colorStops","percentageShift","multiplier","type","transformMatrix","propValue","patternSource","patternImgSrc","offsetsAndBlur","BLUR_BOX","fBoxX","fBoxY","getElementOffset","removeFromArray","transformPoint","invertTransform","getNodeCanvas","createCanvasElement","CANVAS_INIT_ERROR","lowerCanvasEl","canvasEl","cssValue","backgroundObject","overlayObject","activeObject","vpt","fill","m","extend","originalValue","bgColor","overlayColor","bgImage","overlayImage","NUM_FRACTION_DIGITS","viewBox","fontList","row","_char","finalHeight","additionalTransform","repeat","finalWidth","objs","idx","newIdx","shadow","p2","cDistance","lastPoint","newPoints","circle","circles","group","circleRadius","pointerPoint","rects","uniqueRects","patternCanvas","patternCtx","topLeft","isTouchEvent","objsToRender","activeGroupObjects","activeObjects","isTransparent","action","centerTransform","origin","corner","actionHandler","altKey","viewportStart","start","extent","minY","maxX","maxY","strokeOffset","aObjects","isTouch","shouldLookForActive","activeTargetSubs","pointerToUse","subTarget","pointer","upperCanvasEl","boundsWidth","boundsHeight","cssScale","added","oldObjects","oldObject","removed","somethingChanged","originalValues","removeListener","addEventOptions","eventTypePrefix","functor","_target","e","changedTouches","evt","addListener","isClick","checkClick","shouldRender","mouseUpHandler","originalMouseUpHandler","targets","eventType","mouseDownHandler","targetChanged","inOpt","outOpt","inFires","outFires","activeSelection","hoverCursor","isActiveLower","aGroup","currentObject","allowIntersect","quality","cropping","originalWidth","originalHeight","newZoom","vp","translateX","translateY","originalInteractive","newVp","originalRetina","originalContextTop","renderOnAddRemove","loaded","clone","objectCaching","dims","capValue","neededX","neededY","minCacheSize","dimensionsChanged","zoomChanged","shouldRedraw","canvasHeight","sizeShrinking","canvasWidth","shouldResizeCanvas","sizeGrowing","additionalWidth","additionalHeight","drawingWidth","drawingHeight","stateProperties","isChanged","groupNeedsUpdate","drawBorders","drawControls","multX","multY","scaling","pCanvas","pCtx","originalGroup","shadowOffset","shadowBlur","objectLeftTop","pClicked","originXOffset","originYOffset","fromOriginX","toOriginX","fromOriginY","toOriginY","position","hypotFull","offsetFrom","offsetTo","multiplyMatrices","absolute","intersection","pointTL","pointBR","other","boundingRect","iLine","xi","a2","xcount","cos","cosP","cosPMinusSinP","lineCoords","startMatrix","finalMatrix","w","sep","cache","dimX","dimY","dimensions","str","strokeDashArray","visibility","strokeWidth","fontStyle","textDecoration","deltaY","useWhiteSpace","svgTransform","commonPieces","reviver","styleInfo","shadowInfo","absoluteClipPath","vectorEffect","objectMarkup","props","origValue","propertySet","ey","xPoints","hasControls","strokeUniform","borderScaleFactor","callbacks","propsToAnimate","skipCallbacks","to","propPair","coordProps","yMult","parsedAttributes","axis1","axis2","dimension","nearest","farthest","svgString","end","radius","heightBy2","widthBy2","piBy2","isRounded","rect","projectStrokeOnPoints","correctLeftTop","aX","aY","deltaX","skipControls","objectTop","objsToObject","maxXY","newGroup","childrenOverride","global","backend","imageMarkup","imageRendering","strokeSvg","minimumScale","objectScale","cacheKey","filters","sX","sY","maxDestH","rWidth","pAR","offsetLeft","offsetTop","cropX","cropY","rHeight","gl","isSupported","canUseUint8Clamped","imageBuffer","startTime","targetCanvas","copyGLTo2DDrawImage","copyGLTo2DPutImageData","drawImageTime","tempFbo","resizeCanvasIfNeeded","dWidth","dHeight","numBytes","u8","u8Clamped","originalImageData","pipelineState","fragmentSource","vertexSource","uniformLocations","buffer","_class","helpLayer","createClass","iLen","brightness","weights","side","sw","sh","dst","scx","scy","mode","noise","jLen","_i","_iLen","_jLen","distance","lowC","highC","tr","texture","resources","canvas1","blendData","ceil","lobeFunction","filterWindow","taps","offsets","fragmentShader","dW","newData","mult","stepH","tmpCanvas","dH","blue","cacheLanc","fY","weight","process","destData","rcpRatioX","ratioY","w4","pixels","destPixels","xDiff","yDiff","d","ratioWHalf","ratioHHalf","img2","dy","centerX","contrastF","adjust","amt","canvas2","ctx2","random","ctx1","percent","blurScale","delta","rInv","diffSpace","numberOfSpaces","charBound","currentLineWidth","heightOfLine","lineLeftOffset","leftOffset","lineTopOffset","boxStart","drawStart","lastColor","currentColor","boxWidth","previousFontDeclaration","previousWidth","fontCache","coupleWidth","kernedWidth","stylesAreEqual","lineInfo","graphemeInfo","positionInPath","reverse","grapheme","lineBounds","totalPathLength","startingPoint","charSpacing","maxHeight","lineHeights","isJustify","actualStyle","nextStyle","charBox","timeToRender","shortCut","isLtr","drawingLeft","currentDirection","charsToRender","shouldStroke","shouldFill","decl","lineDiff","isEndOfWrapping","textAlign","direction","charStyle","topOffset","lastDecoration","lastFill","currentDecoration","currentFill","_dy","fontIsGeneric","family","forMeasuring","newLine","newLines","newText","isAddingPath","_key","needsDims","parsedAnchor","textContent","lineHeightDiff","scaledDiff","textHeight","offX","textInstance","styleObject","stylePropertyValue","letterCount","allStyleObjectPropertiesMatch","line","selectionStart","startIndex","endIndex","lineStyle","skipRestore","lineIndex","boundaries","cursorWidth","selectionEnd","startLine","endLine","startChar","endChar","boxEnd","drawWidth","drawHeight","objCopy","parseDecoration","tickState","shouldClear","text","reNonWord","currentStart","currentEnd","newSelectionStart","graphemeStart","graphemeEnd","cursorLocation","charHeight","retinaScaling","upperCanvas","upperCanvasWidth","upperCanvasHeight","maxWidth","hiddenTextarea","isTextChanged","lineStart","charStart","lineEnd","charEnd","numericChar","numericLine","isEndOfLine","qty","currentCharStyle","numIndex","newLineStyles","somethingAdded","quantity","numericIndex","newStyle","insertedText","addedLines","copiedStyle","linesLength","cursorLoc","newSelection","mouseOffset","distanceBtwNextCharAndCursor","charCount","nextCharCount","charDiff","selection","removedText","removeFrom","removeTo","fromPaste","textAfterCursor","textBeforeCursor","indexOnLine","charWidth","widthOfCharsOnLine","newValue","textAndBg","dySpan","textTopOffset","textSpans","textInfo","map","nextLineIndex","shouldLimit","nextOffset","charOffset","prevGrapheme","splitByGrapheme","infix","additionalSpace","reservedSpace","words","wordWidth","lineWidth","graphemeLines","infixWidth","lines","linesToKeep","scaleSkewStyleHandler","scaleStyleHandler","scalingEqually","scalingYOrSkewingX","scalingXOrSkewingY","scaleOrSkewActionName","textBoxControls","column","useFabricCanvas","appConstants","useDesignStore","freeGlobal$1","_freeGlobal","freeGlobal","freeSelf","root$2","_root","root$1","now$2","now_1","reWhitespace","trimmedEndIndex","reTrimStart","Symbol$4","_Symbol","Symbol$3","objectProto$1","hasOwnProperty$1","nativeObjectToString$1","symToStringTag$1","objectProto","nativeObjectToString","Symbol$2","getRawTag","objectToString$1","nullTag","undefinedTag","symToStringTag","baseGetTag","isObjectLike","symbolTag","baseTrim","isObject$3","isSymbol","NAN","reIsBadHex","reIsBinary","reIsOctal","freeParseInt","isObject$2","now$1","toNumber$1","FUNC_ERROR_TEXT","nativeMax","nativeMin","lastThis","maxWait","timerId","lastCallTime","lastInvokeTime","leading","maxing","trailing","wait","timeSinceLastInvoke","timeWaiting","timeSinceLastCall","invokeFunc","lastArgs","isInvoking","debounced","setScrollbarWidthCssVar","run","outer","dayjs","getMobileOperatingSystem","currentOS","checkIosVersion","agent","endpoints","mediaRecorderInstance","stream","audioFromWebCam","audioTouse","audioSourceNode","audioFromSong","audioToUse","audioContext","audioToUseSource","gainNode","mergerNode","canvasStream","mediaRecorder","selectedTheme","_c","_f","formData","file","recaptchaResponse","pinia","global_1","check","fails","descriptors","$propertyIsEnumerable","getOwnPropertyDescriptor$2","NASHORN_BUG","f$4","objectPropertyIsEnumerable","createPropertyDescriptor","toString","classofRaw","split","indexedObject","requireObjectCoercible","toIndexedObject","isObject$1","toPrimitive","PREFERRED_STRING","toObject","hasOwnProperty","has$1","document$1","EXISTS","documentCreateElement","ie8DomDefine","$getOwnPropertyDescriptor","f$3","O","P","objectGetOwnPropertyDescriptor","anObject","f$2","objectDefineProperty","createNonEnumerableProperty","setGlobal","SHARED","store$1","sharedStore","functionToString","WeakMap$1","nativeWeakMap","shared","postfix","uid","keys$1","sharedKey","hiddenKeys$1","OBJECT_ALREADY_INITIALIZED","WeakMap$2","set","enforce","getterFor","wmget","wmhas","wmset","metadata","get","has","redefine","enforceInternalState","TEMPLATE","simple","noTargetGet","state","aFunction$1","getBuiltIn","floor","toInteger","min$1","toLength","toAbsoluteIndex","createMethod$3","arrayIncludes","indexOf","objectKeysInternal","enumBugKeys","hiddenKeys","f$1","objectGetOwnPropertyNames","f","objectGetOwnPropertySymbols","ownKeys","getOwnPropertySymbols","copyConstructorProperties","defineProperty","getOwnPropertyDescriptor","replacement","isForced","normalize$1","NATIVE","POLYFILL","isForced_1","getOwnPropertyDescriptor$1","_export","GLOBAL","STATIC","FORCED","sourceProperty","descriptor","targetProperty","aFunction","functionBindContext","isArray","engineUserAgent","process$1","versions","v8","version","nativeSymbol","useSymbolAsUid","WellKnownSymbolsStore","Symbol$1","createWellKnownSymbol","wellKnownSymbol","SPECIES","arraySpeciesCreate","C","push","createMethod$2","IS_FILTER","IS_SOME","IS_EVERY","IS_FIND_INDEX","IS_FILTER_OUT","NO_HOLES","self","boundFunction","create","TYPE","arrayIteration","arrayMethodIsStrict","$forEach","STRICT_METHOD","arrayForEach","CollectionPrototype","propertyIsEnumerable","createMethod$1","objectToArray","$entries","objectSetPrototypeOf","test","setter","CORRECT_SETTER","aPossiblePrototype","inheritIfRequired","NewTarget","NewTargetPrototype","$this","objectDefineProperties","html","GT","LT","PROTOTYPE","SCRIPT","IE_PROTO","EmptyConstructor","scriptTag","NullProtoObjectViaActiveX","activeXDocument","temp","NullProtoObjectViaIFrame","JS","iframeDocument","iframe","NullProtoObject","Properties","whitespaces","whitespace","ltrim","rtrim","createMethod","stringTrim","getOwnPropertyNames","defineProperty$1","trim","NUMBER","NativeNumber","NumberPrototype","BROKEN_CLASSOF","toNumber","it","third","digits","NumberWrapper","dummy","ArrayPrototype","$includes","addToUnscopables","_typeof","__assign","script$2","baseProps","withoutEntry","withoutEntryExit","defaultDuration","durationObj","enter","leave","insertDuration","slotItems","emit","insertLeaveDuration","FunctionPrototype","FunctionPrototypeToString","nameRE","NAME","firstChar","transitionName","ref","insertAt","head","styleInject","script$1","_imports_1$2","_imports_2$1","iconClass","classList","modal","teleportTarget","onMounted","modalInstance","onBeforeUnmount","hide","onShow","isActive","onShown","_b","onHide","onHidden","modalDialogClass","modalContentClass","cssVar","each","setProperty","deps","F","allElements","contents","wholeText","appendChild","WORDS","_","CHARS","key2","results","Splitting","LAYOUT","totalCells","createElement","designStore","selectedOption","defaultOptionRef","errorModalRef","selectOption","isBusy","imgEl","continueHandler","osVersion","os","emits","loadSceneSprite","sceneTwoEelement","sceneThreeEelement","currentScene","tempSprite","_a","count","circleRef","isClient","onScopeDispose","off","fns","param","defaultDocument","defaultNavigator","isMounted","cleanup","mediaQuery","update","matches","tryOnScopeDispose","window","useMediaQuery","shortcutMethods","shortcuts","globalKey","_global","__getOwnPropSymbols$e","__hasOwnProp$e","__propIsEnum$e","__defNormalProp$c","__spreadValues$c","files","document","input","trigger","hasOwn","reset","__getOwnPropSymbols$5","__hasOwnProp$5","__propIsEnum$5","__defNormalProp$5","__spreadValues$5","_navigator","granted","streamCamRef","canvasPlaceholderRef","picTakenPlaceholderRef","enableStartButton","placePicIntoFabric","takeaPicture","removeStreamVideoFromFabric","loadWebcamStream","imgInstance","streamCamElement","webcam","loadStreamingWebcam","checkItemIncanvas","onUnmounted","previewStore","enableRecordButton","isVideoRecorded","clickStarRecordButton","isRecordingWebCam","countDown","recordAnimatedButtonRef","recordVideoHandler","startRecoder","createObjectURL","recordStreamCamRef","recordstreamCamElement","selectMediaType","selectedMediaType","removeRecorderdVideo","_imports_0$2","_imports_1$1","_imports_2","defaultTextboxValue","nameTextBox","objTarget","item2","addTextbox","initCanvas","_extends","then","cb","deferred","ownProp","widgetId","emitVerify","emitExpired","emitError","recaptcha","$root","defaultContent","behavior","failedExecuteInvalidEnumValue","backupMethod","isObject","scrollingElement","event","now","currentX","currentY","nonFinite","isConnected","scrollWithOptions","startY","targetX","targetY","removeEventListener","cancelScroll","isWindow","createScroll","scrollName","scroll","elementScroll","normalizeWritingMode","calcPhysicalAxis","isLTR","layout","writingMode","isXReversed","toPhysicalAlignment","mapNearest","elementEdgeStart","elementEdgeEnd","canOverflow","overflow","getFrameElement","isScrollable","parentElement","pElement","clamp","getSupportedScrollMarginProperty","getElementScrollSnapArea","scrollProperty","right","bottom","calcAlignEdge","getFrameViewport","computeScrollIntoView","ownerWindow","computedStyle","ownerDocument","eAlignH","eAlignV","diffX","diffY","actions","frame","scrollIntoView","canvasContainerRef","recaptchaRef","nextStepHandler","backToPreviousStep","activeStep","createPreview","onVerify","videoFileType","scrollTo","btmEl","_imports_0$1","_imports_1","useShare","_imports_0","previewVideoRef","previewImageRef","downloadHref","sharingFile","isTranscoding","setBlobIntoVideo","setImageIntoImg","urltoFile","onVideoPlay","backToHomePage","videoBlob","imageString","shareToSocialMedia","share","fileName","sceneSpriteList","currentStep","backtoHomeHandler","loadFabricAssets","watchEffect","_sfc_main","useBreakpoints","setCssHelperVars","objectToString","__SENTRY__","DEFAULT_MAX_STRING_LENGTH","elem","sepLength","maxStringLength","nextStr","currentElem","classes","keyAttrs","keyAttrPairs","className","WINDOW$7","host","projectId","projectMatch","components","CONSOLE_LEVELS","wrappedLevels","originalConsole","level","enabled","logger","consoleSandbox","GLOBAL_OBJ","output","pattern","requireExactStringMatch","isRegExp","isString","testString","wrapped","markFunctionWrapped","addNonEnumerableProperty","extractedProps","serialized","truncate","memoizationMap","returnValue","inputValue","WEBPACK_ERROR_REGEXP","frames","createStackParser","stackParser","lastFrameFunction","localStack","defaultFunctionName","sandbox","isChromePackagedApp","hasHistoryApi","SENTRY_XHR_DATA_KEY","handlers","instrumented","instrumentConsole","instrumentDOM","instrumentXHR","instrumentFetch","instrumentHistory","instrumentError","instrumentUnhandledRejection","instrument","handler","triggerHandlers","originalConsoleMethod","handlerData","originalFetch","resource","hasProp","xhrInfo","originalOpen","sentryXhrData","originalSend","WINDOW$4","lastHref","oldOnPopState","lastCapturedEvent","shouldSkipDOMEvent","debounceTimerID","shouldShortcircuitPreviousDebounce","globalDOMEventHandler","handlerForType","originalAddEventListener","originalRemoveEventListener","_oldOnErrorHandler","_oldOnUnhandledRejectionHandler","inner","crypto","firstException","eventId","values","currentMechanism","newMechanism","maxSize","normalizeToSize","normalized","maxProperties","overriddenDepth","numAdded","isSyntheticEvent","States","onfulfilled","onrejected","isRejected","onfinally","cachedHandlers","task","remove","timeout","resolvedSyncPromise","fragment","dateTimestampSource","dynamicRequire","timestampSource","platformPerformance","dateTimestampInSeconds","timestampInSeconds","timestampWithMs","browserPerformanceTimeOrigin","performanceNow","dateNow","timeOriginDelta","threshold","timeOriginIsReliable","navigationStart","navigationStartDelta","navigationStartIsReliable","performance","TRACEPARENT_REGEXP","parentSampled","envelope","textEncoder","append","stringifiedPayload","merged","attachment","dropUndefinedKeys","sdkInfo","tunnel","dsn","discarded_events","timestamp","DEFAULT_RETRY_AFTER","headerDate","limits","rateLimitHeader","retryAfterHeader","headerDelay","delay","updatedRateLimits","statusCode","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","MAX_BAGGAGE_STRING_LENGTH","baggageHeader","baggageObject","dynamicSamplingContext","dscValue","newBaggageHeader","session","updateSession","status","newScope","captureContext","transactionName","processors","hint","processor","isThenable","getGlobalEventProcessors","DEFAULT_BREADCRUMBS","client","scope","syntheticException","exception","message","finalBreadcrumb","mergedBreadcrumb","makeMain","closeSession","currentSession","getMainCarrier","oldHub","setHubOnCarrier","getHubFromCarrier","maybeOptions","maybeHub","errorsInstrumented","addInstrumentationHandler","activeTransaction","errorCallback","span","Span","spanContext","childSpan","nameStr","idStr","logMessage","sampledString","incomingDynamicSamplingContext","prev","transaction","maybeSampleRate","sample_rate","dsc","FINISH_REASON_TAG","IDLE_TRANSACTION_FINISH_REASONS","_pushActivity","_popActivity","transactionSpanId","maxlen","transactionContext","_idleHub","_idleTimeout","_finalTimeout","_heartbeatInterval","_onScope","keepSpan","popActivity","endTimestamp","heartbeatString","samplingContext","sampleRate","isValidSampleRate","rate","customSamplingContext","configInstrumenter","transactionInstrumenter","hub","idleTimeout","finalTimeout","onScope","heartbeatInterval","carrier","registerErrorInstrumentation","getCurrentHub","port","tunnelOrOptions","envelopeHeaders","envelopeItem","enhanceEventWithSdkInfo","createEnvelope","existingInstance","integrationsByName","userIntegrations","defaultIntegrations","integration","integrations","debugIndex","finalIntegrations","setupIntegration","integrationIndex","installedIntegrations","prepared","applyClientOptions","applyIntegrationsMetadata","applyDebugMetadata","finalScope","attachments","normalizeEvent","cachedDebugIdStackFrameCache","debugIdStackFramesCache","debugIdStackParserCache","cachedParsedStack","parsedStack","errorFileNames","filenameDebugIdMap","images","integrationNames","BaseClient","promisedEvent","transport","env","createAttachmentEnvelopeItem","errored","crashed","sessionNonTerminal","interval","ticked","prepareEvent","finalEvent","sentryError","isError","beforeSendLabel","rejectedSyncPromise","processedEvent","beforeSendResult","beforeSend","isTransactionEvent$1","beforeSendTransaction","clientClass","makeRequest","forEachEnvelopeItem","filteredEnvelopeItems","recordEnvelopeLoss","requestTask","rateLimits","originalFunctionToString","clientOptions","eventProcess","addGlobalEventProcessor","internalOptions","_isIgnoredError","_isIgnoredTransaction","_isDeniedUrl","_isAllowedUrl","_getPossibleEventMessages","ignoreOnError","before","withScope","addExceptionTypeValue","addExceptionMechanism","captureException","ex","sentryWrapped","isUnhandledRejection","normalizeDepth","extractExceptionKeysForMessage","popSize","attachStacktrace","eventFromError","BREADCRUMB_INTEGRATION_ID","htmlTreeAsString","breadcrumb","parsedFrom","parsedLoc","feedback","WINDOW$2","breadcrumbIntegration","contentWindow","fetchImpl","cachedFetchImpl","nativeFetch","pendingCount","pendingBodySize","CHROME_PRIORITY","WINJS_PRIORITY","GECKO_PRIORITY","colno","chromeEvalRegex","chrome","subMatch","chromeStackLineParser","geckoREgex","geckoEvalRegex","gecko","createFrame","geckoStackLineParser","winjsRegex","winjs","winjsStackLineParser","defaultStackLineParsers","defaultStackParser","extractSafariExtensionDetails","isSafariWebExtension","isSafariExtension","installFunc","globalHandlerLog","_eventFromIncompleteOnError","_enhanceEventWithInitialFrame","eventFromUnknownInput","addMechanismAndCapture","_eventFromRejectionWithPrimitive","ev","ev0","ev0s","ev0sf","lineno","filename","eventTargetOption","wrap","originalFunction","wrapOptions","eventName","originalEventHandler","DEFAULT_LIMIT","parser","stack","eventProcessor","_isSameExceptionEvent","previousMessage","currentMessage","currentException","previousException","previousFrames","currentFrames","frameB","frameA","previousFingerprint","currentFingerprint","initAndBind","startSessionTracking","startSessionOnHub","REPLAY_SESSION_KEY","REPLAY_EVENT_NAME","UNABLE_TO_SEND_REPLAY","SESSION_IDLE_DURATION","MAX_SESSION_LIFE","DEFAULT_FLUSH_MIN_DELAY","DEFAULT_FLUSH_MAX_DELAY","ERROR_CHECKOUT_TIME","RETRY_BASE_INTERVAL","RETRY_MAX_COUNT","NETWORK_BODY_MAX_SIZE","NodeType","tagName","actualType","isInputTypeMasked","maskInputSelector","maskInputFn","originalGetImageData","getImageData","IGNORED_NODE","processedTagName","cssStringified","canvasCtx","RELATIVE_PATH","DATA_URI","maybeQuote","SRCSET_COMMAS_OR_SPACES","chars","collectCharacters","inParens","descriptorsStr","absoluteToDoc","getAbsoluteSrcsetString","absoluteToStylesheet","maskAllText","_shouldMaskAttribute","maskTextFn","attribute","needMaskingText","readyState","fired","iframeEl","rootId","skipAttribute","stylesheet","cssText","n","checked","is2DCanvasBlank","blankCanvas","canvasDataURL","canvasService","oldValue","image","err","recordInlineImage","needBlock","isScript","parentTagName","defaultMaskFn","maybeAttr","sn","lowerIfExists","slimDOMExcluded","_serializedNode","onSerialize","serializedNode","recordChild","slimDOMOptions","preserveWhiteSpace","serializedChildNode","onceIframeLoaded","serializedIframeNode","onIframeLoad","idNodeMap","serializeNodeWithId","maskAllInputs","slimDOM","EventType","IncrementalSource","MouseInteractions","CanvasContext","MediaInteractions","ReplayerEvents","_mirror","remaining","blockClass","isBlocked","isAncestorRemoved","win","isNodeInLinkedList","mutations","addList","getNextId","nextId","ns","pushAdd","rootShadowHost","_e","isIframeINode","hasShadowRoot","adds","isParentRemoved","isAncestorInSet","parentId","candidate","old","newPriority","styleObj","deepDelete","targetId","addsSet","mutationBuffers","mutationBuffer","angularZoneSymbol","mutationObserverCtor","observer","callbackThreshold","sampling","timeBaseline","callbackWrapper","positions","updatePosition","wrappedCb","on","getHandler","disableMap","lastW","lastH","lastInputValueMap","userTriggered","INPUT_TAGS","ignoreSelector","isChecked","hasInputMaskOptions","cbWithDedup","lastInputValue","inputCb","propertyDescriptor","hookProperties","childRule","hasNestedCSSRule","styleSheetRuleCb","canMonkeyPatchNestedCSSRule","supportedNestedCSSRuleTypes","unmodifiedFunctions","styleDeclarationCb","mediaInteractionCb","fontMap","originalFontFace","fontFace","fontCb","hooks","mutationCb","mousemoveCb","mouseInteractionCb","scrollCb","viewportResizeCb","canvasMutationCb","mergeHooks","mousemoveHandler","mouseInteractionHandler","scrollHandler","viewportResizeHandler","inputHandler","mediaInteractionHandler","styleSheetObserver","styleDeclarationObserver","fontObserver","pluginHandlers","mutationObserver","manager","shadowRoot","initMutationObserver","initScrollObserver","props2D","recordArgs","pix","lookup","base64","contextMap","webGLVarMap","serializeArg","isInstanceOfWebGLObject","saveWebGLVar","mutation","canvas2DReset","canvasWebGL1and2Reset","canvasContextReset","__rest","takeFullSnapshot","mousemoveWait","_maskInputOptions","_slimDOMOptions","polyfill","incrementalSnapshotCount","plugin","wrappedEmit","lastFullSnapshotEvent","exceedTime","exceedCount","wrappedScrollEmit","wrappedCanvasMutationEmit","iframeManager","canvasManager","shadowDomManager","mirror","_d","init","record","currentList","newList","entry","newEntries","newNavigationEntries","existingLcpEntries","newLcpEntry","replay","performanceObserver","isCheckout","addEventPromises","initialTime","expiry","targetTime","isExpired","WINDOW$1","started","lastActivity","segmentId","sampled","stickySession","saveSession","isSessionExpired","makeSession","createSession","addEvent","normalizedKey","addBreadcrumbEvent","targetNode","includeAfterSendEventHandling","isErrorEvent","addInternalBreadcrumb","afterSendHandler","addBreadcrumb","entries","createPerformanceSpans","_isSentryRequest","shouldFilterRequest","addNetworkBreadcrumb","bodySize","filteredHeaders","reqSize","resSize","requestBodySize","responseBodySize","size","bodyText","getBodySize","buildNetworkRequestOrResponse","allHeaders","getHeadersFromOptions","fetchArgs","allowedHeaders","getAllHeaders","getAllowedHeaders","parseContentLengthHeader","responseHeaders","_isXhrBreadcrumb","enrichXhrBreadcrumb","captureXhrBreadcrumbToReplay","_isFetchBreadcrumb","enrichFetchBreadcrumb","captureFetchBreadcrumbToReplay","_LAST_BREADCRUMB","newBreadcrumb","createBreadcrumb","handleNetworkBreadcrumbs","hasHooks","replayId","createMemoryEntry","time","ENTRY_TYPES","startTimeOrNavigationActivation","maxTimerId","callbackReturnValue","hadFirstEvent","earliestEvent","replayEvent","recordingData","createEventEnvelopeHeaders","payloadWithSequence","preparedEvent","replayData","retryConfig","setContext","msg","cbResult","oldSessionId","addGlobalListeners","_context","eventContext","mutationLimit","mutationBreadcrumbLimit","overMutationLimit","captureBodies","defaultHeaders","selectors","defaultSelectors","deprecatedClassOption","deprecatedSelectorOption","allSelectors","maskSelector","unmaskSelector","block","blockSelector","maskTextClass","Replay","sessionSampleRate","errorSampleRate","MEDIA_SELECTORS","_initialized","finalOptions","initialOptions","WINDOW","metric","reportAllChanges","forceReport","prevValue","generateUniqueID","getNavigationEntryFromPerformanceTiming","navigationEntry","getNavigationEntry","getActivationStart","initMetric","navigationType","observe","po","once","onCLS","sessionValue","sessionEntries","lastSessionEntry","report","handleEntries","stopListening","trackChanges","firstHiddenTime","getVisibilityWatcher","onFID","reportedMetricIDs","onLCP","_measurements","_lcpEntry","_clsEntry","_trackFID","lcpCallback","clsCallback","performanceEntries","requestStartTimestamp","_addNavigationSpans","responseStartTimestamp","_addMeasureSpans","shouldRecord","_addResourceSpans","_performanceCursor","_trackNavigator","measurementTimestamp","fidMark","_startChild","measurementName","_tagMetricInfo","timeOrigin","measureEndTimestamp","measureStartTimestamp","_addPerformanceNavigationTiming","_addRequest","description","eventEnd","resourceName","connection","isMeasurementValue","defaultRequestInstrumentationOptions","shouldCreateSpan","shouldAttachHeadersWithTargets","shouldAttachHeaders","spans","traceFetch","fetchCallback","traceXHR","xhrCallback","currentSpan","sentryTraceHeader","sentryBaggageHeader","newHeaders","newBaggageHeaders","existingBaggageHeader","customStartTransaction","startTransactionOnPageLoad","startTransactionOnLocationChange","startingUrl","DEFAULT_BROWSER_TRACING_OPTIONS","addTracingExtensions","_options","startTrackingLongTasks","startTrackingInteractions","instrumentRouting","markBackgroundTransactions","registerBackgroundTabDetection","_experiments","instrumentOutgoingRequests","isPageloadTransaction","sentryTraceMetaTagValue","baggageMetaTagValue","traceParentData","baggageHeaderToDynamicSamplingContext","expandedContext","modifiedContext","finalContext","idleTransaction","addPerformanceEntries","op","currentTransaction","inflightInteractionTransaction","classifyRE","classify","ROOT_COMPONENT_NAME","ANONYMOUS_COMPONENT_NAME","formatComponentName","generateComponentTrace","currentRecursiveSequence","vm","tree","attachErrorHandler","app","trace","errorHandler","warnHandler","hasConsole","VUE_OP","HOOKS","mixins","shouldTrack","internalHook","oldSpan","finishRootSpan","globalWithVue","DEFAULT_CONFIG","init$1","arrayify","vueInit","appWithInstance","hasTracingEnabled","createTracingMixins","configureAxios"],"sources":["../../vite/modulepreload-polyfill","../../node_modules/axios/lib/helpers/bind.js","../../node_modules/axios/lib/utils.js","../../node_modules/axios/lib/helpers/buildURL.js","../../node_modules/axios/lib/core/InterceptorManager.js","../../node_modules/axios/lib/helpers/normalizeHeaderName.js","../../node_modules/axios/lib/core/enhanceError.js","../../node_modules/axios/lib/core/createError.js","../../node_modules/axios/lib/core/settle.js","../../node_modules/axios/lib/helpers/cookies.js","../../node_modules/axios/lib/helpers/isAbsoluteURL.js","../../node_modules/axios/lib/helpers/combineURLs.js","../../node_modules/axios/lib/core/buildFullPath.js","../../node_modules/axios/lib/helpers/parseHeaders.js","../../node_modules/axios/lib/helpers/isURLSameOrigin.js","../../node_modules/axios/lib/cancel/Cancel.js","../../node_modules/axios/lib/adapters/xhr.js","../../node_modules/axios/lib/defaults.js","../../node_modules/axios/lib/core/transformData.js","../../node_modules/axios/lib/cancel/isCancel.js","../../node_modules/axios/lib/core/dispatchRequest.js","../../node_modules/axios/lib/core/mergeConfig.js","../../node_modules/axios/lib/env/data.js","../../node_modules/axios/lib/helpers/validator.js","../../node_modules/axios/lib/core/Axios.js","../../node_modules/axios/lib/cancel/CancelToken.js","../../node_modules/axios/lib/helpers/spread.js","../../node_modules/axios/lib/helpers/isAxiosError.js","../../node_modules/axios/lib/axios.js","../../node_modules/axios/index.js","../../node_modules/has-symbols/shams.js","../../node_modules/has-symbols/index.js","../../node_modules/function-bind/implementation.js","../../node_modules/function-bind/index.js","../../node_modules/has/src/index.js","../../node_modules/get-intrinsic/index.js","../../node_modules/call-bind/index.js","../../node_modules/call-bind/callBound.js","../../__vite-browser-external","../../node_modules/object-inspect/index.js","../../node_modules/side-channel/index.js","../../node_modules/qs/lib/formats.js","../../node_modules/qs/lib/utils.js","../../node_modules/qs/lib/stringify.js","../../node_modules/qs/lib/parse.js","../../node_modules/qs/lib/index.js","../../src/modules/website/config/axios.ts","../../node_modules/fabric/dist/fabric.js","../../src/modules/website/composables/initFabricPrototype.ts","../../src/modules/website/composables/fabricSprite.ts","../../src/modules/website/composables/fabricCustomVideo.ts","../../src/modules/website/composables/use-fabric-canvas.ts","../../src/modules/website/app.constants.ts","../../src/modules/website/stores/design.ts","../../node_modules/lodash/isObject.js","../../node_modules/lodash/_freeGlobal.js","../../node_modules/lodash/_root.js","../../node_modules/lodash/now.js","../../node_modules/lodash/_trimmedEndIndex.js","../../node_modules/lodash/_baseTrim.js","../../node_modules/lodash/_Symbol.js","../../node_modules/lodash/_getRawTag.js","../../node_modules/lodash/_objectToString.js","../../node_modules/lodash/_baseGetTag.js","../../node_modules/lodash/isObjectLike.js","../../node_modules/lodash/isSymbol.js","../../node_modules/lodash/toNumber.js","../../node_modules/lodash/debounce.js","../../src/modules/core/utilities/css.ts","../../node_modules/dayjs/plugin/advancedFormat.js","../../src/modules/core/utilities/dates.ts","../../src/modules/core/utilities/files.ts","../../src/modules/core/utilities/time.ts","../../src/modules/core/utilities/os.ts","../../src/modules/website/endpoints.ts","../../src/modules/website/composables/use-media-recorder.ts","../../src/modules/website/stores/preview.ts","../../src/modules/website/stores/index.ts","../../node_modules/vue3-transitions/vue3-transitions.esm.js","../../../../../../../images/theme/Scene-one.webp","../../../../../../../images/theme/Scene-two.webp","../../../../../../../images/theme/Scene-three.webp","../../src/modules/core/components/icon.vue","../../src/modules/core/components/modal.vue","../../src/modules/core/components/notifications/use-notifications.ts","../../node_modules/splitting/dist/splitting.js","../../src/modules/website/components/design/design-add-background.vue","../../src/modules/website/components/record-animaited-button.vue","../../node_modules/@vueuse/shared/index.mjs","../../node_modules/@vueuse/core/index.mjs","../../src/modules/website/components/design/design-add-media-photo.vue","../../src/modules/website/components/design/design-add-media-video.vue","../../src/modules/website/components/design/design-add-media.vue","../../src/modules/website/components/design/design-add-media-preview.vue","../../../../../../../images/text/greeting-three.svg","../../../../../../../images/text/greeting-two.svg","../../../../../../../images/text/greeting-one.svg","../../src/modules/website/components/design/design-add-text.vue","../../src/modules/website/components/fabric-canvas.vue","../../node_modules/vue-recaptcha/dist/vue-recaptcha.es.js","../../node_modules/seamless-scroll-polyfill/lib/common.js","../../node_modules/seamless-scroll-polyfill/lib/scroll-end-event.js","../../node_modules/seamless-scroll-polyfill/lib/scroll-step.js","../../node_modules/seamless-scroll-polyfill/lib/scroll.js","../../node_modules/seamless-scroll-polyfill/lib/scrollIntoView.js","../../src/modules/website/components/design/design-static-add-text.vue","../../src/modules/website/components/design/design-page.vue","../../../../../../../images/svg/tnb-logo.svg","../../../../../../../images/svg/header.svg","../../src/modules/website/components/landing/landing-page.vue","../../../../../../../images/design-layout.webp","../../src/modules/website/components/preview/preview-page.vue","../../src/modules/website/components/main-container.vue","../../src/modules/website/website.vue","../../node_modules/@sentry/utils/esm/is.js","../../node_modules/@sentry/utils/esm/worldwide.js","../../node_modules/@sentry/utils/esm/browser.js","../../node_modules/@sentry/utils/esm/error.js","../../node_modules/@sentry/utils/esm/dsn.js","../../node_modules/@sentry/utils/esm/logger.js","../../node_modules/@sentry/utils/esm/string.js","../../node_modules/@sentry/utils/esm/object.js","../../node_modules/@sentry/utils/esm/stacktrace.js","../../node_modules/@sentry/utils/esm/supports.js","../../node_modules/@sentry/utils/esm/vendor/supportsHistory.js","../../node_modules/@sentry/utils/esm/instrument.js","../../node_modules/@sentry/utils/esm/memo.js","../../node_modules/@sentry/utils/esm/misc.js","../../node_modules/@sentry/utils/esm/env.js","../../node_modules/@sentry/utils/esm/node.js","../../node_modules/@sentry/utils/esm/normalize.js","../../node_modules/@sentry/utils/esm/syncpromise.js","../../node_modules/@sentry/utils/esm/promisebuffer.js","../../node_modules/@sentry/utils/esm/url.js","../../node_modules/@sentry/utils/esm/severity.js","../../node_modules/@sentry/utils/esm/time.js","../../node_modules/@sentry/utils/esm/tracing.js","../../node_modules/@sentry/utils/esm/envelope.js","../../node_modules/@sentry/utils/esm/clientreport.js","../../node_modules/@sentry/utils/esm/ratelimit.js","../../node_modules/@sentry/utils/esm/baggage.js","../../node_modules/@sentry/core/esm/constants.js","../../node_modules/@sentry/core/esm/session.js","../../node_modules/@sentry/core/esm/scope.js","../../node_modules/@sentry/core/esm/hub.js","../../node_modules/@sentry/core/esm/utils/hasTracingEnabled.js","../../node_modules/@sentry/core/esm/tracing/utils.js","../../node_modules/@sentry/core/esm/tracing/errors.js","../../node_modules/@sentry/core/esm/tracing/span.js","../../node_modules/@sentry/core/esm/tracing/transaction.js","../../node_modules/@sentry/core/esm/tracing/idletransaction.js","../../node_modules/@sentry/core/esm/tracing/hubextensions.js","../../node_modules/@sentry/core/esm/exports.js","../../node_modules/@sentry/core/esm/api.js","../../node_modules/@sentry/core/esm/envelope.js","../../node_modules/@sentry/core/esm/integration.js","../../node_modules/@sentry/core/esm/utils/prepareEvent.js","../../node_modules/@sentry/core/esm/baseclient.js","../../node_modules/@sentry/core/esm/sdk.js","../../node_modules/@sentry/core/esm/transports/base.js","../../node_modules/@sentry/core/esm/version.js","../../node_modules/@sentry/core/esm/integrations/functiontostring.js","../../node_modules/@sentry/core/esm/integrations/inboundfilters.js","../../node_modules/@sentry/browser/esm/helpers.js","../../node_modules/@sentry/browser/esm/eventbuilder.js","../../node_modules/@sentry/browser/esm/integrations/breadcrumbs.js","../../node_modules/@sentry/browser/esm/userfeedback.js","../../node_modules/@sentry/browser/esm/client.js","../../node_modules/@sentry/browser/esm/transports/utils.js","../../node_modules/@sentry/browser/esm/transports/fetch.js","../../node_modules/@sentry/browser/esm/transports/xhr.js","../../node_modules/@sentry/browser/esm/stack-parsers.js","../../node_modules/@sentry/browser/esm/integrations/globalhandlers.js","../../node_modules/@sentry/browser/esm/integrations/trycatch.js","../../node_modules/@sentry/browser/esm/integrations/linkederrors.js","../../node_modules/@sentry/browser/esm/integrations/httpcontext.js","../../node_modules/@sentry/browser/esm/integrations/dedupe.js","../../node_modules/@sentry/browser/esm/sdk.js","../../node_modules/@sentry/replay/esm/index.js","../../node_modules/@sentry-internal/tracing/esm/browser/types.js","../../node_modules/@sentry-internal/tracing/esm/browser/backgroundtab.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/bindReporter.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/generateUniqueID.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/getNavigationEntry.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/getActivationStart.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/initMetric.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/observe.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/onHidden.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/getCLS.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/getVisibilityWatcher.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/getFID.js","../../node_modules/@sentry-internal/tracing/esm/browser/web-vitals/getLCP.js","../../node_modules/@sentry-internal/tracing/esm/browser/metrics/utils.js","../../node_modules/@sentry-internal/tracing/esm/browser/metrics/index.js","../../node_modules/@sentry-internal/tracing/esm/browser/request.js","../../node_modules/@sentry-internal/tracing/esm/browser/router.js","../../node_modules/@sentry-internal/tracing/esm/browser/browsertracing.js","../../node_modules/@sentry/vue/esm/constants.js","../../node_modules/@sentry/vue/esm/vendor/components.js","../../node_modules/@sentry/vue/esm/errorhandler.js","../../node_modules/@sentry/vue/esm/tracing.js","../../node_modules/@sentry/vue/esm/sdk.js","../../src/modules/website/website.ts"],"sourcesContent":["__VITE_IS_MODERN__&&(function polyfill() {\n const relList = document.createElement('link').relList;\n if (relList && relList.supports && relList.supports('modulepreload')) {\n return;\n }\n for (const link of document.querySelectorAll('link[rel=\"modulepreload\"]')) {\n processPreload(link);\n }\n new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type !== 'childList') {\n continue;\n }\n for (const node of mutation.addedNodes) {\n if (node.tagName === 'LINK' && node.rel === 'modulepreload')\n processPreload(node);\n }\n }\n }).observe(document, { childList: true, subtree: true });\n function getFetchOpts(script) {\n const fetchOpts = {};\n if (script.integrity)\n fetchOpts.integrity = script.integrity;\n if (script.referrerpolicy)\n fetchOpts.referrerPolicy = script.referrerpolicy;\n if (script.crossorigin === 'use-credentials')\n fetchOpts.credentials = 'include';\n else if (script.crossorigin === 'anonymous')\n fetchOpts.credentials = 'omit';\n else\n fetchOpts.credentials = 'same-origin';\n return fetchOpts;\n }\n function processPreload(link) {\n if (link.ep)\n // ep marker = processed\n return;\n link.ep = true;\n // prepopulate the load record\n const fetchOpts = getFetchOpts(link);\n fetch(link.href, fetchOpts);\n }\n}());","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return Array.isArray(val);\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return toString.call(val) === '[object FormData]';\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (toString.call(val) !== '[object Object]') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return toString.call(val) === '[object URLSearchParams]';\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","'use strict';\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n };\n return error;\n};\n","'use strict';\n\nvar enhanceError = require('./enhanceError');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n","'use strict';\n\nvar createError = require('./createError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar createError = require('../core/createError');\nvar defaults = require('../defaults');\nvar Cancel = require('../cancel/Cancel');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n var onCanceled;\n function done() {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', onCanceled);\n }\n }\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';\n var transitional = config.transitional || defaults.transitional;\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(\n timeoutErrorMessage,\n config,\n transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken || config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = function(cancel) {\n if (!request) {\n return;\n }\n reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);\n request.abort();\n request = null;\n };\n\n config.cancelToken && config.cancelToken.subscribe(onCanceled);\n if (config.signal) {\n config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\nvar enhanceError = require('./core/enhanceError');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n },\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional || defaults.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw enhanceError(e, this, 'E_JSON_PARSE');\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('./../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\nvar Cancel = require('../cancel/Cancel');\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new Cancel('canceled');\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(prop) {\n if (prop in config2) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n var mergeMap = {\n 'url': valueFromConfig2,\n 'method': valueFromConfig2,\n 'data': valueFromConfig2,\n 'baseURL': defaultToConfig2,\n 'transformRequest': defaultToConfig2,\n 'transformResponse': defaultToConfig2,\n 'paramsSerializer': defaultToConfig2,\n 'timeout': defaultToConfig2,\n 'timeoutMessage': defaultToConfig2,\n 'withCredentials': defaultToConfig2,\n 'adapter': defaultToConfig2,\n 'responseType': defaultToConfig2,\n 'xsrfCookieName': defaultToConfig2,\n 'xsrfHeaderName': defaultToConfig2,\n 'onUploadProgress': defaultToConfig2,\n 'onDownloadProgress': defaultToConfig2,\n 'decompress': defaultToConfig2,\n 'maxContentLength': defaultToConfig2,\n 'maxBodyLength': defaultToConfig2,\n 'transport': defaultToConfig2,\n 'httpAgent': defaultToConfig2,\n 'httpsAgent': defaultToConfig2,\n 'cancelToken': defaultToConfig2,\n 'socketPath': defaultToConfig2,\n 'responseEncoding': defaultToConfig2,\n 'validateStatus': mergeDirectKeys\n };\n\n utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {\n var merge = mergeMap[prop] || mergeDeepProperties;\n var configValue = merge(prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n};\n","module.exports = {\n \"version\": \"0.25.0\"\n};","'use strict';\n\nvar VERSION = require('../env/data').version;\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')));\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new TypeError('option ' + opt + ' must be ' + result);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw Error('Unknown option ' + opt);\n }\n }\n}\n\nmodule.exports = {\n assertOptions: assertOptions,\n validators: validators\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n if (!config.url) {\n throw new Error('Provided config url is not valid');\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n if (!config.url) {\n throw new Error('Provided config url is not valid');\n }\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n","'use strict';\n\nvar Cancel = require('./Cancel');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(function(cancel) {\n if (!token._listeners) return;\n\n var i;\n var l = token._listeners.length;\n\n for (i = 0; i < l; i++) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = function(onfulfilled) {\n var _resolve;\n // eslint-disable-next-line func-names\n var promise = new Promise(function(resolve) {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Subscribe to the cancel signal\n */\n\nCancelToken.prototype.subscribe = function subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n};\n\n/**\n * Unsubscribe from the cancel signal\n */\n\nCancelToken.prototype.unsubscribe = function unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n var index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.Cancel = require('./cancel/Cancel');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\naxios.VERSION = require('./env/data').version;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","module.exports = require('./lib/axios');","'use strict';\n\n/* eslint complexity: [2, 18], max-statements: [2, 33] */\nmodule.exports = function hasSymbols() {\n\tif (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }\n\tif (typeof Symbol.iterator === 'symbol') { return true; }\n\n\tvar obj = {};\n\tvar sym = Symbol('test');\n\tvar symObj = Object(sym);\n\tif (typeof sym === 'string') { return false; }\n\n\tif (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }\n\tif (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }\n\n\t// temp disabled per https://github.com/ljharb/object.assign/issues/17\n\t// if (sym instanceof Symbol) { return false; }\n\t// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4\n\t// if (!(symObj instanceof Symbol)) { return false; }\n\n\t// if (typeof Symbol.prototype.toString !== 'function') { return false; }\n\t// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }\n\n\tvar symVal = 42;\n\tobj[sym] = symVal;\n\tfor (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop\n\tif (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }\n\n\tif (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }\n\n\tvar syms = Object.getOwnPropertySymbols(obj);\n\tif (syms.length !== 1 || syms[0] !== sym) { return false; }\n\n\tif (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }\n\n\tif (typeof Object.getOwnPropertyDescriptor === 'function') {\n\t\tvar descriptor = Object.getOwnPropertyDescriptor(obj, sym);\n\t\tif (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }\n\t}\n\n\treturn true;\n};\n","'use strict';\n\nvar origSymbol = typeof Symbol !== 'undefined' && Symbol;\nvar hasSymbolSham = require('./shams');\n\nmodule.exports = function hasNativeSymbols() {\n\tif (typeof origSymbol !== 'function') { return false; }\n\tif (typeof Symbol !== 'function') { return false; }\n\tif (typeof origSymbol('foo') !== 'symbol') { return false; }\n\tif (typeof Symbol('bar') !== 'symbol') { return false; }\n\n\treturn hasSymbolSham();\n};\n","'use strict';\n\n/* eslint no-invalid-this: 1 */\n\nvar ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';\nvar slice = Array.prototype.slice;\nvar toStr = Object.prototype.toString;\nvar funcType = '[object Function]';\n\nmodule.exports = function bind(that) {\n var target = this;\n if (typeof target !== 'function' || toStr.call(target) !== funcType) {\n throw new TypeError(ERROR_MESSAGE + target);\n }\n var args = slice.call(arguments, 1);\n\n var bound;\n var binder = function () {\n if (this instanceof bound) {\n var result = target.apply(\n this,\n args.concat(slice.call(arguments))\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n } else {\n return target.apply(\n that,\n args.concat(slice.call(arguments))\n );\n }\n };\n\n var boundLength = Math.max(0, target.length - args.length);\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs.push('$' + i);\n }\n\n bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);\n\n if (target.prototype) {\n var Empty = function Empty() {};\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n Empty.prototype = null;\n }\n\n return bound;\n};\n","'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = Function.prototype.bind || implementation;\n","'use strict';\n\nvar bind = require('function-bind');\n\nmodule.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);\n","'use strict';\n\nvar undefined;\n\nvar $SyntaxError = SyntaxError;\nvar $Function = Function;\nvar $TypeError = TypeError;\n\n// eslint-disable-next-line consistent-return\nvar getEvalledConstructor = function (expressionSyntax) {\n\ttry {\n\t\treturn $Function('\"use strict\"; return (' + expressionSyntax + ').constructor;')();\n\t} catch (e) {}\n};\n\nvar $gOPD = Object.getOwnPropertyDescriptor;\nif ($gOPD) {\n\ttry {\n\t\t$gOPD({}, '');\n\t} catch (e) {\n\t\t$gOPD = null; // this is IE 8, which has a broken gOPD\n\t}\n}\n\nvar throwTypeError = function () {\n\tthrow new $TypeError();\n};\nvar ThrowTypeError = $gOPD\n\t? (function () {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties\n\t\t\targuments.callee; // IE 8 does not throw here\n\t\t\treturn throwTypeError;\n\t\t} catch (calleeThrows) {\n\t\t\ttry {\n\t\t\t\t// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')\n\t\t\t\treturn $gOPD(arguments, 'callee').get;\n\t\t\t} catch (gOPDthrows) {\n\t\t\t\treturn throwTypeError;\n\t\t\t}\n\t\t}\n\t}())\n\t: throwTypeError;\n\nvar hasSymbols = require('has-symbols')();\n\nvar getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto\n\nvar needsEval = {};\n\nvar TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);\n\nvar INTRINSICS = {\n\t'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,\n\t'%Array%': Array,\n\t'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,\n\t'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,\n\t'%AsyncFromSyncIteratorPrototype%': undefined,\n\t'%AsyncFunction%': needsEval,\n\t'%AsyncGenerator%': needsEval,\n\t'%AsyncGeneratorFunction%': needsEval,\n\t'%AsyncIteratorPrototype%': needsEval,\n\t'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,\n\t'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,\n\t'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,\n\t'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,\n\t'%Boolean%': Boolean,\n\t'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,\n\t'%Date%': Date,\n\t'%decodeURI%': decodeURI,\n\t'%decodeURIComponent%': decodeURIComponent,\n\t'%encodeURI%': encodeURI,\n\t'%encodeURIComponent%': encodeURIComponent,\n\t'%Error%': Error,\n\t'%eval%': eval, // eslint-disable-line no-eval\n\t'%EvalError%': EvalError,\n\t'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,\n\t'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,\n\t'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,\n\t'%Function%': $Function,\n\t'%GeneratorFunction%': needsEval,\n\t'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,\n\t'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,\n\t'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,\n\t'%isFinite%': isFinite,\n\t'%isNaN%': isNaN,\n\t'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,\n\t'%JSON%': typeof JSON === 'object' ? JSON : undefined,\n\t'%Map%': typeof Map === 'undefined' ? undefined : Map,\n\t'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),\n\t'%Math%': Math,\n\t'%Number%': Number,\n\t'%Object%': Object,\n\t'%parseFloat%': parseFloat,\n\t'%parseInt%': parseInt,\n\t'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,\n\t'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,\n\t'%RangeError%': RangeError,\n\t'%ReferenceError%': ReferenceError,\n\t'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,\n\t'%RegExp%': RegExp,\n\t'%Set%': typeof Set === 'undefined' ? undefined : Set,\n\t'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),\n\t'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,\n\t'%String%': String,\n\t'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,\n\t'%Symbol%': hasSymbols ? Symbol : undefined,\n\t'%SyntaxError%': $SyntaxError,\n\t'%ThrowTypeError%': ThrowTypeError,\n\t'%TypedArray%': TypedArray,\n\t'%TypeError%': $TypeError,\n\t'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,\n\t'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,\n\t'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,\n\t'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,\n\t'%URIError%': URIError,\n\t'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,\n\t'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,\n\t'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet\n};\n\ntry {\n\tnull.error; // eslint-disable-line no-unused-expressions\n} catch (e) {\n\t// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229\n\tvar errorProto = getProto(getProto(e));\n\tINTRINSICS['%Error.prototype%'] = errorProto;\n}\n\nvar doEval = function doEval(name) {\n\tvar value;\n\tif (name === '%AsyncFunction%') {\n\t\tvalue = getEvalledConstructor('async function () {}');\n\t} else if (name === '%GeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('function* () {}');\n\t} else if (name === '%AsyncGeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('async function* () {}');\n\t} else if (name === '%AsyncGenerator%') {\n\t\tvar fn = doEval('%AsyncGeneratorFunction%');\n\t\tif (fn) {\n\t\t\tvalue = fn.prototype;\n\t\t}\n\t} else if (name === '%AsyncIteratorPrototype%') {\n\t\tvar gen = doEval('%AsyncGenerator%');\n\t\tif (gen) {\n\t\t\tvalue = getProto(gen.prototype);\n\t\t}\n\t}\n\n\tINTRINSICS[name] = value;\n\n\treturn value;\n};\n\nvar LEGACY_ALIASES = {\n\t'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],\n\t'%ArrayPrototype%': ['Array', 'prototype'],\n\t'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],\n\t'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],\n\t'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],\n\t'%ArrayProto_values%': ['Array', 'prototype', 'values'],\n\t'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],\n\t'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],\n\t'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],\n\t'%BooleanPrototype%': ['Boolean', 'prototype'],\n\t'%DataViewPrototype%': ['DataView', 'prototype'],\n\t'%DatePrototype%': ['Date', 'prototype'],\n\t'%ErrorPrototype%': ['Error', 'prototype'],\n\t'%EvalErrorPrototype%': ['EvalError', 'prototype'],\n\t'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],\n\t'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],\n\t'%FunctionPrototype%': ['Function', 'prototype'],\n\t'%Generator%': ['GeneratorFunction', 'prototype'],\n\t'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],\n\t'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],\n\t'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],\n\t'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],\n\t'%JSONParse%': ['JSON', 'parse'],\n\t'%JSONStringify%': ['JSON', 'stringify'],\n\t'%MapPrototype%': ['Map', 'prototype'],\n\t'%NumberPrototype%': ['Number', 'prototype'],\n\t'%ObjectPrototype%': ['Object', 'prototype'],\n\t'%ObjProto_toString%': ['Object', 'prototype', 'toString'],\n\t'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],\n\t'%PromisePrototype%': ['Promise', 'prototype'],\n\t'%PromiseProto_then%': ['Promise', 'prototype', 'then'],\n\t'%Promise_all%': ['Promise', 'all'],\n\t'%Promise_reject%': ['Promise', 'reject'],\n\t'%Promise_resolve%': ['Promise', 'resolve'],\n\t'%RangeErrorPrototype%': ['RangeError', 'prototype'],\n\t'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],\n\t'%RegExpPrototype%': ['RegExp', 'prototype'],\n\t'%SetPrototype%': ['Set', 'prototype'],\n\t'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],\n\t'%StringPrototype%': ['String', 'prototype'],\n\t'%SymbolPrototype%': ['Symbol', 'prototype'],\n\t'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],\n\t'%TypedArrayPrototype%': ['TypedArray', 'prototype'],\n\t'%TypeErrorPrototype%': ['TypeError', 'prototype'],\n\t'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],\n\t'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],\n\t'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],\n\t'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],\n\t'%URIErrorPrototype%': ['URIError', 'prototype'],\n\t'%WeakMapPrototype%': ['WeakMap', 'prototype'],\n\t'%WeakSetPrototype%': ['WeakSet', 'prototype']\n};\n\nvar bind = require('function-bind');\nvar hasOwn = require('has');\nvar $concat = bind.call(Function.call, Array.prototype.concat);\nvar $spliceApply = bind.call(Function.apply, Array.prototype.splice);\nvar $replace = bind.call(Function.call, String.prototype.replace);\nvar $strSlice = bind.call(Function.call, String.prototype.slice);\nvar $exec = bind.call(Function.call, RegExp.prototype.exec);\n\n/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */\nvar rePropName = /[^%.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|%$))/g;\nvar reEscapeChar = /\\\\(\\\\)?/g; /** Used to match backslashes in property paths. */\nvar stringToPath = function stringToPath(string) {\n\tvar first = $strSlice(string, 0, 1);\n\tvar last = $strSlice(string, -1);\n\tif (first === '%' && last !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected closing `%`');\n\t} else if (last === '%' && first !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected opening `%`');\n\t}\n\tvar result = [];\n\t$replace(string, rePropName, function (match, number, quote, subString) {\n\t\tresult[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;\n\t});\n\treturn result;\n};\n/* end adaptation */\n\nvar getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {\n\tvar intrinsicName = name;\n\tvar alias;\n\tif (hasOwn(LEGACY_ALIASES, intrinsicName)) {\n\t\talias = LEGACY_ALIASES[intrinsicName];\n\t\tintrinsicName = '%' + alias[0] + '%';\n\t}\n\n\tif (hasOwn(INTRINSICS, intrinsicName)) {\n\t\tvar value = INTRINSICS[intrinsicName];\n\t\tif (value === needsEval) {\n\t\t\tvalue = doEval(intrinsicName);\n\t\t}\n\t\tif (typeof value === 'undefined' && !allowMissing) {\n\t\t\tthrow new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');\n\t\t}\n\n\t\treturn {\n\t\t\talias: alias,\n\t\t\tname: intrinsicName,\n\t\t\tvalue: value\n\t\t};\n\t}\n\n\tthrow new $SyntaxError('intrinsic ' + name + ' does not exist!');\n};\n\nmodule.exports = function GetIntrinsic(name, allowMissing) {\n\tif (typeof name !== 'string' || name.length === 0) {\n\t\tthrow new $TypeError('intrinsic name must be a non-empty string');\n\t}\n\tif (arguments.length > 1 && typeof allowMissing !== 'boolean') {\n\t\tthrow new $TypeError('\"allowMissing\" argument must be a boolean');\n\t}\n\n\tif ($exec(/^%?[^%]*%?$/, name) === null) {\n\t\tthrow new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');\n\t}\n\tvar parts = stringToPath(name);\n\tvar intrinsicBaseName = parts.length > 0 ? parts[0] : '';\n\n\tvar intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);\n\tvar intrinsicRealName = intrinsic.name;\n\tvar value = intrinsic.value;\n\tvar skipFurtherCaching = false;\n\n\tvar alias = intrinsic.alias;\n\tif (alias) {\n\t\tintrinsicBaseName = alias[0];\n\t\t$spliceApply(parts, $concat([0, 1], alias));\n\t}\n\n\tfor (var i = 1, isOwn = true; i < parts.length; i += 1) {\n\t\tvar part = parts[i];\n\t\tvar first = $strSlice(part, 0, 1);\n\t\tvar last = $strSlice(part, -1);\n\t\tif (\n\t\t\t(\n\t\t\t\t(first === '\"' || first === \"'\" || first === '`')\n\t\t\t\t|| (last === '\"' || last === \"'\" || last === '`')\n\t\t\t)\n\t\t\t&& first !== last\n\t\t) {\n\t\t\tthrow new $SyntaxError('property names with quotes must have matching quotes');\n\t\t}\n\t\tif (part === 'constructor' || !isOwn) {\n\t\t\tskipFurtherCaching = true;\n\t\t}\n\n\t\tintrinsicBaseName += '.' + part;\n\t\tintrinsicRealName = '%' + intrinsicBaseName + '%';\n\n\t\tif (hasOwn(INTRINSICS, intrinsicRealName)) {\n\t\t\tvalue = INTRINSICS[intrinsicRealName];\n\t\t} else if (value != null) {\n\t\t\tif (!(part in value)) {\n\t\t\t\tif (!allowMissing) {\n\t\t\t\t\tthrow new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');\n\t\t\t\t}\n\t\t\t\treturn void undefined;\n\t\t\t}\n\t\t\tif ($gOPD && (i + 1) >= parts.length) {\n\t\t\t\tvar desc = $gOPD(value, part);\n\t\t\t\tisOwn = !!desc;\n\n\t\t\t\t// By convention, when a data property is converted to an accessor\n\t\t\t\t// property to emulate a data property that does not suffer from\n\t\t\t\t// the override mistake, that accessor's getter is marked with\n\t\t\t\t// an `originalValue` property. Here, when we detect this, we\n\t\t\t\t// uphold the illusion by pretending to see that original data\n\t\t\t\t// property, i.e., returning the value rather than the getter\n\t\t\t\t// itself.\n\t\t\t\tif (isOwn && 'get' in desc && !('originalValue' in desc.get)) {\n\t\t\t\t\tvalue = desc.get;\n\t\t\t\t} else {\n\t\t\t\t\tvalue = value[part];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tisOwn = hasOwn(value, part);\n\t\t\t\tvalue = value[part];\n\t\t\t}\n\n\t\t\tif (isOwn && !skipFurtherCaching) {\n\t\t\t\tINTRINSICS[intrinsicRealName] = value;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n};\n","'use strict';\n\nvar bind = require('function-bind');\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $apply = GetIntrinsic('%Function.prototype.apply%');\nvar $call = GetIntrinsic('%Function.prototype.call%');\nvar $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\nvar $defineProperty = GetIntrinsic('%Object.defineProperty%', true);\nvar $max = GetIntrinsic('%Math.max%');\n\nif ($defineProperty) {\n\ttry {\n\t\t$defineProperty({}, 'a', { value: 1 });\n\t} catch (e) {\n\t\t// IE 8 has a broken defineProperty\n\t\t$defineProperty = null;\n\t}\n}\n\nmodule.exports = function callBind(originalFunction) {\n\tvar func = $reflectApply(bind, $call, arguments);\n\tif ($gOPD && $defineProperty) {\n\t\tvar desc = $gOPD(func, 'length');\n\t\tif (desc.configurable) {\n\t\t\t// original length, plus the receiver, minus any additional arguments (after the receiver)\n\t\t\t$defineProperty(\n\t\t\t\tfunc,\n\t\t\t\t'length',\n\t\t\t\t{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }\n\t\t\t);\n\t\t}\n\t}\n\treturn func;\n};\n\nvar applyBind = function applyBind() {\n\treturn $reflectApply(bind, $apply, arguments);\n};\n\nif ($defineProperty) {\n\t$defineProperty(module.exports, 'apply', { value: applyBind });\n} else {\n\tmodule.exports.apply = applyBind;\n}\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar callBind = require('./');\n\nvar $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));\n\nmodule.exports = function callBoundIntrinsic(name, allowMissing) {\n\tvar intrinsic = GetIntrinsic(name, !!allowMissing);\n\tif (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {\n\t\treturn callBind(intrinsic);\n\t}\n\treturn intrinsic;\n};\n","export default {}","var hasMap = typeof Map === 'function' && Map.prototype;\nvar mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;\nvar mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;\nvar mapForEach = hasMap && Map.prototype.forEach;\nvar hasSet = typeof Set === 'function' && Set.prototype;\nvar setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;\nvar setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;\nvar setForEach = hasSet && Set.prototype.forEach;\nvar hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;\nvar weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;\nvar hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;\nvar weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;\nvar hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;\nvar weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;\nvar booleanValueOf = Boolean.prototype.valueOf;\nvar objectToString = Object.prototype.toString;\nvar functionToString = Function.prototype.toString;\nvar $match = String.prototype.match;\nvar $slice = String.prototype.slice;\nvar $replace = String.prototype.replace;\nvar $toUpperCase = String.prototype.toUpperCase;\nvar $toLowerCase = String.prototype.toLowerCase;\nvar $test = RegExp.prototype.test;\nvar $concat = Array.prototype.concat;\nvar $join = Array.prototype.join;\nvar $arrSlice = Array.prototype.slice;\nvar $floor = Math.floor;\nvar bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;\nvar gOPS = Object.getOwnPropertySymbols;\nvar symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;\nvar hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';\n// ie, `has-tostringtag/shams\nvar toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')\n ? Symbol.toStringTag\n : null;\nvar isEnumerable = Object.prototype.propertyIsEnumerable;\n\nvar gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (\n [].__proto__ === Array.prototype // eslint-disable-line no-proto\n ? function (O) {\n return O.__proto__; // eslint-disable-line no-proto\n }\n : null\n);\n\nfunction addNumericSeparator(num, str) {\n if (\n num === Infinity\n || num === -Infinity\n || num !== num\n || (num && num > -1000 && num < 1000)\n || $test.call(/e/, str)\n ) {\n return str;\n }\n var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;\n if (typeof num === 'number') {\n var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)\n if (int !== num) {\n var intStr = String(int);\n var dec = $slice.call(str, intStr.length + 1);\n return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');\n }\n }\n return $replace.call(str, sepRegex, '$&_');\n}\n\nvar utilInspect = require('./util.inspect');\nvar inspectCustom = utilInspect.custom;\nvar inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;\n\nmodule.exports = function inspect_(obj, options, depth, seen) {\n var opts = options || {};\n\n if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {\n throw new TypeError('option \"quoteStyle\" must be \"single\" or \"double\"');\n }\n if (\n has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'\n ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity\n : opts.maxStringLength !== null\n )\n ) {\n throw new TypeError('option \"maxStringLength\", if provided, must be a positive integer, Infinity, or `null`');\n }\n var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;\n if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {\n throw new TypeError('option \"customInspect\", if provided, must be `true`, `false`, or `\\'symbol\\'`');\n }\n\n if (\n has(opts, 'indent')\n && opts.indent !== null\n && opts.indent !== '\\t'\n && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)\n ) {\n throw new TypeError('option \"indent\" must be \"\\\\t\", an integer > 0, or `null`');\n }\n if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {\n throw new TypeError('option \"numericSeparator\", if provided, must be `true` or `false`');\n }\n var numericSeparator = opts.numericSeparator;\n\n if (typeof obj === 'undefined') {\n return 'undefined';\n }\n if (obj === null) {\n return 'null';\n }\n if (typeof obj === 'boolean') {\n return obj ? 'true' : 'false';\n }\n\n if (typeof obj === 'string') {\n return inspectString(obj, opts);\n }\n if (typeof obj === 'number') {\n if (obj === 0) {\n return Infinity / obj > 0 ? '0' : '-0';\n }\n var str = String(obj);\n return numericSeparator ? addNumericSeparator(obj, str) : str;\n }\n if (typeof obj === 'bigint') {\n var bigIntStr = String(obj) + 'n';\n return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;\n }\n\n var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;\n if (typeof depth === 'undefined') { depth = 0; }\n if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {\n return isArray(obj) ? '[Array]' : '[Object]';\n }\n\n var indent = getIndent(opts, depth);\n\n if (typeof seen === 'undefined') {\n seen = [];\n } else if (indexOf(seen, obj) >= 0) {\n return '[Circular]';\n }\n\n function inspect(value, from, noIndent) {\n if (from) {\n seen = $arrSlice.call(seen);\n seen.push(from);\n }\n if (noIndent) {\n var newOpts = {\n depth: opts.depth\n };\n if (has(opts, 'quoteStyle')) {\n newOpts.quoteStyle = opts.quoteStyle;\n }\n return inspect_(value, newOpts, depth + 1, seen);\n }\n return inspect_(value, opts, depth + 1, seen);\n }\n\n if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable\n var name = nameOf(obj);\n var keys = arrObjKeys(obj, inspect);\n return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');\n }\n if (isSymbol(obj)) {\n var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\\(.*\\))_[^)]*$/, '$1') : symToString.call(obj);\n return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;\n }\n if (isElement(obj)) {\n var s = '<' + $toLowerCase.call(String(obj.nodeName));\n var attrs = obj.attributes || [];\n for (var i = 0; i < attrs.length; i++) {\n s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);\n }\n s += '>';\n if (obj.childNodes && obj.childNodes.length) { s += '...'; }\n s += '';\n return s;\n }\n if (isArray(obj)) {\n if (obj.length === 0) { return '[]'; }\n var xs = arrObjKeys(obj, inspect);\n if (indent && !singleLineValues(xs)) {\n return '[' + indentedJoin(xs, indent) + ']';\n }\n return '[ ' + $join.call(xs, ', ') + ' ]';\n }\n if (isError(obj)) {\n var parts = arrObjKeys(obj, inspect);\n if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {\n return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';\n }\n if (parts.length === 0) { return '[' + String(obj) + ']'; }\n return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';\n }\n if (typeof obj === 'object' && customInspect) {\n if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {\n return utilInspect(obj, { depth: maxDepth - depth });\n } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {\n return obj.inspect();\n }\n }\n if (isMap(obj)) {\n var mapParts = [];\n if (mapForEach) {\n mapForEach.call(obj, function (value, key) {\n mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));\n });\n }\n return collectionOf('Map', mapSize.call(obj), mapParts, indent);\n }\n if (isSet(obj)) {\n var setParts = [];\n if (setForEach) {\n setForEach.call(obj, function (value) {\n setParts.push(inspect(value, obj));\n });\n }\n return collectionOf('Set', setSize.call(obj), setParts, indent);\n }\n if (isWeakMap(obj)) {\n return weakCollectionOf('WeakMap');\n }\n if (isWeakSet(obj)) {\n return weakCollectionOf('WeakSet');\n }\n if (isWeakRef(obj)) {\n return weakCollectionOf('WeakRef');\n }\n if (isNumber(obj)) {\n return markBoxed(inspect(Number(obj)));\n }\n if (isBigInt(obj)) {\n return markBoxed(inspect(bigIntValueOf.call(obj)));\n }\n if (isBoolean(obj)) {\n return markBoxed(booleanValueOf.call(obj));\n }\n if (isString(obj)) {\n return markBoxed(inspect(String(obj)));\n }\n if (!isDate(obj) && !isRegExp(obj)) {\n var ys = arrObjKeys(obj, inspect);\n var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;\n var protoTag = obj instanceof Object ? '' : 'null prototype';\n var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';\n var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';\n var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');\n if (ys.length === 0) { return tag + '{}'; }\n if (indent) {\n return tag + '{' + indentedJoin(ys, indent) + '}';\n }\n return tag + '{ ' + $join.call(ys, ', ') + ' }';\n }\n return String(obj);\n};\n\nfunction wrapQuotes(s, defaultStyle, opts) {\n var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '\"' : \"'\";\n return quoteChar + s + quoteChar;\n}\n\nfunction quote(s) {\n return $replace.call(String(s), /\"/g, '"');\n}\n\nfunction isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\n\n// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives\nfunction isSymbol(obj) {\n if (hasShammedSymbols) {\n return obj && typeof obj === 'object' && obj instanceof Symbol;\n }\n if (typeof obj === 'symbol') {\n return true;\n }\n if (!obj || typeof obj !== 'object' || !symToString) {\n return false;\n }\n try {\n symToString.call(obj);\n return true;\n } catch (e) {}\n return false;\n}\n\nfunction isBigInt(obj) {\n if (!obj || typeof obj !== 'object' || !bigIntValueOf) {\n return false;\n }\n try {\n bigIntValueOf.call(obj);\n return true;\n } catch (e) {}\n return false;\n}\n\nvar hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };\nfunction has(obj, key) {\n return hasOwn.call(obj, key);\n}\n\nfunction toStr(obj) {\n return objectToString.call(obj);\n}\n\nfunction nameOf(f) {\n if (f.name) { return f.name; }\n var m = $match.call(functionToString.call(f), /^function\\s*([\\w$]+)/);\n if (m) { return m[1]; }\n return null;\n}\n\nfunction indexOf(xs, x) {\n if (xs.indexOf) { return xs.indexOf(x); }\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) { return i; }\n }\n return -1;\n}\n\nfunction isMap(x) {\n if (!mapSize || !x || typeof x !== 'object') {\n return false;\n }\n try {\n mapSize.call(x);\n try {\n setSize.call(x);\n } catch (s) {\n return true;\n }\n return x instanceof Map; // core-js workaround, pre-v2.5.0\n } catch (e) {}\n return false;\n}\n\nfunction isWeakMap(x) {\n if (!weakMapHas || !x || typeof x !== 'object') {\n return false;\n }\n try {\n weakMapHas.call(x, weakMapHas);\n try {\n weakSetHas.call(x, weakSetHas);\n } catch (s) {\n return true;\n }\n return x instanceof WeakMap; // core-js workaround, pre-v2.5.0\n } catch (e) {}\n return false;\n}\n\nfunction isWeakRef(x) {\n if (!weakRefDeref || !x || typeof x !== 'object') {\n return false;\n }\n try {\n weakRefDeref.call(x);\n return true;\n } catch (e) {}\n return false;\n}\n\nfunction isSet(x) {\n if (!setSize || !x || typeof x !== 'object') {\n return false;\n }\n try {\n setSize.call(x);\n try {\n mapSize.call(x);\n } catch (m) {\n return true;\n }\n return x instanceof Set; // core-js workaround, pre-v2.5.0\n } catch (e) {}\n return false;\n}\n\nfunction isWeakSet(x) {\n if (!weakSetHas || !x || typeof x !== 'object') {\n return false;\n }\n try {\n weakSetHas.call(x, weakSetHas);\n try {\n weakMapHas.call(x, weakMapHas);\n } catch (s) {\n return true;\n }\n return x instanceof WeakSet; // core-js workaround, pre-v2.5.0\n } catch (e) {}\n return false;\n}\n\nfunction isElement(x) {\n if (!x || typeof x !== 'object') { return false; }\n if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {\n return true;\n }\n return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';\n}\n\nfunction inspectString(str, opts) {\n if (str.length > opts.maxStringLength) {\n var remaining = str.length - opts.maxStringLength;\n var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');\n return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;\n }\n // eslint-disable-next-line no-control-regex\n var s = $replace.call($replace.call(str, /(['\\\\])/g, '\\\\$1'), /[\\x00-\\x1f]/g, lowbyte);\n return wrapQuotes(s, 'single', opts);\n}\n\nfunction lowbyte(c) {\n var n = c.charCodeAt(0);\n var x = {\n 8: 'b',\n 9: 't',\n 10: 'n',\n 12: 'f',\n 13: 'r'\n }[n];\n if (x) { return '\\\\' + x; }\n return '\\\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));\n}\n\nfunction markBoxed(str) {\n return 'Object(' + str + ')';\n}\n\nfunction weakCollectionOf(type) {\n return type + ' { ? }';\n}\n\nfunction collectionOf(type, size, entries, indent) {\n var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');\n return type + ' (' + size + ') {' + joinedEntries + '}';\n}\n\nfunction singleLineValues(xs) {\n for (var i = 0; i < xs.length; i++) {\n if (indexOf(xs[i], '\\n') >= 0) {\n return false;\n }\n }\n return true;\n}\n\nfunction getIndent(opts, depth) {\n var baseIndent;\n if (opts.indent === '\\t') {\n baseIndent = '\\t';\n } else if (typeof opts.indent === 'number' && opts.indent > 0) {\n baseIndent = $join.call(Array(opts.indent + 1), ' ');\n } else {\n return null;\n }\n return {\n base: baseIndent,\n prev: $join.call(Array(depth + 1), baseIndent)\n };\n}\n\nfunction indentedJoin(xs, indent) {\n if (xs.length === 0) { return ''; }\n var lineJoiner = '\\n' + indent.prev + indent.base;\n return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\\n' + indent.prev;\n}\n\nfunction arrObjKeys(obj, inspect) {\n var isArr = isArray(obj);\n var xs = [];\n if (isArr) {\n xs.length = obj.length;\n for (var i = 0; i < obj.length; i++) {\n xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';\n }\n }\n var syms = typeof gOPS === 'function' ? gOPS(obj) : [];\n var symMap;\n if (hasShammedSymbols) {\n symMap = {};\n for (var k = 0; k < syms.length; k++) {\n symMap['$' + syms[k]] = syms[k];\n }\n }\n\n for (var key in obj) { // eslint-disable-line no-restricted-syntax\n if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue\n if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue\n if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {\n // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section\n continue; // eslint-disable-line no-restricted-syntax, no-continue\n } else if ($test.call(/[^\\w$]/, key)) {\n xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));\n } else {\n xs.push(key + ': ' + inspect(obj[key], obj));\n }\n }\n if (typeof gOPS === 'function') {\n for (var j = 0; j < syms.length; j++) {\n if (isEnumerable.call(obj, syms[j])) {\n xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));\n }\n }\n }\n return xs;\n}\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\nvar callBound = require('call-bind/callBound');\nvar inspect = require('object-inspect');\n\nvar $TypeError = GetIntrinsic('%TypeError%');\nvar $WeakMap = GetIntrinsic('%WeakMap%', true);\nvar $Map = GetIntrinsic('%Map%', true);\n\nvar $weakMapGet = callBound('WeakMap.prototype.get', true);\nvar $weakMapSet = callBound('WeakMap.prototype.set', true);\nvar $weakMapHas = callBound('WeakMap.prototype.has', true);\nvar $mapGet = callBound('Map.prototype.get', true);\nvar $mapSet = callBound('Map.prototype.set', true);\nvar $mapHas = callBound('Map.prototype.has', true);\n\n/*\n * This function traverses the list returning the node corresponding to the\n * given key.\n *\n * That node is also moved to the head of the list, so that if it's accessed\n * again we don't need to traverse the whole list. By doing so, all the recently\n * used nodes can be accessed relatively quickly.\n */\nvar listGetNode = function (list, key) { // eslint-disable-line consistent-return\n\tfor (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {\n\t\tif (curr.key === key) {\n\t\t\tprev.next = curr.next;\n\t\t\tcurr.next = list.next;\n\t\t\tlist.next = curr; // eslint-disable-line no-param-reassign\n\t\t\treturn curr;\n\t\t}\n\t}\n};\n\nvar listGet = function (objects, key) {\n\tvar node = listGetNode(objects, key);\n\treturn node && node.value;\n};\nvar listSet = function (objects, key, value) {\n\tvar node = listGetNode(objects, key);\n\tif (node) {\n\t\tnode.value = value;\n\t} else {\n\t\t// Prepend the new node to the beginning of the list\n\t\tobjects.next = { // eslint-disable-line no-param-reassign\n\t\t\tkey: key,\n\t\t\tnext: objects.next,\n\t\t\tvalue: value\n\t\t};\n\t}\n};\nvar listHas = function (objects, key) {\n\treturn !!listGetNode(objects, key);\n};\n\nmodule.exports = function getSideChannel() {\n\tvar $wm;\n\tvar $m;\n\tvar $o;\n\tvar channel = {\n\t\tassert: function (key) {\n\t\t\tif (!channel.has(key)) {\n\t\t\t\tthrow new $TypeError('Side channel does not contain ' + inspect(key));\n\t\t\t}\n\t\t},\n\t\tget: function (key) { // eslint-disable-line consistent-return\n\t\t\tif ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {\n\t\t\t\tif ($wm) {\n\t\t\t\t\treturn $weakMapGet($wm, key);\n\t\t\t\t}\n\t\t\t} else if ($Map) {\n\t\t\t\tif ($m) {\n\t\t\t\t\treturn $mapGet($m, key);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ($o) { // eslint-disable-line no-lonely-if\n\t\t\t\t\treturn listGet($o, key);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\thas: function (key) {\n\t\t\tif ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {\n\t\t\t\tif ($wm) {\n\t\t\t\t\treturn $weakMapHas($wm, key);\n\t\t\t\t}\n\t\t\t} else if ($Map) {\n\t\t\t\tif ($m) {\n\t\t\t\t\treturn $mapHas($m, key);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif ($o) { // eslint-disable-line no-lonely-if\n\t\t\t\t\treturn listHas($o, key);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t},\n\t\tset: function (key, value) {\n\t\t\tif ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {\n\t\t\t\tif (!$wm) {\n\t\t\t\t\t$wm = new $WeakMap();\n\t\t\t\t}\n\t\t\t\t$weakMapSet($wm, key, value);\n\t\t\t} else if ($Map) {\n\t\t\t\tif (!$m) {\n\t\t\t\t\t$m = new $Map();\n\t\t\t\t}\n\t\t\t\t$mapSet($m, key, value);\n\t\t\t} else {\n\t\t\t\tif (!$o) {\n\t\t\t\t\t/*\n\t\t\t\t\t * Initialize the linked list as an empty node, so that we don't have\n\t\t\t\t\t * to special-case handling of the first node: we can always refer to\n\t\t\t\t\t * it as (previous node).next, instead of something like (list).head\n\t\t\t\t\t */\n\t\t\t\t\t$o = { key: {}, next: null };\n\t\t\t\t}\n\t\t\t\tlistSet($o, key, value);\n\t\t\t}\n\t\t}\n\t};\n\treturn channel;\n};\n","'use strict';\n\nvar replace = String.prototype.replace;\nvar percentTwenties = /%20/g;\n\nvar Format = {\n RFC1738: 'RFC1738',\n RFC3986: 'RFC3986'\n};\n\nmodule.exports = {\n 'default': Format.RFC3986,\n formatters: {\n RFC1738: function (value) {\n return replace.call(value, percentTwenties, '+');\n },\n RFC3986: function (value) {\n return String(value);\n }\n },\n RFC1738: Format.RFC1738,\n RFC3986: Format.RFC3986\n};\n","'use strict';\n\nvar formats = require('./formats');\n\nvar has = Object.prototype.hasOwnProperty;\nvar isArray = Array.isArray;\n\nvar hexTable = (function () {\n var array = [];\n for (var i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n\n return array;\n}());\n\nvar compactQueue = function compactQueue(queue) {\n while (queue.length > 1) {\n var item = queue.pop();\n var obj = item.obj[item.prop];\n\n if (isArray(obj)) {\n var compacted = [];\n\n for (var j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n\n item.obj[item.prop] = compacted;\n }\n }\n};\n\nvar arrayToObject = function arrayToObject(source, options) {\n var obj = options && options.plainObjects ? Object.create(null) : {};\n for (var i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n\n return obj;\n};\n\nvar merge = function merge(target, source, options) {\n /* eslint no-param-reassign: 0 */\n if (!source) {\n return target;\n }\n\n if (typeof source !== 'object') {\n if (isArray(target)) {\n target.push(source);\n } else if (target && typeof target === 'object') {\n if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {\n target[source] = true;\n }\n } else {\n return [target, source];\n }\n\n return target;\n }\n\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n\n var mergeTarget = target;\n if (isArray(target) && !isArray(source)) {\n mergeTarget = arrayToObject(target, options);\n }\n\n if (isArray(target) && isArray(source)) {\n source.forEach(function (item, i) {\n if (has.call(target, i)) {\n var targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n } else {\n target.push(item);\n }\n } else {\n target[i] = item;\n }\n });\n return target;\n }\n\n return Object.keys(source).reduce(function (acc, key) {\n var value = source[key];\n\n if (has.call(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n } else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n};\n\nvar assign = function assignSingleSource(target, source) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n};\n\nvar decode = function (str, decoder, charset) {\n var strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n } catch (e) {\n return strWithoutPlus;\n }\n};\n\nvar encode = function encode(str, defaultEncoder, charset, kind, format) {\n // This code was originally written by Brian White (mscdex) for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n\n var string = str;\n if (typeof str === 'symbol') {\n string = Symbol.prototype.toString.call(str);\n } else if (typeof str !== 'string') {\n string = String(str);\n }\n\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n\n var out = '';\n for (var i = 0; i < string.length; ++i) {\n var c = string.charCodeAt(i);\n\n if (\n c === 0x2D // -\n || c === 0x2E // .\n || c === 0x5F // _\n || c === 0x7E // ~\n || (c >= 0x30 && c <= 0x39) // 0-9\n || (c >= 0x41 && c <= 0x5A) // a-z\n || (c >= 0x61 && c <= 0x7A) // A-Z\n || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )\n ) {\n out += string.charAt(i);\n continue;\n }\n\n if (c < 0x80) {\n out = out + hexTable[c];\n continue;\n }\n\n if (c < 0x800) {\n out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);\n continue;\n }\n\n if (c < 0xD800 || c >= 0xE000) {\n out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);\n continue;\n }\n\n i += 1;\n c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));\n /* eslint operator-linebreak: [2, \"before\"] */\n out += hexTable[0xF0 | (c >> 18)]\n + hexTable[0x80 | ((c >> 12) & 0x3F)]\n + hexTable[0x80 | ((c >> 6) & 0x3F)]\n + hexTable[0x80 | (c & 0x3F)];\n }\n\n return out;\n};\n\nvar compact = function compact(value) {\n var queue = [{ obj: { o: value }, prop: 'o' }];\n var refs = [];\n\n for (var i = 0; i < queue.length; ++i) {\n var item = queue[i];\n var obj = item.obj[item.prop];\n\n var keys = Object.keys(obj);\n for (var j = 0; j < keys.length; ++j) {\n var key = keys[j];\n var val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n\n compactQueue(queue);\n\n return value;\n};\n\nvar isRegExp = function isRegExp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n};\n\nvar isBuffer = function isBuffer(obj) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n};\n\nvar combine = function combine(a, b) {\n return [].concat(a, b);\n};\n\nvar maybeMap = function maybeMap(val, fn) {\n if (isArray(val)) {\n var mapped = [];\n for (var i = 0; i < val.length; i += 1) {\n mapped.push(fn(val[i]));\n }\n return mapped;\n }\n return fn(val);\n};\n\nmodule.exports = {\n arrayToObject: arrayToObject,\n assign: assign,\n combine: combine,\n compact: compact,\n decode: decode,\n encode: encode,\n isBuffer: isBuffer,\n isRegExp: isRegExp,\n maybeMap: maybeMap,\n merge: merge\n};\n","'use strict';\n\nvar getSideChannel = require('side-channel');\nvar utils = require('./utils');\nvar formats = require('./formats');\nvar has = Object.prototype.hasOwnProperty;\n\nvar arrayPrefixGenerators = {\n brackets: function brackets(prefix) {\n return prefix + '[]';\n },\n comma: 'comma',\n indices: function indices(prefix, key) {\n return prefix + '[' + key + ']';\n },\n repeat: function repeat(prefix) {\n return prefix;\n }\n};\n\nvar isArray = Array.isArray;\nvar push = Array.prototype.push;\nvar pushToArray = function (arr, valueOrArray) {\n push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);\n};\n\nvar toISO = Date.prototype.toISOString;\n\nvar defaultFormat = formats['default'];\nvar defaults = {\n addQueryPrefix: false,\n allowDots: false,\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encoder: utils.encode,\n encodeValuesOnly: false,\n format: defaultFormat,\n formatter: formats.formatters[defaultFormat],\n // deprecated\n indices: false,\n serializeDate: function serializeDate(date) {\n return toISO.call(date);\n },\n skipNulls: false,\n strictNullHandling: false\n};\n\nvar isNonNullishPrimitive = function isNonNullishPrimitive(v) {\n return typeof v === 'string'\n || typeof v === 'number'\n || typeof v === 'boolean'\n || typeof v === 'symbol'\n || typeof v === 'bigint';\n};\n\nvar sentinel = {};\n\nvar stringify = function stringify(\n object,\n prefix,\n generateArrayPrefix,\n commaRoundTrip,\n strictNullHandling,\n skipNulls,\n encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n format,\n formatter,\n encodeValuesOnly,\n charset,\n sideChannel\n) {\n var obj = object;\n\n var tmpSc = sideChannel;\n var step = 0;\n var findFlag = false;\n while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) {\n // Where object last appeared in the ref tree\n var pos = tmpSc.get(object);\n step += 1;\n if (typeof pos !== 'undefined') {\n if (pos === step) {\n throw new RangeError('Cyclic object value');\n } else {\n findFlag = true; // Break while\n }\n }\n if (typeof tmpSc.get(sentinel) === 'undefined') {\n step = 0;\n }\n }\n\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n } else if (obj instanceof Date) {\n obj = serializeDate(obj);\n } else if (generateArrayPrefix === 'comma' && isArray(obj)) {\n obj = utils.maybeMap(obj, function (value) {\n if (value instanceof Date) {\n return serializeDate(value);\n }\n return value;\n });\n }\n\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;\n }\n\n obj = '';\n }\n\n if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {\n if (encoder) {\n var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);\n return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];\n }\n return [formatter(prefix) + '=' + formatter(String(obj))];\n }\n\n var values = [];\n\n if (typeof obj === 'undefined') {\n return values;\n }\n\n var objKeys;\n if (generateArrayPrefix === 'comma' && isArray(obj)) {\n // we need to join elements in\n if (encodeValuesOnly && encoder) {\n obj = utils.maybeMap(obj, encoder);\n }\n objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];\n } else if (isArray(filter)) {\n objKeys = filter;\n } else {\n var keys = Object.keys(obj);\n objKeys = sort ? keys.sort(sort) : keys;\n }\n\n var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix;\n\n for (var j = 0; j < objKeys.length; ++j) {\n var key = objKeys[j];\n var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];\n\n if (skipNulls && value === null) {\n continue;\n }\n\n var keyPrefix = isArray(obj)\n ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix\n : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']');\n\n sideChannel.set(object, step);\n var valueSideChannel = getSideChannel();\n valueSideChannel.set(sentinel, sideChannel);\n pushToArray(values, stringify(\n value,\n keyPrefix,\n generateArrayPrefix,\n commaRoundTrip,\n strictNullHandling,\n skipNulls,\n generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n format,\n formatter,\n encodeValuesOnly,\n charset,\n valueSideChannel\n ));\n }\n\n return values;\n};\n\nvar normalizeStringifyOptions = function normalizeStringifyOptions(opts) {\n if (!opts) {\n return defaults;\n }\n\n if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n\n var charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n\n var format = formats['default'];\n if (typeof opts.format !== 'undefined') {\n if (!has.call(formats.formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n var formatter = formats.formatters[format];\n\n var filter = defaults.filter;\n if (typeof opts.filter === 'function' || isArray(opts.filter)) {\n filter = opts.filter;\n }\n\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n format: format,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling\n };\n};\n\nmodule.exports = function (object, opts) {\n var obj = object;\n var options = normalizeStringifyOptions(opts);\n\n var objKeys;\n var filter;\n\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n } else if (isArray(options.filter)) {\n filter = options.filter;\n objKeys = filter;\n }\n\n var keys = [];\n\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n\n var arrayFormat;\n if (opts && opts.arrayFormat in arrayPrefixGenerators) {\n arrayFormat = opts.arrayFormat;\n } else if (opts && 'indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n } else {\n arrayFormat = 'indices';\n }\n\n var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];\n if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {\n throw new TypeError('`commaRoundTrip` must be a boolean, or absent');\n }\n var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip;\n\n if (!objKeys) {\n objKeys = Object.keys(obj);\n }\n\n if (options.sort) {\n objKeys.sort(options.sort);\n }\n\n var sideChannel = getSideChannel();\n for (var i = 0; i < objKeys.length; ++i) {\n var key = objKeys[i];\n\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n pushToArray(keys, stringify(\n obj[key],\n key,\n generateArrayPrefix,\n commaRoundTrip,\n options.strictNullHandling,\n options.skipNulls,\n options.encode ? options.encoder : null,\n options.filter,\n options.sort,\n options.allowDots,\n options.serializeDate,\n options.format,\n options.formatter,\n options.encodeValuesOnly,\n options.charset,\n sideChannel\n ));\n }\n\n var joined = keys.join(options.delimiter);\n var prefix = options.addQueryPrefix === true ? '?' : '';\n\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('✓'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n } else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n\n return joined.length > 0 ? prefix + joined : '';\n};\n","'use strict';\n\nvar utils = require('./utils');\n\nvar has = Object.prototype.hasOwnProperty;\nvar isArray = Array.isArray;\n\nvar defaults = {\n allowDots: false,\n allowPrototypes: false,\n allowSparse: false,\n arrayLimit: 20,\n charset: 'utf-8',\n charsetSentinel: false,\n comma: false,\n decoder: utils.decode,\n delimiter: '&',\n depth: 5,\n ignoreQueryPrefix: false,\n interpretNumericEntities: false,\n parameterLimit: 1000,\n parseArrays: true,\n plainObjects: false,\n strictNullHandling: false\n};\n\nvar interpretNumericEntities = function (str) {\n return str.replace(/&#(\\d+);/g, function ($0, numberStr) {\n return String.fromCharCode(parseInt(numberStr, 10));\n });\n};\n\nvar parseArrayValue = function (val, options) {\n if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {\n return val.split(',');\n }\n\n return val;\n};\n\n// This is what browsers will submit when the ✓ character occurs in an\n// application/x-www-form-urlencoded body and the encoding of the page containing\n// the form is iso-8859-1, or when the submitted form has an accept-charset\n// attribute of iso-8859-1. Presumably also with other charsets that do not contain\n// the ✓ character, such as us-ascii.\nvar isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')\n\n// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.\nvar charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')\n\nvar parseValues = function parseQueryStringValues(str, options) {\n var obj = {};\n var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\\?/, '') : str;\n var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;\n var parts = cleanStr.split(options.delimiter, limit);\n var skipIndex = -1; // Keep track of where the utf8 sentinel was found\n var i;\n\n var charset = options.charset;\n if (options.charsetSentinel) {\n for (i = 0; i < parts.length; ++i) {\n if (parts[i].indexOf('utf8=') === 0) {\n if (parts[i] === charsetSentinel) {\n charset = 'utf-8';\n } else if (parts[i] === isoSentinel) {\n charset = 'iso-8859-1';\n }\n skipIndex = i;\n i = parts.length; // The eslint settings do not allow break;\n }\n }\n }\n\n for (i = 0; i < parts.length; ++i) {\n if (i === skipIndex) {\n continue;\n }\n var part = parts[i];\n\n var bracketEqualsPos = part.indexOf(']=');\n var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;\n\n var key, val;\n if (pos === -1) {\n key = options.decoder(part, defaults.decoder, charset, 'key');\n val = options.strictNullHandling ? null : '';\n } else {\n key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');\n val = utils.maybeMap(\n parseArrayValue(part.slice(pos + 1), options),\n function (encodedVal) {\n return options.decoder(encodedVal, defaults.decoder, charset, 'value');\n }\n );\n }\n\n if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {\n val = interpretNumericEntities(val);\n }\n\n if (part.indexOf('[]=') > -1) {\n val = isArray(val) ? [val] : val;\n }\n\n if (has.call(obj, key)) {\n obj[key] = utils.combine(obj[key], val);\n } else {\n obj[key] = val;\n }\n }\n\n return obj;\n};\n\nvar parseObject = function (chain, val, options, valuesParsed) {\n var leaf = valuesParsed ? val : parseArrayValue(val, options);\n\n for (var i = chain.length - 1; i >= 0; --i) {\n var obj;\n var root = chain[i];\n\n if (root === '[]' && options.parseArrays) {\n obj = [].concat(leaf);\n } else {\n obj = options.plainObjects ? Object.create(null) : {};\n var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;\n var index = parseInt(cleanRoot, 10);\n if (!options.parseArrays && cleanRoot === '') {\n obj = { 0: leaf };\n } else if (\n !isNaN(index)\n && root !== cleanRoot\n && String(index) === cleanRoot\n && index >= 0\n && (options.parseArrays && index <= options.arrayLimit)\n ) {\n obj = [];\n obj[index] = leaf;\n } else if (cleanRoot !== '__proto__') {\n obj[cleanRoot] = leaf;\n }\n }\n\n leaf = obj;\n }\n\n return leaf;\n};\n\nvar parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {\n if (!givenKey) {\n return;\n }\n\n // Transform dot notation to bracket notation\n var key = options.allowDots ? givenKey.replace(/\\.([^.[]+)/g, '[$1]') : givenKey;\n\n // The regex chunks\n\n var brackets = /(\\[[^[\\]]*])/;\n var child = /(\\[[^[\\]]*])/g;\n\n // Get the parent\n\n var segment = options.depth > 0 && brackets.exec(key);\n var parent = segment ? key.slice(0, segment.index) : key;\n\n // Stash the parent if it exists\n\n var keys = [];\n if (parent) {\n // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties\n if (!options.plainObjects && has.call(Object.prototype, parent)) {\n if (!options.allowPrototypes) {\n return;\n }\n }\n\n keys.push(parent);\n }\n\n // Loop through children appending to the array until we hit depth\n\n var i = 0;\n while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {\n i += 1;\n if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {\n if (!options.allowPrototypes) {\n return;\n }\n }\n keys.push(segment[1]);\n }\n\n // If there's a remainder, just add whatever is left\n\n if (segment) {\n keys.push('[' + key.slice(segment.index) + ']');\n }\n\n return parseObject(keys, val, options, valuesParsed);\n};\n\nvar normalizeParseOptions = function normalizeParseOptions(opts) {\n if (!opts) {\n return defaults;\n }\n\n if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {\n throw new TypeError('Decoder has to be a function.');\n }\n\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;\n\n return {\n allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,\n allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,\n allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,\n arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,\n decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,\n delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,\n // eslint-disable-next-line no-implicit-coercion, no-extra-parens\n depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,\n ignoreQueryPrefix: opts.ignoreQueryPrefix === true,\n interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,\n parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,\n parseArrays: opts.parseArrays !== false,\n plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling\n };\n};\n\nmodule.exports = function (str, opts) {\n var options = normalizeParseOptions(opts);\n\n if (str === '' || str === null || typeof str === 'undefined') {\n return options.plainObjects ? Object.create(null) : {};\n }\n\n var tempObj = typeof str === 'string' ? parseValues(str, options) : str;\n var obj = options.plainObjects ? Object.create(null) : {};\n\n // Iterate over the keys and setup the new object\n\n var keys = Object.keys(tempObj);\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');\n obj = utils.merge(obj, newObj, options);\n }\n\n if (options.allowSparse === true) {\n return obj;\n }\n\n return utils.compact(obj);\n};\n","'use strict';\n\nvar stringify = require('./stringify');\nvar parse = require('./parse');\nvar formats = require('./formats');\n\nmodule.exports = {\n formats: formats,\n parse: parse,\n stringify: stringify\n};\n","\n// import { useAuthStore } from '../store';\nimport axios from 'axios';\nimport qs from 'qs';\n\nexport default function configureAxios () {\n // const authStore = useAuthStore();\n\n axios.interceptors.request.use(\n function (config) {\n\t\t\tlet headers: Record = {};\n\n\t\t\tconfig.paramsSerializer = function (params) {\n\t\t\t\treturn qs.stringify(params, { arrayFormat: 'comma' })\n\t\t\t}\n\n // if (authStore.token) {\n\t\t\t// \theaders[appConstants.AUTH_TOKEN_HTTP_HEADER_NAME] = `Bearer ${authStore.token}`;\n // }\n\n\t\t\tif (document.documentElement.lang) {\n\t\t\t\theaders['culture'] = document.documentElement.lang;\n\t\t\t}\n\n\t\t\tconfig.headers = {\n\t\t\t\t...config.headers,\n\t\t\t\t...headers\n\t\t\t}\n \n return config;\n }\n )\n\n // only when logout refresh and remove auth\n\t// when api return 401, remove auth\n\taxios.interceptors.response.use(\n\t\tresponse => response,\n\t\terror => {\n\t\t\tif (!error.response) return Promise.reject(error);\n\t\t\t\n\t\t\tif (axios.isAxiosError(error)) {\n\t\t\t\t// const whitelist = constants.AUTH_INTERCEPTOR_WHITELIST;\n\t\t\t\t// const requestUrl = error.request.responseURL;\n\t\t\t\t// if (whitelist.some(x => requestUrl.includes(x))) {\n\t\t\t\t// \treturn Promise.reject(error);\n\t\t\t\t// }\n\t\t\t}\n\t\t\t\n\t\t\t// const { status } = error.response;\n\t\t\t// if (status === 401) {\n\t\t\t// \tconst memberType = authStore.accountType;\n\t\t\t// \tauthStore.logout()\n \n\t\t\t// \tif (!error.config.suppressAuthCheckReload) {\n\t\t\t// \t\twindow.location.reload()\n\t\t\t// \t}\n\t\t\t// }\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t)\n}","/* build: `node build.js modules=ALL exclude=gestures,accessors,erasing requirejs minifier=uglifyjs` */\n/*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */\n\nvar fabric = fabric || { version: '5.3.0' };\nif (typeof exports !== 'undefined') {\n exports.fabric = fabric;\n}\n/* _AMD_START_ */\nelse if (typeof define === 'function' && define.amd) {\n define([], function() { return fabric; });\n}\n/* _AMD_END_ */\nif (typeof document !== 'undefined' && typeof window !== 'undefined') {\n if (document instanceof (typeof HTMLDocument !== 'undefined' ? HTMLDocument : Document)) {\n fabric.document = document;\n }\n else {\n fabric.document = document.implementation.createHTMLDocument('');\n }\n fabric.window = window;\n}\nelse {\n // assume we're running under node.js when document/window are not present\n var jsdom = require('jsdom');\n var virtualWindow = new jsdom.JSDOM(\n decodeURIComponent('%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E'),\n {\n features: {\n FetchExternalResources: ['img']\n },\n resources: 'usable'\n }).window;\n fabric.document = virtualWindow.document;\n fabric.jsdomImplForWrapper = require('jsdom/lib/jsdom/living/generated/utils').implForWrapper;\n fabric.nodeCanvas = require('jsdom/lib/jsdom/utils').Canvas;\n fabric.window = virtualWindow;\n DOMParser = fabric.window.DOMParser;\n}\n\n/**\n * True when in environment that supports touch events\n * @type boolean\n */\nfabric.isTouchSupported = 'ontouchstart' in fabric.window || 'ontouchstart' in fabric.document ||\n (fabric.window && fabric.window.navigator && fabric.window.navigator.maxTouchPoints > 0);\n\n/**\n * True when in environment that's probably Node.js\n * @type boolean\n */\nfabric.isLikelyNode = typeof Buffer !== 'undefined' &&\n typeof window === 'undefined';\n\n/* _FROM_SVG_START_ */\n/**\n * Attributes parsed from all SVG elements\n * @type array\n */\nfabric.SHARED_ATTRIBUTES = [\n 'display',\n 'transform',\n 'fill', 'fill-opacity', 'fill-rule',\n 'opacity',\n 'stroke', 'stroke-dasharray', 'stroke-linecap', 'stroke-dashoffset',\n 'stroke-linejoin', 'stroke-miterlimit',\n 'stroke-opacity', 'stroke-width',\n 'id', 'paint-order', 'vector-effect',\n 'instantiated_by_use', 'clip-path',\n];\n/* _FROM_SVG_END_ */\n\n/**\n * Pixel per Inch as a default value set to 96. Can be changed for more realistic conversion.\n */\nfabric.DPI = 96;\nfabric.reNum = '(?:[-+]?(?:\\\\d+|\\\\d*\\\\.\\\\d+)(?:[eE][-+]?\\\\d+)?)';\nfabric.commaWsp = '(?:\\\\s+,?\\\\s*|,\\\\s*)';\nfabric.rePathCommand = /([-+]?((\\d+\\.\\d+)|((\\d+)|(\\.\\d+)))(?:[eE][-+]?\\d+)?)/ig;\nfabric.reNonWord = /[ \\n\\.,;!\\?\\-]/;\nfabric.fontPaths = { };\nfabric.iMatrix = [1, 0, 0, 1, 0, 0];\nfabric.svgNS = 'http://www.w3.org/2000/svg';\n\n/**\n * Pixel limit for cache canvases. 1Mpx , 4Mpx should be fine.\n * @since 1.7.14\n * @type Number\n * @default\n */\nfabric.perfLimitSizeTotal = 2097152;\n\n/**\n * Pixel limit for cache canvases width or height. IE fixes the maximum at 5000\n * @since 1.7.14\n * @type Number\n * @default\n */\nfabric.maxCacheSideLimit = 4096;\n\n/**\n * Lowest pixel limit for cache canvases, set at 256PX\n * @since 1.7.14\n * @type Number\n * @default\n */\nfabric.minCacheSideLimit = 256;\n\n/**\n * Cache Object for widths of chars in text rendering.\n */\nfabric.charWidthsCache = { };\n\n/**\n * if webgl is enabled and available, textureSize will determine the size\n * of the canvas backend\n * @since 2.0.0\n * @type Number\n * @default\n */\nfabric.textureSize = 2048;\n\n/**\n * When 'true', style information is not retained when copy/pasting text, making\n * pasted text use destination style.\n * Defaults to 'false'.\n * @type Boolean\n * @default\n */\nfabric.disableStyleCopyPaste = false;\n\n/**\n * Enable webgl for filtering picture is available\n * A filtering backend will be initialized, this will both take memory and\n * time since a default 2048x2048 canvas will be created for the gl context\n * @since 2.0.0\n * @type Boolean\n * @default\n */\nfabric.enableGLFiltering = true;\n\n/**\n * Device Pixel Ratio\n * @see https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/SettingUptheCanvas/SettingUptheCanvas.html\n */\nfabric.devicePixelRatio = fabric.window.devicePixelRatio ||\n fabric.window.webkitDevicePixelRatio ||\n fabric.window.mozDevicePixelRatio ||\n 1;\n/**\n * Browser-specific constant to adjust CanvasRenderingContext2D.shadowBlur value,\n * which is unitless and not rendered equally across browsers.\n *\n * Values that work quite well (as of October 2017) are:\n * - Chrome: 1.5\n * - Edge: 1.75\n * - Firefox: 0.9\n * - Safari: 0.95\n *\n * @since 2.0.0\n * @type Number\n * @default 1\n */\nfabric.browserShadowBlurConstant = 1;\n\n/**\n * This object contains the result of arc to bezier conversion for faster retrieving if the same arc needs to be converted again.\n * It was an internal variable, is accessible since version 2.3.4\n */\nfabric.arcToSegmentsCache = { };\n\n/**\n * This object keeps the results of the boundsOfCurve calculation mapped by the joined arguments necessary to calculate it.\n * It does speed up calculation, if you parse and add always the same paths, but in case of heavy usage of freedrawing\n * you do not get any speed benefit and you get a big object in memory.\n * The object was a private variable before, while now is appended to the lib so that you have access to it and you\n * can eventually clear it.\n * It was an internal variable, is accessible since version 2.3.4\n */\nfabric.boundsOfCurveCache = { };\n\n/**\n * If disabled boundsOfCurveCache is not used. For apps that make heavy usage of pencil drawing probably disabling it is better\n * @default true\n */\nfabric.cachesBoundsOfCurve = true;\n\n/**\n * Skip performance testing of setupGLContext and force the use of putImageData that seems to be the one that works best on\n * Chrome + old hardware. if your users are experiencing empty images after filtering you may try to force this to true\n * this has to be set before instantiating the filtering backend ( before filtering the first image )\n * @type Boolean\n * @default false\n */\nfabric.forceGLPutImageData = false;\n\nfabric.initFilterBackend = function() {\n if (fabric.enableGLFiltering && fabric.isWebglSupported && fabric.isWebglSupported(fabric.textureSize)) {\n console.log('max texture size: ' + fabric.maxTextureSize);\n return (new fabric.WebglFilterBackend({ tileSize: fabric.textureSize }));\n }\n else if (fabric.Canvas2dFilterBackend) {\n return (new fabric.Canvas2dFilterBackend());\n }\n};\n\n\nif (typeof document !== 'undefined' && typeof window !== 'undefined') {\n // ensure globality even if entire library were function wrapped (as in Meteor.js packaging system)\n window.fabric = fabric;\n}\n\n\n(function() {\n\n /**\n * @private\n * @param {String} eventName\n * @param {Function} handler\n */\n function _removeEventListener(eventName, handler) {\n if (!this.__eventListeners[eventName]) {\n return;\n }\n var eventListener = this.__eventListeners[eventName];\n if (handler) {\n eventListener[eventListener.indexOf(handler)] = false;\n }\n else {\n fabric.util.array.fill(eventListener, false);\n }\n }\n\n /**\n * Observes specified event\n * @memberOf fabric.Observable\n * @alias on\n * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})\n * @param {Function} handler Function that receives a notification when an event of the specified type occurs\n * @return {Self} thisArg\n * @chainable\n */\n function on(eventName, handler) {\n if (!this.__eventListeners) {\n this.__eventListeners = { };\n }\n // one object with key/value pairs was passed\n if (arguments.length === 1) {\n for (var prop in eventName) {\n this.on(prop, eventName[prop]);\n }\n }\n else {\n if (!this.__eventListeners[eventName]) {\n this.__eventListeners[eventName] = [];\n }\n this.__eventListeners[eventName].push(handler);\n }\n return this;\n }\n\n function _once(eventName, handler) {\n var _handler = function () {\n handler.apply(this, arguments);\n this.off(eventName, _handler);\n }.bind(this);\n this.on(eventName, _handler);\n }\n\n function once(eventName, handler) {\n // one object with key/value pairs was passed\n if (arguments.length === 1) {\n for (var prop in eventName) {\n _once.call(this, prop, eventName[prop]);\n }\n }\n else {\n _once.call(this, eventName, handler);\n }\n return this;\n }\n\n /**\n * Stops event observing for a particular event handler. Calling this method\n * without arguments removes all handlers for all events\n * @memberOf fabric.Observable\n * @alias off\n * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})\n * @param {Function} handler Function to be deleted from EventListeners\n * @return {Self} thisArg\n * @chainable\n */\n function off(eventName, handler) {\n if (!this.__eventListeners) {\n return this;\n }\n\n // remove all key/value pairs (event name -> event handler)\n if (arguments.length === 0) {\n for (eventName in this.__eventListeners) {\n _removeEventListener.call(this, eventName);\n }\n }\n // one object with key/value pairs was passed\n else if (arguments.length === 1 && typeof arguments[0] === 'object') {\n for (var prop in eventName) {\n _removeEventListener.call(this, prop, eventName[prop]);\n }\n }\n else {\n _removeEventListener.call(this, eventName, handler);\n }\n return this;\n }\n\n /**\n * Fires event with an optional options object\n * @memberOf fabric.Observable\n * @param {String} eventName Event name to fire\n * @param {Object} [options] Options object\n * @return {Self} thisArg\n * @chainable\n */\n function fire(eventName, options) {\n if (!this.__eventListeners) {\n return this;\n }\n\n var listenersForEvent = this.__eventListeners[eventName];\n if (!listenersForEvent) {\n return this;\n }\n\n for (var i = 0, len = listenersForEvent.length; i < len; i++) {\n listenersForEvent[i] && listenersForEvent[i].call(this, options || { });\n }\n this.__eventListeners[eventName] = listenersForEvent.filter(function(value) {\n return value !== false;\n });\n return this;\n }\n\n /**\n * @namespace fabric.Observable\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#events}\n * @see {@link http://fabricjs.com/events|Events demo}\n */\n fabric.Observable = {\n fire: fire,\n on: on,\n once: once,\n off: off,\n };\n})();\n\n\n/**\n * @namespace fabric.Collection\n */\nfabric.Collection = {\n\n _objects: [],\n\n /**\n * Adds objects to collection, Canvas or Group, then renders canvas\n * (if `renderOnAddRemove` is not `false`).\n * in case of Group no changes to bounding box are made.\n * Objects should be instances of (or inherit from) fabric.Object\n * Use of this function is highly discouraged for groups.\n * you can add a bunch of objects with the add method but then you NEED\n * to run a addWithUpdate call for the Group class or position/bbox will be wrong.\n * @param {...fabric.Object} object Zero or more fabric instances\n * @return {Self} thisArg\n * @chainable\n */\n add: function () {\n this._objects.push.apply(this._objects, arguments);\n if (this._onObjectAdded) {\n for (var i = 0, length = arguments.length; i < length; i++) {\n this._onObjectAdded(arguments[i]);\n }\n }\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)\n * An object should be an instance of (or inherit from) fabric.Object\n * Use of this function is highly discouraged for groups.\n * you can add a bunch of objects with the insertAt method but then you NEED\n * to run a addWithUpdate call for the Group class or position/bbox will be wrong.\n * @param {Object} object Object to insert\n * @param {Number} index Index to insert object at\n * @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs\n * @return {Self} thisArg\n * @chainable\n */\n insertAt: function (object, index, nonSplicing) {\n var objects = this._objects;\n if (nonSplicing) {\n objects[index] = object;\n }\n else {\n objects.splice(index, 0, object);\n }\n this._onObjectAdded && this._onObjectAdded(object);\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)\n * @param {...fabric.Object} object Zero or more fabric instances\n * @return {Self} thisArg\n * @chainable\n */\n remove: function() {\n var objects = this._objects,\n index, somethingRemoved = false;\n\n for (var i = 0, length = arguments.length; i < length; i++) {\n index = objects.indexOf(arguments[i]);\n\n // only call onObjectRemoved if an object was actually removed\n if (index !== -1) {\n somethingRemoved = true;\n objects.splice(index, 1);\n this._onObjectRemoved && this._onObjectRemoved(arguments[i]);\n }\n }\n\n this.renderOnAddRemove && somethingRemoved && this.requestRenderAll();\n return this;\n },\n\n /**\n * Executes given function for each object in this group\n * @param {Function} callback\n * Callback invoked with current object as first argument,\n * index - as second and an array of all objects - as third.\n * Callback is invoked in a context of Global Object (e.g. `window`)\n * when no `context` argument is given\n *\n * @param {Object} context Context (aka thisObject)\n * @return {Self} thisArg\n * @chainable\n */\n forEachObject: function(callback, context) {\n var objects = this.getObjects();\n for (var i = 0, len = objects.length; i < len; i++) {\n callback.call(context, objects[i], i, objects);\n }\n return this;\n },\n\n /**\n * Returns an array of children objects of this instance\n * Type parameter introduced in 1.3.10\n * since 2.3.5 this method return always a COPY of the array;\n * @param {String} [type] When specified, only objects of this type are returned\n * @return {Array}\n */\n getObjects: function(type) {\n if (typeof type === 'undefined') {\n return this._objects.concat();\n }\n return this._objects.filter(function(o) {\n return o.type === type;\n });\n },\n\n /**\n * Returns object at specified index\n * @param {Number} index\n * @return {Self} thisArg\n */\n item: function (index) {\n return this._objects[index];\n },\n\n /**\n * Returns true if collection contains no objects\n * @return {Boolean} true if collection is empty\n */\n isEmpty: function () {\n return this._objects.length === 0;\n },\n\n /**\n * Returns a size of a collection (i.e: length of an array containing its objects)\n * @return {Number} Collection size\n */\n size: function() {\n return this._objects.length;\n },\n\n /**\n * Returns true if collection contains an object\n * @param {Object} object Object to check against\n * @param {Boolean} [deep=false] `true` to check all descendants, `false` to check only `_objects`\n * @return {Boolean} `true` if collection contains an object\n */\n contains: function (object, deep) {\n if (this._objects.indexOf(object) > -1) {\n return true;\n }\n else if (deep) {\n return this._objects.some(function (obj) {\n return typeof obj.contains === 'function' && obj.contains(object, true);\n });\n }\n return false;\n },\n\n /**\n * Returns number representation of a collection complexity\n * @return {Number} complexity\n */\n complexity: function () {\n return this._objects.reduce(function (memo, current) {\n memo += current.complexity ? current.complexity() : 0;\n return memo;\n }, 0);\n }\n};\n\n\n/**\n * @namespace fabric.CommonMethods\n */\nfabric.CommonMethods = {\n\n /**\n * Sets object's properties from options\n * @param {Object} [options] Options object\n */\n _setOptions: function(options) {\n for (var prop in options) {\n this.set(prop, options[prop]);\n }\n },\n\n /**\n * @private\n * @param {Object} [filler] Options object\n * @param {String} [property] property to set the Gradient to\n */\n _initGradient: function(filler, property) {\n if (filler && filler.colorStops && !(filler instanceof fabric.Gradient)) {\n this.set(property, new fabric.Gradient(filler));\n }\n },\n\n /**\n * @private\n * @param {Object} [filler] Options object\n * @param {String} [property] property to set the Pattern to\n * @param {Function} [callback] callback to invoke after pattern load\n */\n _initPattern: function(filler, property, callback) {\n if (filler && filler.source && !(filler instanceof fabric.Pattern)) {\n this.set(property, new fabric.Pattern(filler, callback));\n }\n else {\n callback && callback();\n }\n },\n\n /**\n * @private\n */\n _setObject: function(obj) {\n for (var prop in obj) {\n this._set(prop, obj[prop]);\n }\n },\n\n /**\n * Sets property to a given value. When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. If you need to update those, call `setCoords()`.\n * @param {String|Object} key Property name or object (if object, iterate over the object properties)\n * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)\n * @return {fabric.Object} thisArg\n * @chainable\n */\n set: function(key, value) {\n if (typeof key === 'object') {\n this._setObject(key);\n }\n else {\n this._set(key, value);\n }\n return this;\n },\n\n _set: function(key, value) {\n this[key] = value;\n },\n\n /**\n * Toggles specified property from `true` to `false` or from `false` to `true`\n * @param {String} property Property to toggle\n * @return {fabric.Object} thisArg\n * @chainable\n */\n toggle: function(property) {\n var value = this.get(property);\n if (typeof value === 'boolean') {\n this.set(property, !value);\n }\n return this;\n },\n\n /**\n * Basic getter\n * @param {String} property Property name\n * @return {*} value of a property\n */\n get: function(property) {\n return this[property];\n }\n};\n\n\n(function(global) {\n\n var sqrt = Math.sqrt,\n atan2 = Math.atan2,\n pow = Math.pow,\n PiBy180 = Math.PI / 180,\n PiBy2 = Math.PI / 2;\n\n /**\n * @namespace fabric.util\n */\n fabric.util = {\n\n /**\n * Calculate the cos of an angle, avoiding returning floats for known results\n * @static\n * @memberOf fabric.util\n * @param {Number} angle the angle in radians or in degree\n * @return {Number}\n */\n cos: function(angle) {\n if (angle === 0) { return 1; }\n if (angle < 0) {\n // cos(a) = cos(-a)\n angle = -angle;\n }\n var angleSlice = angle / PiBy2;\n switch (angleSlice) {\n case 1: case 3: return 0;\n case 2: return -1;\n }\n return Math.cos(angle);\n },\n\n /**\n * Calculate the sin of an angle, avoiding returning floats for known results\n * @static\n * @memberOf fabric.util\n * @param {Number} angle the angle in radians or in degree\n * @return {Number}\n */\n sin: function(angle) {\n if (angle === 0) { return 0; }\n var angleSlice = angle / PiBy2, sign = 1;\n if (angle < 0) {\n // sin(-a) = -sin(a)\n sign = -1;\n }\n switch (angleSlice) {\n case 1: return sign;\n case 2: return 0;\n case 3: return -sign;\n }\n return Math.sin(angle);\n },\n\n /**\n * Removes value from an array.\n * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf`\n * @static\n * @memberOf fabric.util\n * @param {Array} array\n * @param {*} value\n * @return {Array} original array\n */\n removeFromArray: function(array, value) {\n var idx = array.indexOf(value);\n if (idx !== -1) {\n array.splice(idx, 1);\n }\n return array;\n },\n\n /**\n * Returns random number between 2 specified ones.\n * @static\n * @memberOf fabric.util\n * @param {Number} min lower limit\n * @param {Number} max upper limit\n * @return {Number} random value (between min and max)\n */\n getRandomInt: function(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n },\n\n /**\n * Transforms degrees to radians.\n * @static\n * @memberOf fabric.util\n * @param {Number} degrees value in degrees\n * @return {Number} value in radians\n */\n degreesToRadians: function(degrees) {\n return degrees * PiBy180;\n },\n\n /**\n * Transforms radians to degrees.\n * @static\n * @memberOf fabric.util\n * @param {Number} radians value in radians\n * @return {Number} value in degrees\n */\n radiansToDegrees: function(radians) {\n return radians / PiBy180;\n },\n\n /**\n * Rotates `point` around `origin` with `radians`\n * @static\n * @memberOf fabric.util\n * @param {fabric.Point} point The point to rotate\n * @param {fabric.Point} origin The origin of the rotation\n * @param {Number} radians The radians of the angle for the rotation\n * @return {fabric.Point} The new rotated point\n */\n rotatePoint: function(point, origin, radians) {\n var newPoint = new fabric.Point(point.x - origin.x, point.y - origin.y),\n v = fabric.util.rotateVector(newPoint, radians);\n return new fabric.Point(v.x, v.y).addEquals(origin);\n },\n\n /**\n * Rotates `vector` with `radians`\n * @static\n * @memberOf fabric.util\n * @param {Object} vector The vector to rotate (x and y)\n * @param {Number} radians The radians of the angle for the rotation\n * @return {Object} The new rotated point\n */\n rotateVector: function(vector, radians) {\n var sin = fabric.util.sin(radians),\n cos = fabric.util.cos(radians),\n rx = vector.x * cos - vector.y * sin,\n ry = vector.x * sin + vector.y * cos;\n return {\n x: rx,\n y: ry\n };\n },\n\n /**\n * Creates a vetor from points represented as a point\n * @static\n * @memberOf fabric.util\n *\n * @typedef {Object} Point\n * @property {number} x\n * @property {number} y\n *\n * @param {Point} from\n * @param {Point} to\n * @returns {Point} vector\n */\n createVector: function (from, to) {\n return new fabric.Point(to.x - from.x, to.y - from.y);\n },\n\n /**\n * Calculates angle between 2 vectors using dot product\n * @static\n * @memberOf fabric.util\n * @param {Point} a\n * @param {Point} b\n * @returns the angle in radian between the vectors\n */\n calcAngleBetweenVectors: function (a, b) {\n return Math.acos((a.x * b.x + a.y * b.y) / (Math.hypot(a.x, a.y) * Math.hypot(b.x, b.y)));\n },\n\n /**\n * @static\n * @memberOf fabric.util\n * @param {Point} v\n * @returns {Point} vector representing the unit vector of pointing to the direction of `v`\n */\n getHatVector: function (v) {\n return new fabric.Point(v.x, v.y).multiply(1 / Math.hypot(v.x, v.y));\n },\n\n /**\n * @static\n * @memberOf fabric.util\n * @param {Point} A\n * @param {Point} B\n * @param {Point} C\n * @returns {{ vector: Point, angle: number }} vector representing the bisector of A and A's angle\n */\n getBisector: function (A, B, C) {\n var AB = fabric.util.createVector(A, B), AC = fabric.util.createVector(A, C);\n var alpha = fabric.util.calcAngleBetweenVectors(AB, AC);\n // check if alpha is relative to AB->BC\n var ro = fabric.util.calcAngleBetweenVectors(fabric.util.rotateVector(AB, alpha), AC);\n var phi = alpha * (ro === 0 ? 1 : -1) / 2;\n return {\n vector: fabric.util.getHatVector(fabric.util.rotateVector(AB, phi)),\n angle: alpha\n };\n },\n\n /**\n * Project stroke width on points returning 2 projections for each point as follows:\n * - `miter`: 2 points corresponding to the outer boundary and the inner boundary of stroke.\n * - `bevel`: 2 points corresponding to the bevel boundaries, tangent to the bisector.\n * - `round`: same as `bevel`\n * Used to calculate object's bounding box\n * @static\n * @memberOf fabric.util\n * @param {Point[]} points\n * @param {Object} options\n * @param {number} options.strokeWidth\n * @param {'miter'|'bevel'|'round'} options.strokeLineJoin\n * @param {number} options.strokeMiterLimit https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit\n * @param {boolean} options.strokeUniform\n * @param {number} options.scaleX\n * @param {number} options.scaleY\n * @param {boolean} [openPath] whether the shape is open or not, affects the calculations of the first and last points\n * @returns {fabric.Point[]} array of size 2n/4n of all suspected points\n */\n projectStrokeOnPoints: function (points, options, openPath) {\n var coords = [], s = options.strokeWidth / 2,\n strokeUniformScalar = options.strokeUniform ?\n new fabric.Point(1 / options.scaleX, 1 / options.scaleY) : new fabric.Point(1, 1),\n getStrokeHatVector = function (v) {\n var scalar = s / (Math.hypot(v.x, v.y));\n return new fabric.Point(v.x * scalar * strokeUniformScalar.x, v.y * scalar * strokeUniformScalar.y);\n };\n if (points.length <= 1) {return coords;}\n points.forEach(function (p, index) {\n var A = new fabric.Point(p.x, p.y), B, C;\n if (index === 0) {\n C = points[index + 1];\n B = openPath ? getStrokeHatVector(fabric.util.createVector(C, A)).addEquals(A) : points[points.length - 1];\n }\n else if (index === points.length - 1) {\n B = points[index - 1];\n C = openPath ? getStrokeHatVector(fabric.util.createVector(B, A)).addEquals(A) : points[0];\n }\n else {\n B = points[index - 1];\n C = points[index + 1];\n }\n var bisector = fabric.util.getBisector(A, B, C),\n bisectorVector = bisector.vector,\n alpha = bisector.angle,\n scalar,\n miterVector;\n if (options.strokeLineJoin === 'miter') {\n scalar = -s / Math.sin(alpha / 2);\n miterVector = new fabric.Point(\n bisectorVector.x * scalar * strokeUniformScalar.x,\n bisectorVector.y * scalar * strokeUniformScalar.y\n );\n if (Math.hypot(miterVector.x, miterVector.y) / s <= options.strokeMiterLimit) {\n coords.push(A.add(miterVector));\n coords.push(A.subtract(miterVector));\n return;\n }\n }\n scalar = -s * Math.SQRT2;\n miterVector = new fabric.Point(\n bisectorVector.x * scalar * strokeUniformScalar.x,\n bisectorVector.y * scalar * strokeUniformScalar.y\n );\n coords.push(A.add(miterVector));\n coords.push(A.subtract(miterVector));\n });\n return coords;\n },\n\n /**\n * Apply transform t to point p\n * @static\n * @memberOf fabric.util\n * @param {fabric.Point} p The point to transform\n * @param {Array} t The transform\n * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied\n * @return {fabric.Point} The transformed point\n */\n transformPoint: function(p, t, ignoreOffset) {\n if (ignoreOffset) {\n return new fabric.Point(\n t[0] * p.x + t[2] * p.y,\n t[1] * p.x + t[3] * p.y\n );\n }\n return new fabric.Point(\n t[0] * p.x + t[2] * p.y + t[4],\n t[1] * p.x + t[3] * p.y + t[5]\n );\n },\n\n /**\n * Returns coordinates of points's bounding rectangle (left, top, width, height)\n * @param {Array} points 4 points array\n * @param {Array} [transform] an array of 6 numbers representing a 2x3 transform matrix\n * @return {Object} Object with left, top, width, height properties\n */\n makeBoundingBoxFromPoints: function(points, transform) {\n if (transform) {\n for (var i = 0; i < points.length; i++) {\n points[i] = fabric.util.transformPoint(points[i], transform);\n }\n }\n var xPoints = [points[0].x, points[1].x, points[2].x, points[3].x],\n minX = fabric.util.array.min(xPoints),\n maxX = fabric.util.array.max(xPoints),\n width = maxX - minX,\n yPoints = [points[0].y, points[1].y, points[2].y, points[3].y],\n minY = fabric.util.array.min(yPoints),\n maxY = fabric.util.array.max(yPoints),\n height = maxY - minY;\n\n return {\n left: minX,\n top: minY,\n width: width,\n height: height\n };\n },\n\n /**\n * Invert transformation t\n * @static\n * @memberOf fabric.util\n * @param {Array} t The transform\n * @return {Array} The inverted transform\n */\n invertTransform: function(t) {\n var a = 1 / (t[0] * t[3] - t[1] * t[2]),\n r = [a * t[3], -a * t[1], -a * t[2], a * t[0]],\n o = fabric.util.transformPoint({ x: t[4], y: t[5] }, r, true);\n r[4] = -o.x;\n r[5] = -o.y;\n return r;\n },\n\n /**\n * A wrapper around Number#toFixed, which contrary to native method returns number, not string.\n * @static\n * @memberOf fabric.util\n * @param {Number|String} number number to operate on\n * @param {Number} fractionDigits number of fraction digits to \"leave\"\n * @return {Number}\n */\n toFixed: function(number, fractionDigits) {\n return parseFloat(Number(number).toFixed(fractionDigits));\n },\n\n /**\n * Converts from attribute value to pixel value if applicable.\n * Returns converted pixels or original value not converted.\n * @param {Number|String} value number to operate on\n * @param {Number} fontSize\n * @return {Number|String}\n */\n parseUnit: function(value, fontSize) {\n var unit = /\\D{0,2}$/.exec(value),\n number = parseFloat(value);\n if (!fontSize) {\n fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;\n }\n switch (unit[0]) {\n case 'mm':\n return number * fabric.DPI / 25.4;\n\n case 'cm':\n return number * fabric.DPI / 2.54;\n\n case 'in':\n return number * fabric.DPI;\n\n case 'pt':\n return number * fabric.DPI / 72; // or * 4 / 3\n\n case 'pc':\n return number * fabric.DPI / 72 * 12; // or * 16\n\n case 'em':\n return number * fontSize;\n\n default:\n return number;\n }\n },\n\n /**\n * Function which always returns `false`.\n * @static\n * @memberOf fabric.util\n * @return {Boolean}\n */\n falseFunction: function() {\n return false;\n },\n\n /**\n * Returns klass \"Class\" object of given namespace\n * @memberOf fabric.util\n * @param {String} type Type of object (eg. 'circle')\n * @param {String} namespace Namespace to get klass \"Class\" object from\n * @return {Object} klass \"Class\"\n */\n getKlass: function(type, namespace) {\n // capitalize first letter only\n type = fabric.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));\n return fabric.util.resolveNamespace(namespace)[type];\n },\n\n /**\n * Returns array of attributes for given svg that fabric parses\n * @memberOf fabric.util\n * @param {String} type Type of svg element (eg. 'circle')\n * @return {Array} string names of supported attributes\n */\n getSvgAttributes: function(type) {\n var attributes = [\n 'instantiated_by_use',\n 'style',\n 'id',\n 'class'\n ];\n switch (type) {\n case 'linearGradient':\n attributes = attributes.concat(['x1', 'y1', 'x2', 'y2', 'gradientUnits', 'gradientTransform']);\n break;\n case 'radialGradient':\n attributes = attributes.concat(['gradientUnits', 'gradientTransform', 'cx', 'cy', 'r', 'fx', 'fy', 'fr']);\n break;\n case 'stop':\n attributes = attributes.concat(['offset', 'stop-color', 'stop-opacity']);\n break;\n }\n return attributes;\n },\n\n /**\n * Returns object of given namespace\n * @memberOf fabric.util\n * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric'\n * @return {Object} Object for given namespace (default fabric)\n */\n resolveNamespace: function(namespace) {\n if (!namespace) {\n return fabric;\n }\n\n var parts = namespace.split('.'),\n len = parts.length, i,\n obj = global || fabric.window;\n\n for (i = 0; i < len; ++i) {\n obj = obj[parts[i]];\n }\n\n return obj;\n },\n\n /**\n * Loads image element from given url and passes it to a callback\n * @memberOf fabric.util\n * @param {String} url URL representing an image\n * @param {Function} callback Callback; invoked with loaded image\n * @param {*} [context] Context to invoke callback in\n * @param {Object} [crossOrigin] crossOrigin value to set image element to\n */\n loadImage: function(url, callback, context, crossOrigin) {\n if (!url) {\n callback && callback.call(context, url);\n return;\n }\n\n var img = fabric.util.createImage();\n\n /** @ignore */\n var onLoadCallback = function () {\n callback && callback.call(context, img, false);\n img = img.onload = img.onerror = null;\n };\n\n img.onload = onLoadCallback;\n /** @ignore */\n img.onerror = function() {\n fabric.log('Error loading ' + img.src);\n callback && callback.call(context, null, true);\n img = img.onload = img.onerror = null;\n };\n\n // data-urls appear to be buggy with crossOrigin\n // https://github.com/kangax/fabric.js/commit/d0abb90f1cd5c5ef9d2a94d3fb21a22330da3e0a#commitcomment-4513767\n // see https://code.google.com/p/chromium/issues/detail?id=315152\n // https://bugzilla.mozilla.org/show_bug.cgi?id=935069\n // crossOrigin null is the same as not set.\n if (url.indexOf('data') !== 0 &&\n crossOrigin !== undefined &&\n crossOrigin !== null) {\n img.crossOrigin = crossOrigin;\n }\n\n // IE10 / IE11-Fix: SVG contents from data: URI\n // will only be available if the IMG is present\n // in the DOM (and visible)\n if (url.substring(0,14) === 'data:image/svg') {\n img.onload = null;\n fabric.util.loadImageInDom(img, onLoadCallback);\n }\n\n img.src = url;\n },\n\n /**\n * Attaches SVG image with data: URL to the dom\n * @memberOf fabric.util\n * @param {Object} img Image object with data:image/svg src\n * @param {Function} callback Callback; invoked with loaded image\n * @return {Object} DOM element (div containing the SVG image)\n */\n loadImageInDom: function(img, onLoadCallback) {\n var div = fabric.document.createElement('div');\n div.style.width = div.style.height = '1px';\n div.style.left = div.style.top = '-100%';\n div.style.position = 'absolute';\n div.appendChild(img);\n fabric.document.querySelector('body').appendChild(div);\n /**\n * Wrap in function to:\n * 1. Call existing callback\n * 2. Cleanup DOM\n */\n img.onload = function () {\n onLoadCallback();\n div.parentNode.removeChild(div);\n div = null;\n };\n },\n\n /**\n * Creates corresponding fabric instances from their object representations\n * @static\n * @memberOf fabric.util\n * @param {Array} objects Objects to enliven\n * @param {Function} callback Callback to invoke when all objects are created\n * @param {String} namespace Namespace to get klass \"Class\" object from\n * @param {Function} reviver Method for further parsing of object elements,\n * called after each fabric object created.\n */\n enlivenObjects: function(objects, callback, namespace, reviver) {\n objects = objects || [];\n\n var enlivenedObjects = [],\n numLoadedObjects = 0,\n numTotalObjects = objects.length;\n\n function onLoaded() {\n if (++numLoadedObjects === numTotalObjects) {\n callback && callback(enlivenedObjects.filter(function(obj) {\n // filter out undefined objects (objects that gave error)\n return obj;\n }));\n }\n }\n\n if (!numTotalObjects) {\n callback && callback(enlivenedObjects);\n return;\n }\n\n objects.forEach(function (o, index) {\n // if sparse array\n if (!o || !o.type) {\n onLoaded();\n return;\n }\n var klass = fabric.util.getKlass(o.type, namespace);\n klass.fromObject(o, function (obj, error) {\n error || (enlivenedObjects[index] = obj);\n reviver && reviver(o, obj, error);\n onLoaded();\n });\n });\n },\n\n /**\n * Creates corresponding fabric instances residing in an object, e.g. `clipPath`\n * @see {@link fabric.Object.ENLIVEN_PROPS}\n * @param {Object} object\n * @param {Object} [context] assign enlived props to this object (pass null to skip this)\n * @param {(objects:fabric.Object[]) => void} callback\n */\n enlivenObjectEnlivables: function (object, context, callback) {\n var enlivenProps = fabric.Object.ENLIVEN_PROPS.filter(function (key) { return !!object[key]; });\n fabric.util.enlivenObjects(enlivenProps.map(function (key) { return object[key]; }), function (enlivedProps) {\n var objects = {};\n enlivenProps.forEach(function (key, index) {\n objects[key] = enlivedProps[index];\n context && (context[key] = enlivedProps[index]);\n });\n callback && callback(objects);\n });\n },\n\n /**\n * Create and wait for loading of patterns\n * @static\n * @memberOf fabric.util\n * @param {Array} patterns Objects to enliven\n * @param {Function} callback Callback to invoke when all objects are created\n * called after each fabric object created.\n */\n enlivenPatterns: function(patterns, callback) {\n patterns = patterns || [];\n\n function onLoaded() {\n if (++numLoadedPatterns === numPatterns) {\n callback && callback(enlivenedPatterns);\n }\n }\n\n var enlivenedPatterns = [],\n numLoadedPatterns = 0,\n numPatterns = patterns.length;\n\n if (!numPatterns) {\n callback && callback(enlivenedPatterns);\n return;\n }\n\n patterns.forEach(function (p, index) {\n if (p && p.source) {\n new fabric.Pattern(p, function(pattern) {\n enlivenedPatterns[index] = pattern;\n onLoaded();\n });\n }\n else {\n enlivenedPatterns[index] = p;\n onLoaded();\n }\n });\n },\n\n /**\n * Groups SVG elements (usually those retrieved from SVG document)\n * @static\n * @memberOf fabric.util\n * @param {Array} elements SVG elements to group\n * @param {Object} [options] Options object\n * @param {String} path Value to set sourcePath to\n * @return {fabric.Object|fabric.Group}\n */\n groupSVGElements: function(elements, options, path) {\n var object;\n if (elements && elements.length === 1) {\n if (typeof path !== 'undefined') {\n elements[0].sourcePath = path;\n }\n return elements[0];\n }\n if (options) {\n if (options.width && options.height) {\n options.centerPoint = {\n x: options.width / 2,\n y: options.height / 2\n };\n }\n else {\n delete options.width;\n delete options.height;\n }\n }\n object = new fabric.Group(elements, options);\n if (typeof path !== 'undefined') {\n object.sourcePath = path;\n }\n return object;\n },\n\n /**\n * Populates an object with properties of another object\n * @static\n * @memberOf fabric.util\n * @param {Object} source Source object\n * @param {Object} destination Destination object\n * @return {Array} properties Properties names to include\n */\n populateWithProperties: function(source, destination, properties) {\n if (properties && Array.isArray(properties)) {\n for (var i = 0, len = properties.length; i < len; i++) {\n if (properties[i] in source) {\n destination[properties[i]] = source[properties[i]];\n }\n }\n }\n },\n\n /**\n * Creates canvas element\n * @static\n * @memberOf fabric.util\n * @return {CanvasElement} initialized canvas element\n */\n createCanvasElement: function() {\n return fabric.document.createElement('canvas');\n },\n\n /**\n * Creates a canvas element that is a copy of another and is also painted\n * @param {CanvasElement} canvas to copy size and content of\n * @static\n * @memberOf fabric.util\n * @return {CanvasElement} initialized canvas element\n */\n copyCanvasElement: function(canvas) {\n var newCanvas = fabric.util.createCanvasElement();\n newCanvas.width = canvas.width;\n newCanvas.height = canvas.height;\n newCanvas.getContext('2d').drawImage(canvas, 0, 0);\n return newCanvas;\n },\n\n /**\n * since 2.6.0 moved from canvas instance to utility.\n * @param {CanvasElement} canvasEl to copy size and content of\n * @param {String} format 'jpeg' or 'png', in some browsers 'webp' is ok too\n * @param {Number} quality <= 1 and > 0\n * @static\n * @memberOf fabric.util\n * @return {String} data url\n */\n toDataURL: function(canvasEl, format, quality) {\n return canvasEl.toDataURL('image/' + format, quality);\n },\n\n /**\n * Creates image element (works on client and node)\n * @static\n * @memberOf fabric.util\n * @return {HTMLImageElement} HTML image element\n */\n createImage: function() {\n return fabric.document.createElement('img');\n },\n\n /**\n * Multiply matrix A by matrix B to nest transformations\n * @static\n * @memberOf fabric.util\n * @param {Array} a First transformMatrix\n * @param {Array} b Second transformMatrix\n * @param {Boolean} is2x2 flag to multiply matrices as 2x2 matrices\n * @return {Array} The product of the two transform matrices\n */\n multiplyTransformMatrices: function(a, b, is2x2) {\n // Matrix multiply a * b\n return [\n a[0] * b[0] + a[2] * b[1],\n a[1] * b[0] + a[3] * b[1],\n a[0] * b[2] + a[2] * b[3],\n a[1] * b[2] + a[3] * b[3],\n is2x2 ? 0 : a[0] * b[4] + a[2] * b[5] + a[4],\n is2x2 ? 0 : a[1] * b[4] + a[3] * b[5] + a[5]\n ];\n },\n\n /**\n * Decomposes standard 2x3 matrix into transform components\n * @static\n * @memberOf fabric.util\n * @param {Array} a transformMatrix\n * @return {Object} Components of transform\n */\n qrDecompose: function(a) {\n var angle = atan2(a[1], a[0]),\n denom = pow(a[0], 2) + pow(a[1], 2),\n scaleX = sqrt(denom),\n scaleY = (a[0] * a[3] - a[2] * a[1]) / scaleX,\n skewX = atan2(a[0] * a[2] + a[1] * a [3], denom);\n return {\n angle: angle / PiBy180,\n scaleX: scaleX,\n scaleY: scaleY,\n skewX: skewX / PiBy180,\n skewY: 0,\n translateX: a[4],\n translateY: a[5]\n };\n },\n\n /**\n * Returns a transform matrix starting from an object of the same kind of\n * the one returned from qrDecompose, useful also if you want to calculate some\n * transformations from an object that is not enlived yet\n * @static\n * @memberOf fabric.util\n * @param {Object} options\n * @param {Number} [options.angle] angle in degrees\n * @return {Number[]} transform matrix\n */\n calcRotateMatrix: function(options) {\n if (!options.angle) {\n return fabric.iMatrix.concat();\n }\n var theta = fabric.util.degreesToRadians(options.angle),\n cos = fabric.util.cos(theta),\n sin = fabric.util.sin(theta);\n return [cos, sin, -sin, cos, 0, 0];\n },\n\n /**\n * Returns a transform matrix starting from an object of the same kind of\n * the one returned from qrDecompose, useful also if you want to calculate some\n * transformations from an object that is not enlived yet.\n * is called DimensionsTransformMatrix because those properties are the one that influence\n * the size of the resulting box of the object.\n * @static\n * @memberOf fabric.util\n * @param {Object} options\n * @param {Number} [options.scaleX]\n * @param {Number} [options.scaleY]\n * @param {Boolean} [options.flipX]\n * @param {Boolean} [options.flipY]\n * @param {Number} [options.skewX]\n * @param {Number} [options.skewY]\n * @return {Number[]} transform matrix\n */\n calcDimensionsMatrix: function(options) {\n var scaleX = typeof options.scaleX === 'undefined' ? 1 : options.scaleX,\n scaleY = typeof options.scaleY === 'undefined' ? 1 : options.scaleY,\n scaleMatrix = [\n options.flipX ? -scaleX : scaleX,\n 0,\n 0,\n options.flipY ? -scaleY : scaleY,\n 0,\n 0],\n multiply = fabric.util.multiplyTransformMatrices,\n degreesToRadians = fabric.util.degreesToRadians;\n if (options.skewX) {\n scaleMatrix = multiply(\n scaleMatrix,\n [1, 0, Math.tan(degreesToRadians(options.skewX)), 1],\n true);\n }\n if (options.skewY) {\n scaleMatrix = multiply(\n scaleMatrix,\n [1, Math.tan(degreesToRadians(options.skewY)), 0, 1],\n true);\n }\n return scaleMatrix;\n },\n\n /**\n * Returns a transform matrix starting from an object of the same kind of\n * the one returned from qrDecompose, useful also if you want to calculate some\n * transformations from an object that is not enlived yet\n * @static\n * @memberOf fabric.util\n * @param {Object} options\n * @param {Number} [options.angle]\n * @param {Number} [options.scaleX]\n * @param {Number} [options.scaleY]\n * @param {Boolean} [options.flipX]\n * @param {Boolean} [options.flipY]\n * @param {Number} [options.skewX]\n * @param {Number} [options.skewX]\n * @param {Number} [options.translateX]\n * @param {Number} [options.translateY]\n * @return {Number[]} transform matrix\n */\n composeMatrix: function(options) {\n var matrix = [1, 0, 0, 1, options.translateX || 0, options.translateY || 0],\n multiply = fabric.util.multiplyTransformMatrices;\n if (options.angle) {\n matrix = multiply(matrix, fabric.util.calcRotateMatrix(options));\n }\n if (options.scaleX !== 1 || options.scaleY !== 1 ||\n options.skewX || options.skewY || options.flipX || options.flipY) {\n matrix = multiply(matrix, fabric.util.calcDimensionsMatrix(options));\n }\n return matrix;\n },\n\n /**\n * reset an object transform state to neutral. Top and left are not accounted for\n * @static\n * @memberOf fabric.util\n * @param {fabric.Object} target object to transform\n */\n resetObjectTransform: function (target) {\n target.scaleX = 1;\n target.scaleY = 1;\n target.skewX = 0;\n target.skewY = 0;\n target.flipX = false;\n target.flipY = false;\n target.rotate(0);\n },\n\n /**\n * Extract Object transform values\n * @static\n * @memberOf fabric.util\n * @param {fabric.Object} target object to read from\n * @return {Object} Components of transform\n */\n saveObjectTransform: function (target) {\n return {\n scaleX: target.scaleX,\n scaleY: target.scaleY,\n skewX: target.skewX,\n skewY: target.skewY,\n angle: target.angle,\n left: target.left,\n flipX: target.flipX,\n flipY: target.flipY,\n top: target.top\n };\n },\n\n /**\n * Returns true if context has transparent pixel\n * at specified location (taking tolerance into account)\n * @param {CanvasRenderingContext2D} ctx context\n * @param {Number} x x coordinate\n * @param {Number} y y coordinate\n * @param {Number} tolerance Tolerance\n */\n isTransparent: function(ctx, x, y, tolerance) {\n\n // If tolerance is > 0 adjust start coords to take into account.\n // If moves off Canvas fix to 0\n if (tolerance > 0) {\n if (x > tolerance) {\n x -= tolerance;\n }\n else {\n x = 0;\n }\n if (y > tolerance) {\n y -= tolerance;\n }\n else {\n y = 0;\n }\n }\n\n var _isTransparent = true, i, temp,\n imageData = ctx.getImageData(x, y, (tolerance * 2) || 1, (tolerance * 2) || 1),\n l = imageData.data.length;\n\n // Split image data - for tolerance > 1, pixelDataSize = 4;\n for (i = 3; i < l; i += 4) {\n temp = imageData.data[i];\n _isTransparent = temp <= 0;\n if (_isTransparent === false) {\n break; // Stop if colour found\n }\n }\n\n imageData = null;\n\n return _isTransparent;\n },\n\n /**\n * Parse preserveAspectRatio attribute from element\n * @param {string} attribute to be parsed\n * @return {Object} an object containing align and meetOrSlice attribute\n */\n parsePreserveAspectRatioAttribute: function(attribute) {\n var meetOrSlice = 'meet', alignX = 'Mid', alignY = 'Mid',\n aspectRatioAttrs = attribute.split(' '), align;\n\n if (aspectRatioAttrs && aspectRatioAttrs.length) {\n meetOrSlice = aspectRatioAttrs.pop();\n if (meetOrSlice !== 'meet' && meetOrSlice !== 'slice') {\n align = meetOrSlice;\n meetOrSlice = 'meet';\n }\n else if (aspectRatioAttrs.length) {\n align = aspectRatioAttrs.pop();\n }\n }\n //divide align in alignX and alignY\n alignX = align !== 'none' ? align.slice(1, 4) : 'none';\n alignY = align !== 'none' ? align.slice(5, 8) : 'none';\n return {\n meetOrSlice: meetOrSlice,\n alignX: alignX,\n alignY: alignY\n };\n },\n\n /**\n * Clear char widths cache for the given font family or all the cache if no\n * fontFamily is specified.\n * Use it if you know you are loading fonts in a lazy way and you are not waiting\n * for custom fonts to load properly when adding text objects to the canvas.\n * If a text object is added when its own font is not loaded yet, you will get wrong\n * measurement and so wrong bounding boxes.\n * After the font cache is cleared, either change the textObject text content or call\n * initDimensions() to trigger a recalculation\n * @memberOf fabric.util\n * @param {String} [fontFamily] font family to clear\n */\n clearFabricFontCache: function(fontFamily) {\n fontFamily = (fontFamily || '').toLowerCase();\n if (!fontFamily) {\n fabric.charWidthsCache = { };\n }\n else if (fabric.charWidthsCache[fontFamily]) {\n delete fabric.charWidthsCache[fontFamily];\n }\n },\n\n /**\n * Given current aspect ratio, determines the max width and height that can\n * respect the total allowed area for the cache.\n * @memberOf fabric.util\n * @param {Number} ar aspect ratio\n * @param {Number} maximumArea Maximum area you want to achieve\n * @return {Object.x} Limited dimensions by X\n * @return {Object.y} Limited dimensions by Y\n */\n limitDimsByArea: function(ar, maximumArea) {\n var roughWidth = Math.sqrt(maximumArea * ar),\n perfLimitSizeY = Math.floor(maximumArea / roughWidth);\n return { x: Math.floor(roughWidth), y: perfLimitSizeY };\n },\n\n capValue: function(min, value, max) {\n return Math.max(min, Math.min(value, max));\n },\n\n /**\n * Finds the scale for the object source to fit inside the object destination,\n * keeping aspect ratio intact.\n * respect the total allowed area for the cache.\n * @memberOf fabric.util\n * @param {Object | fabric.Object} source\n * @param {Number} source.height natural unscaled height of the object\n * @param {Number} source.width natural unscaled width of the object\n * @param {Object | fabric.Object} destination\n * @param {Number} destination.height natural unscaled height of the object\n * @param {Number} destination.width natural unscaled width of the object\n * @return {Number} scale factor to apply to source to fit into destination\n */\n findScaleToFit: function(source, destination) {\n return Math.min(destination.width / source.width, destination.height / source.height);\n },\n\n /**\n * Finds the scale for the object source to cover entirely the object destination,\n * keeping aspect ratio intact.\n * respect the total allowed area for the cache.\n * @memberOf fabric.util\n * @param {Object | fabric.Object} source\n * @param {Number} source.height natural unscaled height of the object\n * @param {Number} source.width natural unscaled width of the object\n * @param {Object | fabric.Object} destination\n * @param {Number} destination.height natural unscaled height of the object\n * @param {Number} destination.width natural unscaled width of the object\n * @return {Number} scale factor to apply to source to cover destination\n */\n findScaleToCover: function(source, destination) {\n return Math.max(destination.width / source.width, destination.height / source.height);\n },\n\n /**\n * given an array of 6 number returns something like `\"matrix(...numbers)\"`\n * @memberOf fabric.util\n * @param {Array} transform an array with 6 numbers\n * @return {String} transform matrix for svg\n * @return {Object.y} Limited dimensions by Y\n */\n matrixToSVG: function(transform) {\n return 'matrix(' + transform.map(function(value) {\n return fabric.util.toFixed(value, fabric.Object.NUM_FRACTION_DIGITS);\n }).join(' ') + ')';\n },\n\n /**\n * given an object and a transform, apply the inverse transform to the object,\n * this is equivalent to remove from that object that transformation, so that\n * added in a space with the removed transform, the object will be the same as before.\n * Removing from an object a transform that scale by 2 is like scaling it by 1/2.\n * Removing from an object a transfrom that rotate by 30deg is like rotating by 30deg\n * in the opposite direction.\n * This util is used to add objects inside transformed groups or nested groups.\n * @memberOf fabric.util\n * @param {fabric.Object} object the object you want to transform\n * @param {Array} transform the destination transform\n */\n removeTransformFromObject: function(object, transform) {\n var inverted = fabric.util.invertTransform(transform),\n finalTransform = fabric.util.multiplyTransformMatrices(inverted, object.calcOwnMatrix());\n fabric.util.applyTransformToObject(object, finalTransform);\n },\n\n /**\n * given an object and a transform, apply the transform to the object.\n * this is equivalent to change the space where the object is drawn.\n * Adding to an object a transform that scale by 2 is like scaling it by 2.\n * This is used when removing an object from an active selection for example.\n * @memberOf fabric.util\n * @param {fabric.Object} object the object you want to transform\n * @param {Array} transform the destination transform\n */\n addTransformToObject: function(object, transform) {\n fabric.util.applyTransformToObject(\n object,\n fabric.util.multiplyTransformMatrices(transform, object.calcOwnMatrix())\n );\n },\n\n /**\n * discard an object transform state and apply the one from the matrix.\n * @memberOf fabric.util\n * @param {fabric.Object} object the object you want to transform\n * @param {Array} transform the destination transform\n */\n applyTransformToObject: function(object, transform) {\n var options = fabric.util.qrDecompose(transform),\n center = new fabric.Point(options.translateX, options.translateY);\n object.flipX = false;\n object.flipY = false;\n object.set('scaleX', options.scaleX);\n object.set('scaleY', options.scaleY);\n object.skewX = options.skewX;\n object.skewY = options.skewY;\n object.angle = options.angle;\n object.setPositionByOrigin(center, 'center', 'center');\n },\n\n /**\n * given a width and height, return the size of the bounding box\n * that can contains the box with width/height with applied transform\n * described in options.\n * Use to calculate the boxes around objects for controls.\n * @memberOf fabric.util\n * @param {Number} width\n * @param {Number} height\n * @param {Object} options\n * @param {Number} options.scaleX\n * @param {Number} options.scaleY\n * @param {Number} options.skewX\n * @param {Number} options.skewY\n * @return {Object.x} width of containing\n * @return {Object.y} height of containing\n */\n sizeAfterTransform: function(width, height, options) {\n var dimX = width / 2, dimY = height / 2,\n points = [\n {\n x: -dimX,\n y: -dimY\n },\n {\n x: dimX,\n y: -dimY\n },\n {\n x: -dimX,\n y: dimY\n },\n {\n x: dimX,\n y: dimY\n }],\n transformMatrix = fabric.util.calcDimensionsMatrix(options),\n bbox = fabric.util.makeBoundingBoxFromPoints(points, transformMatrix);\n return {\n x: bbox.width,\n y: bbox.height,\n };\n },\n\n /**\n * Merges 2 clip paths into one visually equal clip path\n *\n * **IMPORTANT**:\\\n * Does **NOT** clone the arguments, clone them proir if necessary.\n *\n * Creates a wrapper (group) that contains one clip path and is clipped by the other so content is kept where both overlap.\n * Use this method if both the clip paths may have nested clip paths of their own, so assigning one to the other's clip path property is not possible.\n *\n * In order to handle the `inverted` property we follow logic described in the following cases:\\\n * **(1)** both clip paths are inverted - the clip paths pass the inverted prop to the wrapper and loose it themselves.\\\n * **(2)** one is inverted and the other isn't - the wrapper shouldn't become inverted and the inverted clip path must clip the non inverted one to produce an identical visual effect.\\\n * **(3)** both clip paths are not inverted - wrapper and clip paths remain unchanged.\n *\n * @memberOf fabric.util\n * @param {fabric.Object} c1\n * @param {fabric.Object} c2\n * @returns {fabric.Object} merged clip path\n */\n mergeClipPaths: function (c1, c2) {\n var a = c1, b = c2;\n if (a.inverted && !b.inverted) {\n // case (2)\n a = c2;\n b = c1;\n }\n // `b` becomes `a`'s clip path so we transform `b` to `a` coordinate plane\n fabric.util.applyTransformToObject(\n b,\n fabric.util.multiplyTransformMatrices(\n fabric.util.invertTransform(a.calcTransformMatrix()),\n b.calcTransformMatrix()\n )\n );\n // assign the `inverted` prop to the wrapping group\n var inverted = a.inverted && b.inverted;\n if (inverted) {\n // case (1)\n a.inverted = b.inverted = false;\n }\n return new fabric.Group([a], { clipPath: b, inverted: inverted });\n },\n\n /**\n * @memberOf fabric.util\n * @param {Object} prevStyle first style to compare\n * @param {Object} thisStyle second style to compare\n * @param {boolean} forTextSpans whether to check overline, underline, and line-through properties\n * @return {boolean} true if the style changed\n */\n hasStyleChanged: function(prevStyle, thisStyle, forTextSpans) {\n forTextSpans = forTextSpans || false;\n return (prevStyle.fill !== thisStyle.fill ||\n prevStyle.stroke !== thisStyle.stroke ||\n prevStyle.strokeWidth !== thisStyle.strokeWidth ||\n prevStyle.fontSize !== thisStyle.fontSize ||\n prevStyle.fontFamily !== thisStyle.fontFamily ||\n prevStyle.fontWeight !== thisStyle.fontWeight ||\n prevStyle.fontStyle !== thisStyle.fontStyle ||\n prevStyle.textBackgroundColor !== thisStyle.textBackgroundColor ||\n prevStyle.deltaY !== thisStyle.deltaY) ||\n (forTextSpans &&\n (prevStyle.overline !== thisStyle.overline ||\n prevStyle.underline !== thisStyle.underline ||\n prevStyle.linethrough !== thisStyle.linethrough));\n },\n\n /**\n * Returns the array form of a text object's inline styles property with styles grouped in ranges\n * rather than per character. This format is less verbose, and is better suited for storage\n * so it is used in serialization (not during runtime).\n * @memberOf fabric.util\n * @param {object} styles per character styles for a text object\n * @param {String} text the text string that the styles are applied to\n * @return {{start: number, end: number, style: object}[]}\n */\n stylesToArray: function(styles, text) {\n // clone style structure to prevent mutation\n var styles = fabric.util.object.clone(styles, true),\n textLines = text.split('\\n'),\n charIndex = -1, prevStyle = {}, stylesArray = [];\n //loop through each textLine\n for (var i = 0; i < textLines.length; i++) {\n if (!styles[i]) {\n //no styles exist for this line, so add the line's length to the charIndex total\n charIndex += textLines[i].length;\n continue;\n }\n //loop through each character of the current line\n for (var c = 0; c < textLines[i].length; c++) {\n charIndex++;\n var thisStyle = styles[i][c];\n //check if style exists for this character\n if (thisStyle && Object.keys(thisStyle).length > 0) {\n var styleChanged = fabric.util.hasStyleChanged(prevStyle, thisStyle, true);\n if (styleChanged) {\n stylesArray.push({\n start: charIndex,\n end: charIndex + 1,\n style: thisStyle\n });\n }\n else {\n //if style is the same as previous character, increase end index\n stylesArray[stylesArray.length - 1].end++;\n }\n }\n prevStyle = thisStyle || {};\n }\n }\n return stylesArray;\n },\n\n /**\n * Returns the object form of the styles property with styles that are assigned per\n * character rather than grouped by range. This format is more verbose, and is\n * only used during runtime (not for serialization/storage)\n * @memberOf fabric.util\n * @param {Array} styles the serialized form of a text object's styles\n * @param {String} text the text string that the styles are applied to\n * @return {Object}\n */\n stylesFromArray: function(styles, text) {\n if (!Array.isArray(styles)) {\n return styles;\n }\n var textLines = text.split('\\n'),\n charIndex = -1, styleIndex = 0, stylesObject = {};\n //loop through each textLine\n for (var i = 0; i < textLines.length; i++) {\n //loop through each character of the current line\n for (var c = 0; c < textLines[i].length; c++) {\n charIndex++;\n //check if there's a style collection that includes the current character\n if (styles[styleIndex]\n && styles[styleIndex].start <= charIndex\n && charIndex < styles[styleIndex].end) {\n //create object for line index if it doesn't exist\n stylesObject[i] = stylesObject[i] || {};\n //assign a style at this character's index\n stylesObject[i][c] = Object.assign({}, styles[styleIndex].style);\n //if character is at the end of the current style collection, move to the next\n if (charIndex === styles[styleIndex].end - 1) {\n styleIndex++;\n }\n }\n }\n }\n return stylesObject;\n }\n };\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function() {\n var _join = Array.prototype.join,\n commandLengths = {\n m: 2,\n l: 2,\n h: 1,\n v: 1,\n c: 6,\n s: 4,\n q: 4,\n t: 2,\n a: 7\n },\n repeatedCommands = {\n m: 'l',\n M: 'L'\n };\n function segmentToBezier(th2, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY) {\n var costh2 = fabric.util.cos(th2),\n sinth2 = fabric.util.sin(th2),\n costh3 = fabric.util.cos(th3),\n sinth3 = fabric.util.sin(th3),\n toX = cosTh * rx * costh3 - sinTh * ry * sinth3 + cx1,\n toY = sinTh * rx * costh3 + cosTh * ry * sinth3 + cy1,\n cp1X = fromX + mT * ( -cosTh * rx * sinth2 - sinTh * ry * costh2),\n cp1Y = fromY + mT * ( -sinTh * rx * sinth2 + cosTh * ry * costh2),\n cp2X = toX + mT * ( cosTh * rx * sinth3 + sinTh * ry * costh3),\n cp2Y = toY + mT * ( sinTh * rx * sinth3 - cosTh * ry * costh3);\n\n return ['C',\n cp1X, cp1Y,\n cp2X, cp2Y,\n toX, toY\n ];\n }\n\n /* Adapted from http://dxr.mozilla.org/mozilla-central/source/content/svg/content/src/nsSVGPathDataParser.cpp\n * by Andrea Bogazzi code is under MPL. if you don't have a copy of the license you can take it here\n * http://mozilla.org/MPL/2.0/\n */\n function arcToSegments(toX, toY, rx, ry, large, sweep, rotateX) {\n var PI = Math.PI, th = rotateX * PI / 180,\n sinTh = fabric.util.sin(th),\n cosTh = fabric.util.cos(th),\n fromX = 0, fromY = 0;\n\n rx = Math.abs(rx);\n ry = Math.abs(ry);\n\n var px = -cosTh * toX * 0.5 - sinTh * toY * 0.5,\n py = -cosTh * toY * 0.5 + sinTh * toX * 0.5,\n rx2 = rx * rx, ry2 = ry * ry, py2 = py * py, px2 = px * px,\n pl = rx2 * ry2 - rx2 * py2 - ry2 * px2,\n root = 0;\n\n if (pl < 0) {\n var s = Math.sqrt(1 - pl / (rx2 * ry2));\n rx *= s;\n ry *= s;\n }\n else {\n root = (large === sweep ? -1.0 : 1.0) *\n Math.sqrt( pl / (rx2 * py2 + ry2 * px2));\n }\n\n var cx = root * rx * py / ry,\n cy = -root * ry * px / rx,\n cx1 = cosTh * cx - sinTh * cy + toX * 0.5,\n cy1 = sinTh * cx + cosTh * cy + toY * 0.5,\n mTheta = calcVectorAngle(1, 0, (px - cx) / rx, (py - cy) / ry),\n dtheta = calcVectorAngle((px - cx) / rx, (py - cy) / ry, (-px - cx) / rx, (-py - cy) / ry);\n\n if (sweep === 0 && dtheta > 0) {\n dtheta -= 2 * PI;\n }\n else if (sweep === 1 && dtheta < 0) {\n dtheta += 2 * PI;\n }\n\n // Convert into cubic bezier segments <= 90deg\n var segments = Math.ceil(Math.abs(dtheta / PI * 2)),\n result = [], mDelta = dtheta / segments,\n mT = 8 / 3 * Math.sin(mDelta / 4) * Math.sin(mDelta / 4) / Math.sin(mDelta / 2),\n th3 = mTheta + mDelta;\n\n for (var i = 0; i < segments; i++) {\n result[i] = segmentToBezier(mTheta, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY);\n fromX = result[i][5];\n fromY = result[i][6];\n mTheta = th3;\n th3 += mDelta;\n }\n return result;\n }\n\n /*\n * Private\n */\n function calcVectorAngle(ux, uy, vx, vy) {\n var ta = Math.atan2(uy, ux),\n tb = Math.atan2(vy, vx);\n if (tb >= ta) {\n return tb - ta;\n }\n else {\n return 2 * Math.PI - (ta - tb);\n }\n }\n\n /**\n * Calculate bounding box of a beziercurve\n * @param {Number} x0 starting point\n * @param {Number} y0\n * @param {Number} x1 first control point\n * @param {Number} y1\n * @param {Number} x2 secondo control point\n * @param {Number} y2\n * @param {Number} x3 end of bezier\n * @param {Number} y3\n */\n // taken from http://jsbin.com/ivomiq/56/edit no credits available for that.\n // TODO: can we normalize this with the starting points set at 0 and then translated the bbox?\n function getBoundsOfCurve(x0, y0, x1, y1, x2, y2, x3, y3) {\n var argsString;\n if (fabric.cachesBoundsOfCurve) {\n argsString = _join.call(arguments);\n if (fabric.boundsOfCurveCache[argsString]) {\n return fabric.boundsOfCurveCache[argsString];\n }\n }\n\n var sqrt = Math.sqrt,\n min = Math.min, max = Math.max,\n abs = Math.abs, tvalues = [],\n bounds = [[], []],\n a, b, c, t, t1, t2, b2ac, sqrtb2ac;\n\n b = 6 * x0 - 12 * x1 + 6 * x2;\n a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;\n c = 3 * x1 - 3 * x0;\n\n for (var i = 0; i < 2; ++i) {\n if (i > 0) {\n b = 6 * y0 - 12 * y1 + 6 * y2;\n a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;\n c = 3 * y1 - 3 * y0;\n }\n\n if (abs(a) < 1e-12) {\n if (abs(b) < 1e-12) {\n continue;\n }\n t = -c / b;\n if (0 < t && t < 1) {\n tvalues.push(t);\n }\n continue;\n }\n b2ac = b * b - 4 * c * a;\n if (b2ac < 0) {\n continue;\n }\n sqrtb2ac = sqrt(b2ac);\n t1 = (-b + sqrtb2ac) / (2 * a);\n if (0 < t1 && t1 < 1) {\n tvalues.push(t1);\n }\n t2 = (-b - sqrtb2ac) / (2 * a);\n if (0 < t2 && t2 < 1) {\n tvalues.push(t2);\n }\n }\n\n var x, y, j = tvalues.length, jlen = j, mt;\n while (j--) {\n t = tvalues[j];\n mt = 1 - t;\n x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);\n bounds[0][j] = x;\n\n y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);\n bounds[1][j] = y;\n }\n\n bounds[0][jlen] = x0;\n bounds[1][jlen] = y0;\n bounds[0][jlen + 1] = x3;\n bounds[1][jlen + 1] = y3;\n var result = [\n {\n x: min.apply(null, bounds[0]),\n y: min.apply(null, bounds[1])\n },\n {\n x: max.apply(null, bounds[0]),\n y: max.apply(null, bounds[1])\n }\n ];\n if (fabric.cachesBoundsOfCurve) {\n fabric.boundsOfCurveCache[argsString] = result;\n }\n return result;\n }\n\n /**\n * Converts arc to a bunch of bezier curves\n * @param {Number} fx starting point x\n * @param {Number} fy starting point y\n * @param {Array} coords Arc command\n */\n function fromArcToBeziers(fx, fy, coords) {\n var rx = coords[1],\n ry = coords[2],\n rot = coords[3],\n large = coords[4],\n sweep = coords[5],\n tx = coords[6],\n ty = coords[7],\n segsNorm = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);\n\n for (var i = 0, len = segsNorm.length; i < len; i++) {\n segsNorm[i][1] += fx;\n segsNorm[i][2] += fy;\n segsNorm[i][3] += fx;\n segsNorm[i][4] += fy;\n segsNorm[i][5] += fx;\n segsNorm[i][6] += fy;\n }\n return segsNorm;\n };\n\n /**\n * This function take a parsed SVG path and make it simpler for fabricJS logic.\n * simplification consist of: only UPPERCASE absolute commands ( relative converted to absolute )\n * S converted in C, T converted in Q, A converted in C.\n * @param {Array} path the array of commands of a parsed svg path for fabric.Path\n * @return {Array} the simplified array of commands of a parsed svg path for fabric.Path\n */\n function makePathSimpler(path) {\n // x and y represent the last point of the path. the previous command point.\n // we add them to each relative command to make it an absolute comment.\n // we also swap the v V h H with L, because are easier to transform.\n var x = 0, y = 0, len = path.length,\n // x1 and y1 represent the last point of the subpath. the subpath is started with\n // m or M command. When a z or Z command is drawn, x and y need to be resetted to\n // the last x1 and y1.\n x1 = 0, y1 = 0, current, i, converted,\n // previous will host the letter of the previous command, to handle S and T.\n // controlX and controlY will host the previous reflected control point\n destinationPath = [], previous, controlX, controlY;\n for (i = 0; i < len; ++i) {\n converted = false;\n current = path[i].slice(0);\n switch (current[0]) { // first letter\n case 'l': // lineto, relative\n current[0] = 'L';\n current[1] += x;\n current[2] += y;\n // falls through\n case 'L':\n x = current[1];\n y = current[2];\n break;\n case 'h': // horizontal lineto, relative\n current[1] += x;\n // falls through\n case 'H':\n current[0] = 'L';\n current[2] = y;\n x = current[1];\n break;\n case 'v': // vertical lineto, relative\n current[1] += y;\n // falls through\n case 'V':\n current[0] = 'L';\n y = current[1];\n current[1] = x;\n current[2] = y;\n break;\n case 'm': // moveTo, relative\n current[0] = 'M';\n current[1] += x;\n current[2] += y;\n // falls through\n case 'M':\n x = current[1];\n y = current[2];\n x1 = current[1];\n y1 = current[2];\n break;\n case 'c': // bezierCurveTo, relative\n current[0] = 'C';\n current[1] += x;\n current[2] += y;\n current[3] += x;\n current[4] += y;\n current[5] += x;\n current[6] += y;\n // falls through\n case 'C':\n controlX = current[3];\n controlY = current[4];\n x = current[5];\n y = current[6];\n break;\n case 's': // shorthand cubic bezierCurveTo, relative\n current[0] = 'S';\n current[1] += x;\n current[2] += y;\n current[3] += x;\n current[4] += y;\n // falls through\n case 'S':\n // would be sScC but since we are swapping sSc for C, we check just that.\n if (previous === 'C') {\n // calculate reflection of previous control points\n controlX = 2 * x - controlX;\n controlY = 2 * y - controlY;\n }\n else {\n // If there is no previous command or if the previous command was not a C, c, S, or s,\n // the control point is coincident with the current point\n controlX = x;\n controlY = y;\n }\n x = current[3];\n y = current[4];\n current[0] = 'C';\n current[5] = current[3];\n current[6] = current[4];\n current[3] = current[1];\n current[4] = current[2];\n current[1] = controlX;\n current[2] = controlY;\n // current[3] and current[4] are NOW the second control point.\n // we keep it for the next reflection.\n controlX = current[3];\n controlY = current[4];\n break;\n case 'q': // quadraticCurveTo, relative\n current[0] = 'Q';\n current[1] += x;\n current[2] += y;\n current[3] += x;\n current[4] += y;\n // falls through\n case 'Q':\n controlX = current[1];\n controlY = current[2];\n x = current[3];\n y = current[4];\n break;\n case 't': // shorthand quadraticCurveTo, relative\n current[0] = 'T';\n current[1] += x;\n current[2] += y;\n // falls through\n case 'T':\n if (previous === 'Q') {\n // calculate reflection of previous control point\n controlX = 2 * x - controlX;\n controlY = 2 * y - controlY;\n }\n else {\n // If there is no previous command or if the previous command was not a Q, q, T or t,\n // assume the control point is coincident with the current point\n controlX = x;\n controlY = y;\n }\n current[0] = 'Q';\n x = current[1];\n y = current[2];\n current[1] = controlX;\n current[2] = controlY;\n current[3] = x;\n current[4] = y;\n break;\n case 'a':\n current[0] = 'A';\n current[6] += x;\n current[7] += y;\n // falls through\n case 'A':\n converted = true;\n destinationPath = destinationPath.concat(fromArcToBeziers(x, y, current));\n x = current[6];\n y = current[7];\n break;\n case 'z':\n case 'Z':\n x = x1;\n y = y1;\n break;\n default:\n }\n if (!converted) {\n destinationPath.push(current);\n }\n previous = current[0];\n }\n return destinationPath;\n };\n\n /**\n * Calc length from point x1,y1 to x2,y2\n * @param {Number} x1 starting point x\n * @param {Number} y1 starting point y\n * @param {Number} x2 starting point x\n * @param {Number} y2 starting point y\n * @return {Number} length of segment\n */\n function calcLineLength(x1, y1, x2, y2) {\n return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n }\n\n // functions for the Cubic beizer\n // taken from: https://github.com/konvajs/konva/blob/7.0.5/src/shapes/Path.ts#L350\n function CB1(t) {\n return t * t * t;\n }\n function CB2(t) {\n return 3 * t * t * (1 - t);\n }\n function CB3(t) {\n return 3 * t * (1 - t) * (1 - t);\n }\n function CB4(t) {\n return (1 - t) * (1 - t) * (1 - t);\n }\n\n function getPointOnCubicBezierIterator(p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y) {\n return function(pct) {\n var c1 = CB1(pct), c2 = CB2(pct), c3 = CB3(pct), c4 = CB4(pct);\n return {\n x: p4x * c1 + p3x * c2 + p2x * c3 + p1x * c4,\n y: p4y * c1 + p3y * c2 + p2y * c3 + p1y * c4\n };\n };\n }\n\n function getTangentCubicIterator(p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y) {\n return function (pct) {\n var invT = 1 - pct,\n tangentX = (3 * invT * invT * (p2x - p1x)) + (6 * invT * pct * (p3x - p2x)) +\n (3 * pct * pct * (p4x - p3x)),\n tangentY = (3 * invT * invT * (p2y - p1y)) + (6 * invT * pct * (p3y - p2y)) +\n (3 * pct * pct * (p4y - p3y));\n return Math.atan2(tangentY, tangentX);\n };\n }\n\n function QB1(t) {\n return t * t;\n }\n\n function QB2(t) {\n return 2 * t * (1 - t);\n }\n\n function QB3(t) {\n return (1 - t) * (1 - t);\n }\n\n function getPointOnQuadraticBezierIterator(p1x, p1y, p2x, p2y, p3x, p3y) {\n return function(pct) {\n var c1 = QB1(pct), c2 = QB2(pct), c3 = QB3(pct);\n return {\n x: p3x * c1 + p2x * c2 + p1x * c3,\n y: p3y * c1 + p2y * c2 + p1y * c3\n };\n };\n }\n\n function getTangentQuadraticIterator(p1x, p1y, p2x, p2y, p3x, p3y) {\n return function (pct) {\n var invT = 1 - pct,\n tangentX = (2 * invT * (p2x - p1x)) + (2 * pct * (p3x - p2x)),\n tangentY = (2 * invT * (p2y - p1y)) + (2 * pct * (p3y - p2y));\n return Math.atan2(tangentY, tangentX);\n };\n }\n\n\n // this will run over a path segment ( a cubic or quadratic segment) and approximate it\n // with 100 segemnts. This will good enough to calculate the length of the curve\n function pathIterator(iterator, x1, y1) {\n var tempP = { x: x1, y: y1 }, p, tmpLen = 0, perc;\n for (perc = 1; perc <= 100; perc += 1) {\n p = iterator(perc / 100);\n tmpLen += calcLineLength(tempP.x, tempP.y, p.x, p.y);\n tempP = p;\n }\n return tmpLen;\n }\n\n /**\n * Given a pathInfo, and a distance in pixels, find the percentage from 0 to 1\n * that correspond to that pixels run over the path.\n * The percentage will be then used to find the correct point on the canvas for the path.\n * @param {Array} segInfo fabricJS collection of information on a parsed path\n * @param {Number} distance from starting point, in pixels.\n * @return {Object} info object with x and y ( the point on canvas ) and angle, the tangent on that point;\n */\n function findPercentageForDistance(segInfo, distance) {\n var perc = 0, tmpLen = 0, iterator = segInfo.iterator, tempP = { x: segInfo.x, y: segInfo.y },\n p, nextLen, nextStep = 0.01, angleFinder = segInfo.angleFinder, lastPerc;\n // nextStep > 0.0001 covers 0.00015625 that 1/64th of 1/100\n // the path\n while (tmpLen < distance && nextStep > 0.0001) {\n p = iterator(perc);\n lastPerc = perc;\n nextLen = calcLineLength(tempP.x, tempP.y, p.x, p.y);\n // compare tmpLen each cycle with distance, decide next perc to test.\n if ((nextLen + tmpLen) > distance) {\n // we discard this step and we make smaller steps.\n perc -= nextStep;\n nextStep /= 2;\n }\n else {\n tempP = p;\n perc += nextStep;\n tmpLen += nextLen;\n }\n }\n p.angle = angleFinder(lastPerc);\n return p;\n }\n\n /**\n * Run over a parsed and simplifed path and extrac some informations.\n * informations are length of each command and starting point\n * @param {Array} path fabricJS parsed path commands\n * @return {Array} path commands informations\n */\n function getPathSegmentsInfo(path) {\n var totalLength = 0, len = path.length, current,\n //x2 and y2 are the coords of segment start\n //x1 and y1 are the coords of the current point\n x1 = 0, y1 = 0, x2 = 0, y2 = 0, info = [], iterator, tempInfo, angleFinder;\n for (var i = 0; i < len; i++) {\n current = path[i];\n tempInfo = {\n x: x1,\n y: y1,\n command: current[0],\n };\n switch (current[0]) { //first letter\n case 'M':\n tempInfo.length = 0;\n x2 = x1 = current[1];\n y2 = y1 = current[2];\n break;\n case 'L':\n tempInfo.length = calcLineLength(x1, y1, current[1], current[2]);\n x1 = current[1];\n y1 = current[2];\n break;\n case 'C':\n iterator = getPointOnCubicBezierIterator(\n x1,\n y1,\n current[1],\n current[2],\n current[3],\n current[4],\n current[5],\n current[6]\n );\n angleFinder = getTangentCubicIterator(\n x1,\n y1,\n current[1],\n current[2],\n current[3],\n current[4],\n current[5],\n current[6]\n );\n tempInfo.iterator = iterator;\n tempInfo.angleFinder = angleFinder;\n tempInfo.length = pathIterator(iterator, x1, y1);\n x1 = current[5];\n y1 = current[6];\n break;\n case 'Q':\n iterator = getPointOnQuadraticBezierIterator(\n x1,\n y1,\n current[1],\n current[2],\n current[3],\n current[4]\n );\n angleFinder = getTangentQuadraticIterator(\n x1,\n y1,\n current[1],\n current[2],\n current[3],\n current[4]\n );\n tempInfo.iterator = iterator;\n tempInfo.angleFinder = angleFinder;\n tempInfo.length = pathIterator(iterator, x1, y1);\n x1 = current[3];\n y1 = current[4];\n break;\n case 'Z':\n case 'z':\n // we add those in order to ease calculations later\n tempInfo.destX = x2;\n tempInfo.destY = y2;\n tempInfo.length = calcLineLength(x1, y1, x2, y2);\n x1 = x2;\n y1 = y2;\n break;\n }\n totalLength += tempInfo.length;\n info.push(tempInfo);\n }\n info.push({ length: totalLength, x: x1, y: y1 });\n return info;\n }\n\n function getPointOnPath(path, distance, infos) {\n if (!infos) {\n infos = getPathSegmentsInfo(path);\n }\n var i = 0;\n while ((distance - infos[i].length > 0) && i < (infos.length - 2)) {\n distance -= infos[i].length;\n i++;\n }\n // var distance = infos[infos.length - 1] * perc;\n var segInfo = infos[i], segPercent = distance / segInfo.length,\n command = segInfo.command, segment = path[i], info;\n\n switch (command) {\n case 'M':\n return { x: segInfo.x, y: segInfo.y, angle: 0 };\n case 'Z':\n case 'z':\n info = new fabric.Point(segInfo.x, segInfo.y).lerp(\n new fabric.Point(segInfo.destX, segInfo.destY),\n segPercent\n );\n info.angle = Math.atan2(segInfo.destY - segInfo.y, segInfo.destX - segInfo.x);\n return info;\n case 'L':\n info = new fabric.Point(segInfo.x, segInfo.y).lerp(\n new fabric.Point(segment[1], segment[2]),\n segPercent\n );\n info.angle = Math.atan2(segment[2] - segInfo.y, segment[1] - segInfo.x);\n return info;\n case 'C':\n return findPercentageForDistance(segInfo, distance);\n case 'Q':\n return findPercentageForDistance(segInfo, distance);\n }\n }\n\n /**\n *\n * @param {string} pathString\n * @return {(string|number)[][]} An array of SVG path commands\n * @example Usage\n * parsePath('M 3 4 Q 3 5 2 1 4 0 Q 9 12 2 1 4 0') === [\n * ['M', 3, 4],\n * ['Q', 3, 5, 2, 1, 4, 0],\n * ['Q', 9, 12, 2, 1, 4, 0],\n * ];\n *\n */\n function parsePath(pathString) {\n var result = [],\n coords = [],\n currentPath,\n parsed,\n re = fabric.rePathCommand,\n rNumber = '[-+]?(?:\\\\d*\\\\.\\\\d+|\\\\d+\\\\.?)(?:[eE][-+]?\\\\d+)?\\\\s*',\n rNumberCommaWsp = '(' + rNumber + ')' + fabric.commaWsp,\n rFlagCommaWsp = '([01])' + fabric.commaWsp + '?',\n rArcSeq = rNumberCommaWsp + '?' + rNumberCommaWsp + '?' + rNumberCommaWsp + rFlagCommaWsp + rFlagCommaWsp +\n rNumberCommaWsp + '?(' + rNumber + ')',\n regArcArgumentSequence = new RegExp(rArcSeq, 'g'),\n match,\n coordsStr,\n // one of commands (m,M,l,L,q,Q,c,C,etc.) followed by non-command characters (i.e. command values)\n path;\n if (!pathString || !pathString.match) {\n return result;\n }\n path = pathString.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi);\n\n for (var i = 0, coordsParsed, len = path.length; i < len; i++) {\n currentPath = path[i];\n\n coordsStr = currentPath.slice(1).trim();\n coords.length = 0;\n\n var command = currentPath.charAt(0);\n coordsParsed = [command];\n\n if (command.toLowerCase() === 'a') {\n // arcs have special flags that apparently don't require spaces so handle special\n for (var args; (args = regArcArgumentSequence.exec(coordsStr));) {\n for (var j = 1; j < args.length; j++) {\n coords.push(args[j]);\n }\n }\n }\n else {\n while ((match = re.exec(coordsStr))) {\n coords.push(match[0]);\n }\n }\n\n for (var j = 0, jlen = coords.length; j < jlen; j++) {\n parsed = parseFloat(coords[j]);\n if (!isNaN(parsed)) {\n coordsParsed.push(parsed);\n }\n }\n\n var commandLength = commandLengths[command.toLowerCase()],\n repeatedCommand = repeatedCommands[command] || command;\n\n if (coordsParsed.length - 1 > commandLength) {\n for (var k = 1, klen = coordsParsed.length; k < klen; k += commandLength) {\n result.push([command].concat(coordsParsed.slice(k, k + commandLength)));\n command = repeatedCommand;\n }\n }\n else {\n result.push(coordsParsed);\n }\n }\n\n return result;\n };\n\n /**\n *\n * Converts points to a smooth SVG path\n * @param {{ x: number,y: number }[]} points Array of points\n * @param {number} [correction] Apply a correction to the path (usually we use `width / 1000`). If value is undefined 0 is used as the correction value.\n * @return {(string|number)[][]} An array of SVG path commands\n */\n function getSmoothPathFromPoints(points, correction) {\n var path = [], i,\n p1 = new fabric.Point(points[0].x, points[0].y),\n p2 = new fabric.Point(points[1].x, points[1].y),\n len = points.length, multSignX = 1, multSignY = 0, manyPoints = len > 2;\n correction = correction || 0;\n\n if (manyPoints) {\n multSignX = points[2].x < p2.x ? -1 : points[2].x === p2.x ? 0 : 1;\n multSignY = points[2].y < p2.y ? -1 : points[2].y === p2.y ? 0 : 1;\n }\n path.push(['M', p1.x - multSignX * correction, p1.y - multSignY * correction]);\n for (i = 1; i < len; i++) {\n if (!p1.eq(p2)) {\n var midPoint = p1.midPointFrom(p2);\n // p1 is our bezier control point\n // midpoint is our endpoint\n // start point is p(i-1) value.\n path.push(['Q', p1.x, p1.y, midPoint.x, midPoint.y]);\n }\n p1 = points[i];\n if ((i + 1) < points.length) {\n p2 = points[i + 1];\n }\n }\n if (manyPoints) {\n multSignX = p1.x > points[i - 2].x ? 1 : p1.x === points[i - 2].x ? 0 : -1;\n multSignY = p1.y > points[i - 2].y ? 1 : p1.y === points[i - 2].y ? 0 : -1;\n }\n path.push(['L', p1.x + multSignX * correction, p1.y + multSignY * correction]);\n return path;\n }\n /**\n * Transform a path by transforming each segment.\n * it has to be a simplified path or it won't work.\n * WARNING: this depends from pathOffset for correct operation\n * @param {Array} path fabricJS parsed and simplified path commands\n * @param {Array} transform matrix that represent the transformation\n * @param {Object} [pathOffset] the fabric.Path pathOffset\n * @param {Number} pathOffset.x\n * @param {Number} pathOffset.y\n * @returns {Array} the transformed path\n */\n function transformPath(path, transform, pathOffset) {\n if (pathOffset) {\n transform = fabric.util.multiplyTransformMatrices(\n transform,\n [1, 0, 0, 1, -pathOffset.x, -pathOffset.y]\n );\n }\n return path.map(function(pathSegment) {\n var newSegment = pathSegment.slice(0), point = {};\n for (var i = 1; i < pathSegment.length - 1; i += 2) {\n point.x = pathSegment[i];\n point.y = pathSegment[i + 1];\n point = fabric.util.transformPoint(point, transform);\n newSegment[i] = point.x;\n newSegment[i + 1] = point.y;\n }\n return newSegment;\n });\n }\n\n /**\n * Join path commands to go back to svg format\n * @param {Array} pathData fabricJS parsed path commands\n * @return {String} joined path 'M 0 0 L 20 30'\n */\n fabric.util.joinPath = function(pathData) {\n return pathData.map(function (segment) { return segment.join(' '); }).join(' ');\n };\n fabric.util.parsePath = parsePath;\n fabric.util.makePathSimpler = makePathSimpler;\n fabric.util.getSmoothPathFromPoints = getSmoothPathFromPoints;\n fabric.util.getPathSegmentsInfo = getPathSegmentsInfo;\n fabric.util.getBoundsOfCurve = getBoundsOfCurve;\n fabric.util.getPointOnPath = getPointOnPath;\n fabric.util.transformPath = transformPath;\n})();\n\n\n(function() {\n\n var slice = Array.prototype.slice;\n\n /**\n * Invokes method on all items in a given array\n * @memberOf fabric.util.array\n * @param {Array} array Array to iterate over\n * @param {String} method Name of a method to invoke\n * @return {Array}\n */\n function invoke(array, method) {\n var args = slice.call(arguments, 2), result = [];\n for (var i = 0, len = array.length; i < len; i++) {\n result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);\n }\n return result;\n }\n\n /**\n * Finds maximum value in array (not necessarily \"first\" one)\n * @memberOf fabric.util.array\n * @param {Array} array Array to iterate over\n * @param {String} byProperty\n * @return {*}\n */\n function max(array, byProperty) {\n return find(array, byProperty, function(value1, value2) {\n return value1 >= value2;\n });\n }\n\n /**\n * Finds minimum value in array (not necessarily \"first\" one)\n * @memberOf fabric.util.array\n * @param {Array} array Array to iterate over\n * @param {String} byProperty\n * @return {*}\n */\n function min(array, byProperty) {\n return find(array, byProperty, function(value1, value2) {\n return value1 < value2;\n });\n }\n\n /**\n * @private\n */\n function fill(array, value) {\n var k = array.length;\n while (k--) {\n array[k] = value;\n }\n return array;\n }\n\n /**\n * @private\n */\n function find(array, byProperty, condition) {\n if (!array || array.length === 0) {\n return;\n }\n\n var i = array.length - 1,\n result = byProperty ? array[i][byProperty] : array[i];\n if (byProperty) {\n while (i--) {\n if (condition(array[i][byProperty], result)) {\n result = array[i][byProperty];\n }\n }\n }\n else {\n while (i--) {\n if (condition(array[i], result)) {\n result = array[i];\n }\n }\n }\n return result;\n }\n\n /**\n * @namespace fabric.util.array\n */\n fabric.util.array = {\n fill: fill,\n invoke: invoke,\n min: min,\n max: max\n };\n\n})();\n\n\n(function() {\n /**\n * Copies all enumerable properties of one js object to another\n * this does not and cannot compete with generic utils.\n * Does not clone or extend fabric.Object subclasses.\n * This is mostly for internal use and has extra handling for fabricJS objects\n * it skips the canvas and group properties in deep cloning.\n * @memberOf fabric.util.object\n * @param {Object} destination Where to copy to\n * @param {Object} source Where to copy from\n * @param {Boolean} [deep] Whether to extend nested objects\n * @return {Object}\n */\n\n function extend(destination, source, deep) {\n // JScript DontEnum bug is not taken care of\n // the deep clone is for internal use, is not meant to avoid\n // javascript traps or cloning html element or self referenced objects.\n if (deep) {\n if (!fabric.isLikelyNode && source instanceof Element) {\n // avoid cloning deep images, canvases,\n destination = source;\n }\n else if (source instanceof Array) {\n destination = [];\n for (var i = 0, len = source.length; i < len; i++) {\n destination[i] = extend({ }, source[i], deep);\n }\n }\n else if (source && typeof source === 'object') {\n for (var property in source) {\n if (property === 'canvas' || property === 'group') {\n // we do not want to clone this props at all.\n // we want to keep the keys in the copy\n destination[property] = null;\n }\n else if (source.hasOwnProperty(property)) {\n destination[property] = extend({ }, source[property], deep);\n }\n }\n }\n else {\n // this sounds odd for an extend but is ok for recursive use\n destination = source;\n }\n }\n else {\n for (var property in source) {\n destination[property] = source[property];\n }\n }\n return destination;\n }\n\n /**\n * Creates an empty object and copies all enumerable properties of another object to it\n * This method is mostly for internal use, and not intended for duplicating shapes in canvas. \n * @memberOf fabric.util.object\n * @param {Object} object Object to clone\n * @param {Boolean} [deep] Whether to clone nested objects\n * @return {Object}\n */\n\n //TODO: this function return an empty object if you try to clone null\n function clone(object, deep) {\n return extend({ }, object, deep);\n }\n\n /** @namespace fabric.util.object */\n fabric.util.object = {\n extend: extend,\n clone: clone\n };\n fabric.util.object.extend(fabric.util, fabric.Observable);\n})();\n\n\n(function() {\n\n /**\n * Camelizes a string\n * @memberOf fabric.util.string\n * @param {String} string String to camelize\n * @return {String} Camelized version of a string\n */\n function camelize(string) {\n return string.replace(/-+(.)?/g, function(match, character) {\n return character ? character.toUpperCase() : '';\n });\n }\n\n /**\n * Capitalizes a string\n * @memberOf fabric.util.string\n * @param {String} string String to capitalize\n * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized\n * and other letters stay untouched, if false first letter is capitalized\n * and other letters are converted to lowercase.\n * @return {String} Capitalized version of a string\n */\n function capitalize(string, firstLetterOnly) {\n return string.charAt(0).toUpperCase() +\n (firstLetterOnly ? string.slice(1) : string.slice(1).toLowerCase());\n }\n\n /**\n * Escapes XML in a string\n * @memberOf fabric.util.string\n * @param {String} string String to escape\n * @return {String} Escaped version of a string\n */\n function escapeXml(string) {\n return string.replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(//g, '>');\n }\n\n /**\n * Divide a string in the user perceived single units\n * @memberOf fabric.util.string\n * @param {String} textstring String to escape\n * @return {Array} array containing the graphemes\n */\n function graphemeSplit(textstring) {\n var i = 0, chr, graphemes = [];\n for (i = 0, chr; i < textstring.length; i++) {\n if ((chr = getWholeChar(textstring, i)) === false) {\n continue;\n }\n graphemes.push(chr);\n }\n return graphemes;\n }\n\n // taken from mdn in the charAt doc page.\n function getWholeChar(str, i) {\n var code = str.charCodeAt(i);\n\n if (isNaN(code)) {\n return ''; // Position not found\n }\n if (code < 0xD800 || code > 0xDFFF) {\n return str.charAt(i);\n }\n\n // High surrogate (could change last hex to 0xDB7F to treat high private\n // surrogates as single characters)\n if (0xD800 <= code && code <= 0xDBFF) {\n if (str.length <= (i + 1)) {\n throw 'High surrogate without following low surrogate';\n }\n var next = str.charCodeAt(i + 1);\n if (0xDC00 > next || next > 0xDFFF) {\n throw 'High surrogate without following low surrogate';\n }\n return str.charAt(i) + str.charAt(i + 1);\n }\n // Low surrogate (0xDC00 <= code && code <= 0xDFFF)\n if (i === 0) {\n throw 'Low surrogate without preceding high surrogate';\n }\n var prev = str.charCodeAt(i - 1);\n\n // (could change last hex to 0xDB7F to treat high private\n // surrogates as single characters)\n if (0xD800 > prev || prev > 0xDBFF) {\n throw 'Low surrogate without preceding high surrogate';\n }\n // We can pass over low surrogates now as the second component\n // in a pair which we have already processed\n return false;\n }\n\n\n /**\n * String utilities\n * @namespace fabric.util.string\n */\n fabric.util.string = {\n camelize: camelize,\n capitalize: capitalize,\n escapeXml: escapeXml,\n graphemeSplit: graphemeSplit\n };\n})();\n\n\n(function() {\n\n var slice = Array.prototype.slice, emptyFunction = function() { },\n\n IS_DONTENUM_BUGGY = (function() {\n for (var p in { toString: 1 }) {\n if (p === 'toString') {\n return false;\n }\n }\n return true;\n })(),\n\n /** @ignore */\n addMethods = function(klass, source, parent) {\n for (var property in source) {\n\n if (property in klass.prototype &&\n typeof klass.prototype[property] === 'function' &&\n (source[property] + '').indexOf('callSuper') > -1) {\n\n klass.prototype[property] = (function(property) {\n return function() {\n\n var superclass = this.constructor.superclass;\n this.constructor.superclass = parent;\n var returnValue = source[property].apply(this, arguments);\n this.constructor.superclass = superclass;\n\n if (property !== 'initialize') {\n return returnValue;\n }\n };\n })(property);\n }\n else {\n klass.prototype[property] = source[property];\n }\n\n if (IS_DONTENUM_BUGGY) {\n if (source.toString !== Object.prototype.toString) {\n klass.prototype.toString = source.toString;\n }\n if (source.valueOf !== Object.prototype.valueOf) {\n klass.prototype.valueOf = source.valueOf;\n }\n }\n }\n };\n\n function Subclass() { }\n\n function callSuper(methodName) {\n var parentMethod = null,\n _this = this;\n\n // climb prototype chain to find method not equal to callee's method\n while (_this.constructor.superclass) {\n var superClassMethod = _this.constructor.superclass.prototype[methodName];\n if (_this[methodName] !== superClassMethod) {\n parentMethod = superClassMethod;\n break;\n }\n // eslint-disable-next-line\n _this = _this.constructor.superclass.prototype;\n }\n\n if (!parentMethod) {\n return console.log('tried to callSuper ' + methodName + ', method not found in prototype chain', this);\n }\n\n return (arguments.length > 1)\n ? parentMethod.apply(this, slice.call(arguments, 1))\n : parentMethod.call(this);\n }\n\n /**\n * Helper for creation of \"classes\".\n * @memberOf fabric.util\n * @param {Function} [parent] optional \"Class\" to inherit from\n * @param {Object} [properties] Properties shared by all instances of this class\n * (be careful modifying objects defined here as this would affect all instances)\n */\n function createClass() {\n var parent = null,\n properties = slice.call(arguments, 0);\n\n if (typeof properties[0] === 'function') {\n parent = properties.shift();\n }\n function klass() {\n this.initialize.apply(this, arguments);\n }\n\n klass.superclass = parent;\n klass.subclasses = [];\n\n if (parent) {\n Subclass.prototype = parent.prototype;\n klass.prototype = new Subclass();\n parent.subclasses.push(klass);\n }\n for (var i = 0, length = properties.length; i < length; i++) {\n addMethods(klass, properties[i], parent);\n }\n if (!klass.prototype.initialize) {\n klass.prototype.initialize = emptyFunction;\n }\n klass.prototype.constructor = klass;\n klass.prototype.callSuper = callSuper;\n return klass;\n }\n\n fabric.util.createClass = createClass;\n})();\n\n\n(function () {\n // since ie11 can use addEventListener but they do not support options, i need to check\n var couldUseAttachEvent = !!fabric.document.createElement('div').attachEvent,\n touchEvents = ['touchstart', 'touchmove', 'touchend'];\n /**\n * Adds an event listener to an element\n * @function\n * @memberOf fabric.util\n * @param {HTMLElement} element\n * @param {String} eventName\n * @param {Function} handler\n */\n fabric.util.addListener = function(element, eventName, handler, options) {\n element && element.addEventListener(eventName, handler, couldUseAttachEvent ? false : options);\n };\n\n /**\n * Removes an event listener from an element\n * @function\n * @memberOf fabric.util\n * @param {HTMLElement} element\n * @param {String} eventName\n * @param {Function} handler\n */\n fabric.util.removeListener = function(element, eventName, handler, options) {\n element && element.removeEventListener(eventName, handler, couldUseAttachEvent ? false : options);\n };\n\n function getTouchInfo(event) {\n var touchProp = event.changedTouches;\n if (touchProp && touchProp[0]) {\n return touchProp[0];\n }\n return event;\n }\n\n fabric.util.getPointer = function(event) {\n var element = event.target,\n scroll = fabric.util.getScrollLeftTop(element),\n _evt = getTouchInfo(event);\n return {\n x: _evt.clientX + scroll.left,\n y: _evt.clientY + scroll.top\n };\n };\n\n fabric.util.isTouchEvent = function(event) {\n return touchEvents.indexOf(event.type) > -1 || event.pointerType === 'touch';\n };\n})();\n\n\n(function () {\n\n /**\n * Cross-browser wrapper for setting element's style\n * @memberOf fabric.util\n * @param {HTMLElement} element\n * @param {Object} styles\n * @return {HTMLElement} Element that was passed as a first argument\n */\n function setStyle(element, styles) {\n var elementStyle = element.style;\n if (!elementStyle) {\n return element;\n }\n if (typeof styles === 'string') {\n element.style.cssText += ';' + styles;\n return styles.indexOf('opacity') > -1\n ? setOpacity(element, styles.match(/opacity:\\s*(\\d?\\.?\\d*)/)[1])\n : element;\n }\n for (var property in styles) {\n if (property === 'opacity') {\n setOpacity(element, styles[property]);\n }\n else {\n var normalizedProperty = (property === 'float' || property === 'cssFloat')\n ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat')\n : property;\n elementStyle.setProperty(normalizedProperty, styles[property]);\n }\n }\n return element;\n }\n\n var parseEl = fabric.document.createElement('div'),\n supportsOpacity = typeof parseEl.style.opacity === 'string',\n supportsFilters = typeof parseEl.style.filter === 'string',\n reOpacity = /alpha\\s*\\(\\s*opacity\\s*=\\s*([^\\)]+)\\)/,\n\n /** @ignore */\n setOpacity = function (element) { return element; };\n\n if (supportsOpacity) {\n /** @ignore */\n setOpacity = function(element, value) {\n element.style.opacity = value;\n return element;\n };\n }\n else if (supportsFilters) {\n /** @ignore */\n setOpacity = function(element, value) {\n var es = element.style;\n if (element.currentStyle && !element.currentStyle.hasLayout) {\n es.zoom = 1;\n }\n if (reOpacity.test(es.filter)) {\n value = value >= 0.9999 ? '' : ('alpha(opacity=' + (value * 100) + ')');\n es.filter = es.filter.replace(reOpacity, value);\n }\n else {\n es.filter += ' alpha(opacity=' + (value * 100) + ')';\n }\n return element;\n };\n }\n\n fabric.util.setStyle = setStyle;\n\n})();\n\n\n(function() {\n\n var _slice = Array.prototype.slice;\n\n /**\n * Takes id and returns an element with that id (if one exists in a document)\n * @memberOf fabric.util\n * @param {String|HTMLElement} id\n * @return {HTMLElement|null}\n */\n function getById(id) {\n return typeof id === 'string' ? fabric.document.getElementById(id) : id;\n }\n\n var sliceCanConvertNodelists,\n /**\n * Converts an array-like object (e.g. arguments or NodeList) to an array\n * @memberOf fabric.util\n * @param {Object} arrayLike\n * @return {Array}\n */\n toArray = function(arrayLike) {\n return _slice.call(arrayLike, 0);\n };\n\n try {\n sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;\n }\n catch (err) { }\n\n if (!sliceCanConvertNodelists) {\n toArray = function(arrayLike) {\n var arr = new Array(arrayLike.length), i = arrayLike.length;\n while (i--) {\n arr[i] = arrayLike[i];\n }\n return arr;\n };\n }\n\n /**\n * Creates specified element with specified attributes\n * @memberOf fabric.util\n * @param {String} tagName Type of an element to create\n * @param {Object} [attributes] Attributes to set on an element\n * @return {HTMLElement} Newly created element\n */\n function makeElement(tagName, attributes) {\n var el = fabric.document.createElement(tagName);\n for (var prop in attributes) {\n if (prop === 'class') {\n el.className = attributes[prop];\n }\n else if (prop === 'for') {\n el.htmlFor = attributes[prop];\n }\n else {\n el.setAttribute(prop, attributes[prop]);\n }\n }\n return el;\n }\n\n /**\n * Adds class to an element\n * @memberOf fabric.util\n * @param {HTMLElement} element Element to add class to\n * @param {String} className Class to add to an element\n */\n function addClass(element, className) {\n if (element && (' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {\n element.className += (element.className ? ' ' : '') + className;\n }\n }\n\n /**\n * Wraps element with another element\n * @memberOf fabric.util\n * @param {HTMLElement} element Element to wrap\n * @param {HTMLElement|String} wrapper Element to wrap with\n * @param {Object} [attributes] Attributes to set on a wrapper\n * @return {HTMLElement} wrapper\n */\n function wrapElement(element, wrapper, attributes) {\n if (typeof wrapper === 'string') {\n wrapper = makeElement(wrapper, attributes);\n }\n if (element.parentNode) {\n element.parentNode.replaceChild(wrapper, element);\n }\n wrapper.appendChild(element);\n return wrapper;\n }\n\n /**\n * Returns element scroll offsets\n * @memberOf fabric.util\n * @param {HTMLElement} element Element to operate on\n * @return {Object} Object with left/top values\n */\n function getScrollLeftTop(element) {\n\n var left = 0,\n top = 0,\n docElement = fabric.document.documentElement,\n body = fabric.document.body || {\n scrollLeft: 0, scrollTop: 0\n };\n\n // While loop checks (and then sets element to) .parentNode OR .host\n // to account for ShadowDOM. We still want to traverse up out of ShadowDOM,\n // but the .parentNode of a root ShadowDOM node will always be null, instead\n // it should be accessed through .host. See http://stackoverflow.com/a/24765528/4383938\n while (element && (element.parentNode || element.host)) {\n\n // Set element to element parent, or 'host' in case of ShadowDOM\n element = element.parentNode || element.host;\n\n if (element === fabric.document) {\n left = body.scrollLeft || docElement.scrollLeft || 0;\n top = body.scrollTop || docElement.scrollTop || 0;\n }\n else {\n left += element.scrollLeft || 0;\n top += element.scrollTop || 0;\n }\n\n if (element.nodeType === 1 && element.style.position === 'fixed') {\n break;\n }\n }\n\n return { left: left, top: top };\n }\n\n /**\n * Returns offset for a given element\n * @function\n * @memberOf fabric.util\n * @param {HTMLElement} element Element to get offset for\n * @return {Object} Object with \"left\" and \"top\" properties\n */\n function getElementOffset(element) {\n var docElem,\n doc = element && element.ownerDocument,\n box = { left: 0, top: 0 },\n offset = { left: 0, top: 0 },\n scrollLeftTop,\n offsetAttributes = {\n borderLeftWidth: 'left',\n borderTopWidth: 'top',\n paddingLeft: 'left',\n paddingTop: 'top'\n };\n\n if (!doc) {\n return offset;\n }\n\n for (var attr in offsetAttributes) {\n offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;\n }\n\n docElem = doc.documentElement;\n if ( typeof element.getBoundingClientRect !== 'undefined' ) {\n box = element.getBoundingClientRect();\n }\n\n scrollLeftTop = getScrollLeftTop(element);\n\n return {\n left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,\n top: box.top + scrollLeftTop.top - (docElem.clientTop || 0) + offset.top\n };\n }\n\n /**\n * Returns style attribute value of a given element\n * @memberOf fabric.util\n * @param {HTMLElement} element Element to get style attribute for\n * @param {String} attr Style attribute to get for element\n * @return {String} Style attribute value of the given element.\n */\n var getElementStyle;\n if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {\n getElementStyle = function(element, attr) {\n var style = fabric.document.defaultView.getComputedStyle(element, null);\n return style ? style[attr] : undefined;\n };\n }\n else {\n getElementStyle = function(element, attr) {\n var value = element.style[attr];\n if (!value && element.currentStyle) {\n value = element.currentStyle[attr];\n }\n return value;\n };\n }\n\n (function () {\n var style = fabric.document.documentElement.style,\n selectProp = 'userSelect' in style\n ? 'userSelect'\n : 'MozUserSelect' in style\n ? 'MozUserSelect'\n : 'WebkitUserSelect' in style\n ? 'WebkitUserSelect'\n : 'KhtmlUserSelect' in style\n ? 'KhtmlUserSelect'\n : '';\n\n /**\n * Makes element unselectable\n * @memberOf fabric.util\n * @param {HTMLElement} element Element to make unselectable\n * @return {HTMLElement} Element that was passed in\n */\n function makeElementUnselectable(element) {\n if (typeof element.onselectstart !== 'undefined') {\n element.onselectstart = fabric.util.falseFunction;\n }\n if (selectProp) {\n element.style[selectProp] = 'none';\n }\n else if (typeof element.unselectable === 'string') {\n element.unselectable = 'on';\n }\n return element;\n }\n\n /**\n * Makes element selectable\n * @memberOf fabric.util\n * @param {HTMLElement} element Element to make selectable\n * @return {HTMLElement} Element that was passed in\n */\n function makeElementSelectable(element) {\n if (typeof element.onselectstart !== 'undefined') {\n element.onselectstart = null;\n }\n if (selectProp) {\n element.style[selectProp] = '';\n }\n else if (typeof element.unselectable === 'string') {\n element.unselectable = '';\n }\n return element;\n }\n\n fabric.util.makeElementUnselectable = makeElementUnselectable;\n fabric.util.makeElementSelectable = makeElementSelectable;\n })();\n\n function getNodeCanvas(element) {\n var impl = fabric.jsdomImplForWrapper(element);\n return impl._canvas || impl._image;\n };\n\n function cleanUpJsdomNode(element) {\n if (!fabric.isLikelyNode) {\n return;\n }\n var impl = fabric.jsdomImplForWrapper(element);\n if (impl) {\n impl._image = null;\n impl._canvas = null;\n // unsure if necessary\n impl._currentSrc = null;\n impl._attributes = null;\n impl._classList = null;\n }\n }\n\n function setImageSmoothing(ctx, value) {\n ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled || ctx.webkitImageSmoothingEnabled\n || ctx.mozImageSmoothingEnabled || ctx.msImageSmoothingEnabled || ctx.oImageSmoothingEnabled;\n ctx.imageSmoothingEnabled = value;\n }\n\n /**\n * setImageSmoothing sets the context imageSmoothingEnabled property.\n * Used by canvas and by ImageObject.\n * @memberOf fabric.util\n * @since 4.0.0\n * @param {HTMLRenderingContext2D} ctx to set on\n * @param {Boolean} value true or false\n */\n fabric.util.setImageSmoothing = setImageSmoothing;\n fabric.util.getById = getById;\n fabric.util.toArray = toArray;\n fabric.util.addClass = addClass;\n fabric.util.makeElement = makeElement;\n fabric.util.wrapElement = wrapElement;\n fabric.util.getScrollLeftTop = getScrollLeftTop;\n fabric.util.getElementOffset = getElementOffset;\n fabric.util.getNodeCanvas = getNodeCanvas;\n fabric.util.cleanUpJsdomNode = cleanUpJsdomNode;\n\n})();\n\n\n(function() {\n\n function addParamToUrl(url, param) {\n return url + (/\\?/.test(url) ? '&' : '?') + param;\n }\n\n function emptyFn() { }\n\n /**\n * Cross-browser abstraction for sending XMLHttpRequest\n * @memberOf fabric.util\n * @param {String} url URL to send XMLHttpRequest to\n * @param {Object} [options] Options object\n * @param {String} [options.method=\"GET\"]\n * @param {String} [options.parameters] parameters to append to url in GET or in body\n * @param {String} [options.body] body to send with POST or PUT request\n * @param {Function} options.onComplete Callback to invoke when request is completed\n * @return {XMLHttpRequest} request\n */\n function request(url, options) {\n options || (options = { });\n\n var method = options.method ? options.method.toUpperCase() : 'GET',\n onComplete = options.onComplete || function() { },\n xhr = new fabric.window.XMLHttpRequest(),\n body = options.body || options.parameters;\n\n /** @ignore */\n xhr.onreadystatechange = function() {\n if (xhr.readyState === 4) {\n onComplete(xhr);\n xhr.onreadystatechange = emptyFn;\n }\n };\n\n if (method === 'GET') {\n body = null;\n if (typeof options.parameters === 'string') {\n url = addParamToUrl(url, options.parameters);\n }\n }\n\n xhr.open(method, url, true);\n\n if (method === 'POST' || method === 'PUT') {\n xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n }\n\n xhr.send(body);\n return xhr;\n }\n\n fabric.util.request = request;\n})();\n\n\n/**\n * Wrapper around `console.log` (when available)\n * @param {*} [values] Values to log\n */\nfabric.log = console.log;\n\n/**\n * Wrapper around `console.warn` (when available)\n * @param {*} [values] Values to log as a warning\n */\nfabric.warn = console.warn;\n\n\n(function () {\n\n var extend = fabric.util.object.extend,\n clone = fabric.util.object.clone;\n\n /**\n * @typedef {Object} AnimationOptions\n * Animation of a value or list of values.\n * When using lists, think of something like this:\n * fabric.util.animate({\n * startValue: [1, 2, 3],\n * endValue: [2, 4, 6],\n * onChange: function([a, b, c]) {\n * canvas.zoomToPoint({x: b, y: c}, a)\n * canvas.renderAll()\n * }\n * });\n * @example\n * @property {Function} [onChange] Callback; invoked on every value change\n * @property {Function} [onComplete] Callback; invoked when value change is completed\n * @example\n * // Note: startValue, endValue, and byValue must match the type\n * var animationOptions = { startValue: 0, endValue: 1, byValue: 0.25 }\n * var animationOptions = { startValue: [0, 1], endValue: [1, 2], byValue: [0.25, 0.25] }\n * @property {number | number[]} [startValue=0] Starting value\n * @property {number | number[]} [endValue=100] Ending value\n * @property {number | number[]} [byValue=100] Value to modify the property by\n * @property {Function} [easing] Easing function\n * @property {Number} [duration=500] Duration of change (in ms)\n * @property {Function} [abort] Additional function with logic. If returns true, animation aborts.\n *\n * @typedef {() => void} CancelFunction\n *\n * @typedef {Object} AnimationCurrentState\n * @property {number | number[]} currentValue value in range [`startValue`, `endValue`]\n * @property {number} completionRate value in range [0, 1]\n * @property {number} durationRate value in range [0, 1]\n *\n * @typedef {(AnimationOptions & AnimationCurrentState & { cancel: CancelFunction }} AnimationContext\n */\n\n /**\n * Array holding all running animations\n * @memberof fabric\n * @type {AnimationContext[]}\n */\n var RUNNING_ANIMATIONS = [];\n fabric.util.object.extend(RUNNING_ANIMATIONS, {\n\n /**\n * cancel all running animations at the next requestAnimFrame\n * @returns {AnimationContext[]}\n */\n cancelAll: function () {\n var animations = this.splice(0);\n animations.forEach(function (animation) {\n animation.cancel();\n });\n return animations;\n },\n\n /**\n * cancel all running animations attached to canvas at the next requestAnimFrame\n * @param {fabric.Canvas} canvas\n * @returns {AnimationContext[]}\n */\n cancelByCanvas: function (canvas) {\n if (!canvas) {\n return [];\n }\n var cancelled = this.filter(function (animation) {\n return typeof animation.target === 'object' && animation.target.canvas === canvas;\n });\n cancelled.forEach(function (animation) {\n animation.cancel();\n });\n return cancelled;\n },\n\n /**\n * cancel all running animations for target at the next requestAnimFrame\n * @param {*} target\n * @returns {AnimationContext[]}\n */\n cancelByTarget: function (target) {\n var cancelled = this.findAnimationsByTarget(target);\n cancelled.forEach(function (animation) {\n animation.cancel();\n });\n return cancelled;\n },\n\n /**\n *\n * @param {CancelFunction} cancelFunc the function returned by animate\n * @returns {number}\n */\n findAnimationIndex: function (cancelFunc) {\n return this.indexOf(this.findAnimation(cancelFunc));\n },\n\n /**\n *\n * @param {CancelFunction} cancelFunc the function returned by animate\n * @returns {AnimationContext | undefined} animation's options object\n */\n findAnimation: function (cancelFunc) {\n return this.find(function (animation) {\n return animation.cancel === cancelFunc;\n });\n },\n\n /**\n *\n * @param {*} target the object that is assigned to the target property of the animation context\n * @returns {AnimationContext[]} array of animation options object associated with target\n */\n findAnimationsByTarget: function (target) {\n if (!target) {\n return [];\n }\n return this.filter(function (animation) {\n return animation.target === target;\n });\n }\n });\n\n function noop() {\n return false;\n }\n\n function defaultEasing(t, b, c, d) {\n return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;\n }\n\n /**\n * Changes value from one to another within certain period of time, invoking callbacks as value is being changed.\n * @memberOf fabric.util\n * @param {AnimationOptions} [options] Animation options\n * @example\n * // Note: startValue, endValue, and byValue must match the type\n * fabric.util.animate({ startValue: 0, endValue: 1, byValue: 0.25 })\n * fabric.util.animate({ startValue: [0, 1], endValue: [1, 2], byValue: [0.25, 0.25] })\n * @returns {CancelFunction} cancel function\n */\n function animate(options) {\n options || (options = {});\n var cancel = false,\n context,\n removeFromRegistry = function () {\n var index = fabric.runningAnimations.indexOf(context);\n return index > -1 && fabric.runningAnimations.splice(index, 1)[0];\n };\n\n context = extend(clone(options), {\n cancel: function () {\n cancel = true;\n return removeFromRegistry();\n },\n currentValue: 'startValue' in options ? options.startValue : 0,\n completionRate: 0,\n durationRate: 0\n });\n fabric.runningAnimations.push(context);\n\n requestAnimFrame(function(timestamp) {\n var start = timestamp || +new Date(),\n duration = options.duration || 500,\n finish = start + duration, time,\n onChange = options.onChange || noop,\n abort = options.abort || noop,\n onComplete = options.onComplete || noop,\n easing = options.easing || defaultEasing,\n isMany = 'startValue' in options ? options.startValue.length > 0 : false,\n startValue = 'startValue' in options ? options.startValue : 0,\n endValue = 'endValue' in options ? options.endValue : 100,\n byValue = options.byValue || (isMany ? startValue.map(function(value, i) {\n return endValue[i] - startValue[i];\n }) : endValue - startValue);\n\n options.onStart && options.onStart();\n\n (function tick(ticktime) {\n time = ticktime || +new Date();\n var currentTime = time > finish ? duration : (time - start),\n timePerc = currentTime / duration,\n current = isMany ? startValue.map(function(_value, i) {\n return easing(currentTime, startValue[i], byValue[i], duration);\n }) : easing(currentTime, startValue, byValue, duration),\n valuePerc = isMany ? Math.abs((current[0] - startValue[0]) / byValue[0])\n : Math.abs((current - startValue) / byValue);\n // update context\n context.currentValue = isMany ? current.slice() : current;\n context.completionRate = valuePerc;\n context.durationRate = timePerc;\n if (cancel) {\n return;\n }\n if (abort(current, valuePerc, timePerc)) {\n removeFromRegistry();\n return;\n }\n if (time > finish) {\n // update context\n context.currentValue = isMany ? endValue.slice() : endValue;\n context.completionRate = 1;\n context.durationRate = 1;\n // execute callbacks\n onChange(isMany ? endValue.slice() : endValue, 1, 1);\n onComplete(endValue, 1, 1);\n removeFromRegistry();\n return;\n }\n else {\n onChange(current, valuePerc, timePerc);\n requestAnimFrame(tick);\n }\n })(start);\n });\n\n return context.cancel;\n }\n\n var _requestAnimFrame = fabric.window.requestAnimationFrame ||\n fabric.window.webkitRequestAnimationFrame ||\n fabric.window.mozRequestAnimationFrame ||\n fabric.window.oRequestAnimationFrame ||\n fabric.window.msRequestAnimationFrame ||\n function(callback) {\n return fabric.window.setTimeout(callback, 1000 / 60);\n };\n\n var _cancelAnimFrame = fabric.window.cancelAnimationFrame || fabric.window.clearTimeout;\n\n /**\n * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/\n * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method\n * @memberOf fabric.util\n * @param {Function} callback Callback to invoke\n * @param {DOMElement} element optional Element to associate with animation\n */\n function requestAnimFrame() {\n return _requestAnimFrame.apply(fabric.window, arguments);\n }\n\n function cancelAnimFrame() {\n return _cancelAnimFrame.apply(fabric.window, arguments);\n }\n\n fabric.util.animate = animate;\n fabric.util.requestAnimFrame = requestAnimFrame;\n fabric.util.cancelAnimFrame = cancelAnimFrame;\n fabric.runningAnimations = RUNNING_ANIMATIONS;\n})();\n\n\n(function() {\n // Calculate an in-between color. Returns a \"rgba()\" string.\n // Credit: Edwin Martin \n // http://www.bitstorm.org/jquery/color-animation/jquery.animate-colors.js\n function calculateColor(begin, end, pos) {\n var color = 'rgba('\n + parseInt((begin[0] + pos * (end[0] - begin[0])), 10) + ','\n + parseInt((begin[1] + pos * (end[1] - begin[1])), 10) + ','\n + parseInt((begin[2] + pos * (end[2] - begin[2])), 10);\n\n color += ',' + (begin && end ? parseFloat(begin[3] + pos * (end[3] - begin[3])) : 1);\n color += ')';\n return color;\n }\n\n /**\n * Changes the color from one to another within certain period of time, invoking callbacks as value is being changed.\n * @memberOf fabric.util\n * @param {String} fromColor The starting color in hex or rgb(a) format.\n * @param {String} toColor The starting color in hex or rgb(a) format.\n * @param {Number} [duration] Duration of change (in ms).\n * @param {Object} [options] Animation options\n * @param {Function} [options.onChange] Callback; invoked on every value change\n * @param {Function} [options.onComplete] Callback; invoked when value change is completed\n * @param {Function} [options.colorEasing] Easing function. Note that this function only take two arguments (currentTime, duration). Thus the regular animation easing functions cannot be used.\n * @param {Function} [options.abort] Additional function with logic. If returns true, onComplete is called.\n * @returns {Function} abort function\n */\n function animateColor(fromColor, toColor, duration, options) {\n var startColor = new fabric.Color(fromColor).getSource(),\n endColor = new fabric.Color(toColor).getSource(),\n originalOnComplete = options.onComplete,\n originalOnChange = options.onChange;\n options = options || {};\n\n return fabric.util.animate(fabric.util.object.extend(options, {\n duration: duration || 500,\n startValue: startColor,\n endValue: endColor,\n byValue: endColor,\n easing: function (currentTime, startValue, byValue, duration) {\n var posValue = options.colorEasing\n ? options.colorEasing(currentTime, duration)\n : 1 - Math.cos(currentTime / duration * (Math.PI / 2));\n return calculateColor(startValue, byValue, posValue);\n },\n // has to take in account for color restoring;\n onComplete: function(current, valuePerc, timePerc) {\n if (originalOnComplete) {\n return originalOnComplete(\n calculateColor(endColor, endColor, 0),\n valuePerc,\n timePerc\n );\n }\n },\n onChange: function(current, valuePerc, timePerc) {\n if (originalOnChange) {\n if (Array.isArray(current)) {\n return originalOnChange(\n calculateColor(current, current, 0),\n valuePerc,\n timePerc\n );\n }\n originalOnChange(current, valuePerc, timePerc);\n }\n }\n }));\n }\n\n fabric.util.animateColor = animateColor;\n\n})();\n\n\n(function() {\n\n function normalize(a, c, p, s) {\n if (a < Math.abs(c)) {\n a = c;\n s = p / 4;\n }\n else {\n //handle the 0/0 case:\n if (c === 0 && a === 0) {\n s = p / (2 * Math.PI) * Math.asin(1);\n }\n else {\n s = p / (2 * Math.PI) * Math.asin(c / a);\n }\n }\n return { a: a, c: c, p: p, s: s };\n }\n\n function elastic(opts, t, d) {\n return opts.a *\n Math.pow(2, 10 * (t -= 1)) *\n Math.sin( (t * d - opts.s) * (2 * Math.PI) / opts.p );\n }\n\n /**\n * Cubic easing out\n * @memberOf fabric.util.ease\n */\n function easeOutCubic(t, b, c, d) {\n return c * ((t = t / d - 1) * t * t + 1) + b;\n }\n\n /**\n * Cubic easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutCubic(t, b, c, d) {\n t /= d / 2;\n if (t < 1) {\n return c / 2 * t * t * t + b;\n }\n return c / 2 * ((t -= 2) * t * t + 2) + b;\n }\n\n /**\n * Quartic easing in\n * @memberOf fabric.util.ease\n */\n function easeInQuart(t, b, c, d) {\n return c * (t /= d) * t * t * t + b;\n }\n\n /**\n * Quartic easing out\n * @memberOf fabric.util.ease\n */\n function easeOutQuart(t, b, c, d) {\n return -c * ((t = t / d - 1) * t * t * t - 1) + b;\n }\n\n /**\n * Quartic easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutQuart(t, b, c, d) {\n t /= d / 2;\n if (t < 1) {\n return c / 2 * t * t * t * t + b;\n }\n return -c / 2 * ((t -= 2) * t * t * t - 2) + b;\n }\n\n /**\n * Quintic easing in\n * @memberOf fabric.util.ease\n */\n function easeInQuint(t, b, c, d) {\n return c * (t /= d) * t * t * t * t + b;\n }\n\n /**\n * Quintic easing out\n * @memberOf fabric.util.ease\n */\n function easeOutQuint(t, b, c, d) {\n return c * ((t = t / d - 1) * t * t * t * t + 1) + b;\n }\n\n /**\n * Quintic easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutQuint(t, b, c, d) {\n t /= d / 2;\n if (t < 1) {\n return c / 2 * t * t * t * t * t + b;\n }\n return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;\n }\n\n /**\n * Sinusoidal easing in\n * @memberOf fabric.util.ease\n */\n function easeInSine(t, b, c, d) {\n return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;\n }\n\n /**\n * Sinusoidal easing out\n * @memberOf fabric.util.ease\n */\n function easeOutSine(t, b, c, d) {\n return c * Math.sin(t / d * (Math.PI / 2)) + b;\n }\n\n /**\n * Sinusoidal easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutSine(t, b, c, d) {\n return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;\n }\n\n /**\n * Exponential easing in\n * @memberOf fabric.util.ease\n */\n function easeInExpo(t, b, c, d) {\n return (t === 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;\n }\n\n /**\n * Exponential easing out\n * @memberOf fabric.util.ease\n */\n function easeOutExpo(t, b, c, d) {\n return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;\n }\n\n /**\n * Exponential easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutExpo(t, b, c, d) {\n if (t === 0) {\n return b;\n }\n if (t === d) {\n return b + c;\n }\n t /= d / 2;\n if (t < 1) {\n return c / 2 * Math.pow(2, 10 * (t - 1)) + b;\n }\n return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;\n }\n\n /**\n * Circular easing in\n * @memberOf fabric.util.ease\n */\n function easeInCirc(t, b, c, d) {\n return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;\n }\n\n /**\n * Circular easing out\n * @memberOf fabric.util.ease\n */\n function easeOutCirc(t, b, c, d) {\n return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;\n }\n\n /**\n * Circular easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutCirc(t, b, c, d) {\n t /= d / 2;\n if (t < 1) {\n return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;\n }\n return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;\n }\n\n /**\n * Elastic easing in\n * @memberOf fabric.util.ease\n */\n function easeInElastic(t, b, c, d) {\n var s = 1.70158, p = 0, a = c;\n if (t === 0) {\n return b;\n }\n t /= d;\n if (t === 1) {\n return b + c;\n }\n if (!p) {\n p = d * 0.3;\n }\n var opts = normalize(a, c, p, s);\n return -elastic(opts, t, d) + b;\n }\n\n /**\n * Elastic easing out\n * @memberOf fabric.util.ease\n */\n function easeOutElastic(t, b, c, d) {\n var s = 1.70158, p = 0, a = c;\n if (t === 0) {\n return b;\n }\n t /= d;\n if (t === 1) {\n return b + c;\n }\n if (!p) {\n p = d * 0.3;\n }\n var opts = normalize(a, c, p, s);\n return opts.a * Math.pow(2, -10 * t) * Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) + opts.c + b;\n }\n\n /**\n * Elastic easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutElastic(t, b, c, d) {\n var s = 1.70158, p = 0, a = c;\n if (t === 0) {\n return b;\n }\n t /= d / 2;\n if (t === 2) {\n return b + c;\n }\n if (!p) {\n p = d * (0.3 * 1.5);\n }\n var opts = normalize(a, c, p, s);\n if (t < 1) {\n return -0.5 * elastic(opts, t, d) + b;\n }\n return opts.a * Math.pow(2, -10 * (t -= 1)) *\n Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) * 0.5 + opts.c + b;\n }\n\n /**\n * Backwards easing in\n * @memberOf fabric.util.ease\n */\n function easeInBack(t, b, c, d, s) {\n if (s === undefined) {\n s = 1.70158;\n }\n return c * (t /= d) * t * ((s + 1) * t - s) + b;\n }\n\n /**\n * Backwards easing out\n * @memberOf fabric.util.ease\n */\n function easeOutBack(t, b, c, d, s) {\n if (s === undefined) {\n s = 1.70158;\n }\n return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;\n }\n\n /**\n * Backwards easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutBack(t, b, c, d, s) {\n if (s === undefined) {\n s = 1.70158;\n }\n t /= d / 2;\n if (t < 1) {\n return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;\n }\n return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;\n }\n\n /**\n * Bouncing easing in\n * @memberOf fabric.util.ease\n */\n function easeInBounce(t, b, c, d) {\n return c - easeOutBounce (d - t, 0, c, d) + b;\n }\n\n /**\n * Bouncing easing out\n * @memberOf fabric.util.ease\n */\n function easeOutBounce(t, b, c, d) {\n if ((t /= d) < (1 / 2.75)) {\n return c * (7.5625 * t * t) + b;\n }\n else if (t < (2 / 2.75)) {\n return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;\n }\n else if (t < (2.5 / 2.75)) {\n return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;\n }\n else {\n return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;\n }\n }\n\n /**\n * Bouncing easing in and out\n * @memberOf fabric.util.ease\n */\n function easeInOutBounce(t, b, c, d) {\n if (t < d / 2) {\n return easeInBounce (t * 2, 0, c, d) * 0.5 + b;\n }\n return easeOutBounce(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;\n }\n\n /**\n * Easing functions\n * See Easing Equations by Robert Penner\n * @namespace fabric.util.ease\n */\n fabric.util.ease = {\n\n /**\n * Quadratic easing in\n * @memberOf fabric.util.ease\n */\n easeInQuad: function(t, b, c, d) {\n return c * (t /= d) * t + b;\n },\n\n /**\n * Quadratic easing out\n * @memberOf fabric.util.ease\n */\n easeOutQuad: function(t, b, c, d) {\n return -c * (t /= d) * (t - 2) + b;\n },\n\n /**\n * Quadratic easing in and out\n * @memberOf fabric.util.ease\n */\n easeInOutQuad: function(t, b, c, d) {\n t /= (d / 2);\n if (t < 1) {\n return c / 2 * t * t + b;\n }\n return -c / 2 * ((--t) * (t - 2) - 1) + b;\n },\n\n /**\n * Cubic easing in\n * @memberOf fabric.util.ease\n */\n easeInCubic: function(t, b, c, d) {\n return c * (t /= d) * t * t + b;\n },\n\n easeOutCubic: easeOutCubic,\n easeInOutCubic: easeInOutCubic,\n easeInQuart: easeInQuart,\n easeOutQuart: easeOutQuart,\n easeInOutQuart: easeInOutQuart,\n easeInQuint: easeInQuint,\n easeOutQuint: easeOutQuint,\n easeInOutQuint: easeInOutQuint,\n easeInSine: easeInSine,\n easeOutSine: easeOutSine,\n easeInOutSine: easeInOutSine,\n easeInExpo: easeInExpo,\n easeOutExpo: easeOutExpo,\n easeInOutExpo: easeInOutExpo,\n easeInCirc: easeInCirc,\n easeOutCirc: easeOutCirc,\n easeInOutCirc: easeInOutCirc,\n easeInElastic: easeInElastic,\n easeOutElastic: easeOutElastic,\n easeInOutElastic: easeInOutElastic,\n easeInBack: easeInBack,\n easeOutBack: easeOutBack,\n easeInOutBack: easeInOutBack,\n easeInBounce: easeInBounce,\n easeOutBounce: easeOutBounce,\n easeInOutBounce: easeInOutBounce\n };\n\n})();\n\n\n(function(global) {\n\n 'use strict';\n\n /**\n * @name fabric\n * @namespace\n */\n\n var fabric = global.fabric || (global.fabric = { }),\n extend = fabric.util.object.extend,\n clone = fabric.util.object.clone,\n toFixed = fabric.util.toFixed,\n parseUnit = fabric.util.parseUnit,\n multiplyTransformMatrices = fabric.util.multiplyTransformMatrices,\n\n svgValidTagNames = ['path', 'circle', 'polygon', 'polyline', 'ellipse', 'rect', 'line',\n 'image', 'text'],\n svgViewBoxElements = ['symbol', 'image', 'marker', 'pattern', 'view', 'svg'],\n svgInvalidAncestors = ['pattern', 'defs', 'symbol', 'metadata', 'clipPath', 'mask', 'desc'],\n svgValidParents = ['symbol', 'g', 'a', 'svg', 'clipPath', 'defs'],\n\n attributesMap = {\n cx: 'left',\n x: 'left',\n r: 'radius',\n cy: 'top',\n y: 'top',\n display: 'visible',\n visibility: 'visible',\n transform: 'transformMatrix',\n 'fill-opacity': 'fillOpacity',\n 'fill-rule': 'fillRule',\n 'font-family': 'fontFamily',\n 'font-size': 'fontSize',\n 'font-style': 'fontStyle',\n 'font-weight': 'fontWeight',\n 'letter-spacing': 'charSpacing',\n 'paint-order': 'paintFirst',\n 'stroke-dasharray': 'strokeDashArray',\n 'stroke-dashoffset': 'strokeDashOffset',\n 'stroke-linecap': 'strokeLineCap',\n 'stroke-linejoin': 'strokeLineJoin',\n 'stroke-miterlimit': 'strokeMiterLimit',\n 'stroke-opacity': 'strokeOpacity',\n 'stroke-width': 'strokeWidth',\n 'text-decoration': 'textDecoration',\n 'text-anchor': 'textAnchor',\n opacity: 'opacity',\n 'clip-path': 'clipPath',\n 'clip-rule': 'clipRule',\n 'vector-effect': 'strokeUniform',\n 'image-rendering': 'imageSmoothing',\n },\n\n colorAttributes = {\n stroke: 'strokeOpacity',\n fill: 'fillOpacity'\n },\n\n fSize = 'font-size', cPath = 'clip-path';\n\n fabric.svgValidTagNamesRegEx = getSvgRegex(svgValidTagNames);\n fabric.svgViewBoxElementsRegEx = getSvgRegex(svgViewBoxElements);\n fabric.svgInvalidAncestorsRegEx = getSvgRegex(svgInvalidAncestors);\n fabric.svgValidParentsRegEx = getSvgRegex(svgValidParents);\n\n fabric.cssRules = { };\n fabric.gradientDefs = { };\n fabric.clipPaths = { };\n\n function normalizeAttr(attr) {\n // transform attribute names\n if (attr in attributesMap) {\n return attributesMap[attr];\n }\n return attr;\n }\n\n function normalizeValue(attr, value, parentAttributes, fontSize) {\n var isArray = Array.isArray(value), parsed;\n\n if ((attr === 'fill' || attr === 'stroke') && value === 'none') {\n value = '';\n }\n else if (attr === 'strokeUniform') {\n return (value === 'non-scaling-stroke');\n }\n else if (attr === 'strokeDashArray') {\n if (value === 'none') {\n value = null;\n }\n else {\n value = value.replace(/,/g, ' ').split(/\\s+/).map(parseFloat);\n }\n }\n else if (attr === 'transformMatrix') {\n if (parentAttributes && parentAttributes.transformMatrix) {\n value = multiplyTransformMatrices(\n parentAttributes.transformMatrix, fabric.parseTransformAttribute(value));\n }\n else {\n value = fabric.parseTransformAttribute(value);\n }\n }\n else if (attr === 'visible') {\n value = value !== 'none' && value !== 'hidden';\n // display=none on parent element always takes precedence over child element\n if (parentAttributes && parentAttributes.visible === false) {\n value = false;\n }\n }\n else if (attr === 'opacity') {\n value = parseFloat(value);\n if (parentAttributes && typeof parentAttributes.opacity !== 'undefined') {\n value *= parentAttributes.opacity;\n }\n }\n else if (attr === 'textAnchor' /* text-anchor */) {\n value = value === 'start' ? 'left' : value === 'end' ? 'right' : 'center';\n }\n else if (attr === 'charSpacing') {\n // parseUnit returns px and we convert it to em\n parsed = parseUnit(value, fontSize) / fontSize * 1000;\n }\n else if (attr === 'paintFirst') {\n var fillIndex = value.indexOf('fill');\n var strokeIndex = value.indexOf('stroke');\n var value = 'fill';\n if (fillIndex > -1 && strokeIndex > -1 && strokeIndex < fillIndex) {\n value = 'stroke';\n }\n else if (fillIndex === -1 && strokeIndex > -1) {\n value = 'stroke';\n }\n }\n else if (attr === 'href' || attr === 'xlink:href' || attr === 'font') {\n return value;\n }\n else if (attr === 'imageSmoothing') {\n return (value === 'optimizeQuality');\n }\n else {\n parsed = isArray ? value.map(parseUnit) : parseUnit(value, fontSize);\n }\n\n return (!isArray && isNaN(parsed) ? value : parsed);\n }\n\n /**\n * @private\n */\n function getSvgRegex(arr) {\n return new RegExp('^(' + arr.join('|') + ')\\\\b', 'i');\n }\n\n /**\n * @private\n * @param {Object} attributes Array of attributes to parse\n */\n function _setStrokeFillOpacity(attributes) {\n for (var attr in colorAttributes) {\n\n if (typeof attributes[colorAttributes[attr]] === 'undefined' || attributes[attr] === '') {\n continue;\n }\n\n if (typeof attributes[attr] === 'undefined') {\n if (!fabric.Object.prototype[attr]) {\n continue;\n }\n attributes[attr] = fabric.Object.prototype[attr];\n }\n\n if (attributes[attr].indexOf('url(') === 0) {\n continue;\n }\n\n var color = new fabric.Color(attributes[attr]);\n attributes[attr] = color.setAlpha(toFixed(color.getAlpha() * attributes[colorAttributes[attr]], 2)).toRgba();\n }\n return attributes;\n }\n\n /**\n * @private\n */\n function _getMultipleNodes(doc, nodeNames) {\n var nodeName, nodeArray = [], nodeList, i, len;\n for (i = 0, len = nodeNames.length; i < len; i++) {\n nodeName = nodeNames[i];\n nodeList = doc.getElementsByTagName(nodeName);\n nodeArray = nodeArray.concat(Array.prototype.slice.call(nodeList));\n }\n return nodeArray;\n }\n\n /**\n * Parses \"transform\" attribute, returning an array of values\n * @static\n * @function\n * @memberOf fabric\n * @param {String} attributeValue String containing attribute value\n * @return {Array} Array of 6 elements representing transformation matrix\n */\n fabric.parseTransformAttribute = (function() {\n function rotateMatrix(matrix, args) {\n var cos = fabric.util.cos(args[0]), sin = fabric.util.sin(args[0]),\n x = 0, y = 0;\n if (args.length === 3) {\n x = args[1];\n y = args[2];\n }\n\n matrix[0] = cos;\n matrix[1] = sin;\n matrix[2] = -sin;\n matrix[3] = cos;\n matrix[4] = x - (cos * x - sin * y);\n matrix[5] = y - (sin * x + cos * y);\n }\n\n function scaleMatrix(matrix, args) {\n var multiplierX = args[0],\n multiplierY = (args.length === 2) ? args[1] : args[0];\n\n matrix[0] = multiplierX;\n matrix[3] = multiplierY;\n }\n\n function skewMatrix(matrix, args, pos) {\n matrix[pos] = Math.tan(fabric.util.degreesToRadians(args[0]));\n }\n\n function translateMatrix(matrix, args) {\n matrix[4] = args[0];\n if (args.length === 2) {\n matrix[5] = args[1];\n }\n }\n\n // identity matrix\n var iMatrix = fabric.iMatrix,\n\n // == begin transform regexp\n number = fabric.reNum,\n\n commaWsp = fabric.commaWsp,\n\n skewX = '(?:(skewX)\\\\s*\\\\(\\\\s*(' + number + ')\\\\s*\\\\))',\n\n skewY = '(?:(skewY)\\\\s*\\\\(\\\\s*(' + number + ')\\\\s*\\\\))',\n\n rotate = '(?:(rotate)\\\\s*\\\\(\\\\s*(' + number + ')(?:' +\n commaWsp + '(' + number + ')' +\n commaWsp + '(' + number + '))?\\\\s*\\\\))',\n\n scale = '(?:(scale)\\\\s*\\\\(\\\\s*(' + number + ')(?:' +\n commaWsp + '(' + number + '))?\\\\s*\\\\))',\n\n translate = '(?:(translate)\\\\s*\\\\(\\\\s*(' + number + ')(?:' +\n commaWsp + '(' + number + '))?\\\\s*\\\\))',\n\n matrix = '(?:(matrix)\\\\s*\\\\(\\\\s*' +\n '(' + number + ')' + commaWsp +\n '(' + number + ')' + commaWsp +\n '(' + number + ')' + commaWsp +\n '(' + number + ')' + commaWsp +\n '(' + number + ')' + commaWsp +\n '(' + number + ')' +\n '\\\\s*\\\\))',\n\n transform = '(?:' +\n matrix + '|' +\n translate + '|' +\n scale + '|' +\n rotate + '|' +\n skewX + '|' +\n skewY +\n ')',\n\n transforms = '(?:' + transform + '(?:' + commaWsp + '*' + transform + ')*' + ')',\n\n transformList = '^\\\\s*(?:' + transforms + '?)\\\\s*$',\n\n // http://www.w3.org/TR/SVG/coords.html#TransformAttribute\n reTransformList = new RegExp(transformList),\n // == end transform regexp\n\n reTransform = new RegExp(transform, 'g');\n\n return function(attributeValue) {\n\n // start with identity matrix\n var matrix = iMatrix.concat(),\n matrices = [];\n\n // return if no argument was given or\n // an argument does not match transform attribute regexp\n if (!attributeValue || (attributeValue && !reTransformList.test(attributeValue))) {\n return matrix;\n }\n\n attributeValue.replace(reTransform, function(match) {\n\n var m = new RegExp(transform).exec(match).filter(function (match) {\n // match !== '' && match != null\n return (!!match);\n }),\n operation = m[1],\n args = m.slice(2).map(parseFloat);\n\n switch (operation) {\n case 'translate':\n translateMatrix(matrix, args);\n break;\n case 'rotate':\n args[0] = fabric.util.degreesToRadians(args[0]);\n rotateMatrix(matrix, args);\n break;\n case 'scale':\n scaleMatrix(matrix, args);\n break;\n case 'skewX':\n skewMatrix(matrix, args, 2);\n break;\n case 'skewY':\n skewMatrix(matrix, args, 1);\n break;\n case 'matrix':\n matrix = args;\n break;\n }\n\n // snapshot current matrix into matrices array\n matrices.push(matrix.concat());\n // reset\n matrix = iMatrix.concat();\n });\n\n var combinedMatrix = matrices[0];\n while (matrices.length > 1) {\n matrices.shift();\n combinedMatrix = fabric.util.multiplyTransformMatrices(combinedMatrix, matrices[0]);\n }\n return combinedMatrix;\n };\n })();\n\n /**\n * @private\n */\n function parseStyleString(style, oStyle) {\n var attr, value;\n style.replace(/;\\s*$/, '').split(';').forEach(function (chunk) {\n var pair = chunk.split(':');\n\n attr = pair[0].trim().toLowerCase();\n value = pair[1].trim();\n\n oStyle[attr] = value;\n });\n }\n\n /**\n * @private\n */\n function parseStyleObject(style, oStyle) {\n var attr, value;\n for (var prop in style) {\n if (typeof style[prop] === 'undefined') {\n continue;\n }\n\n attr = prop.toLowerCase();\n value = style[prop];\n\n oStyle[attr] = value;\n }\n }\n\n /**\n * @private\n */\n function getGlobalStylesForElement(element, svgUid) {\n var styles = { };\n for (var rule in fabric.cssRules[svgUid]) {\n if (elementMatchesRule(element, rule.split(' '))) {\n for (var property in fabric.cssRules[svgUid][rule]) {\n styles[property] = fabric.cssRules[svgUid][rule][property];\n }\n }\n }\n return styles;\n }\n\n /**\n * @private\n */\n function elementMatchesRule(element, selectors) {\n var firstMatching, parentMatching = true;\n //start from rightmost selector.\n firstMatching = selectorMatches(element, selectors.pop());\n if (firstMatching && selectors.length) {\n parentMatching = doesSomeParentMatch(element, selectors);\n }\n return firstMatching && parentMatching && (selectors.length === 0);\n }\n\n function doesSomeParentMatch(element, selectors) {\n var selector, parentMatching = true;\n while (element.parentNode && element.parentNode.nodeType === 1 && selectors.length) {\n if (parentMatching) {\n selector = selectors.pop();\n }\n element = element.parentNode;\n parentMatching = selectorMatches(element, selector);\n }\n return selectors.length === 0;\n }\n\n /**\n * @private\n */\n function selectorMatches(element, selector) {\n var nodeName = element.nodeName,\n classNames = element.getAttribute('class'),\n id = element.getAttribute('id'), matcher, i;\n // i check if a selector matches slicing away part from it.\n // if i get empty string i should match\n matcher = new RegExp('^' + nodeName, 'i');\n selector = selector.replace(matcher, '');\n if (id && selector.length) {\n matcher = new RegExp('#' + id + '(?![a-zA-Z\\\\-]+)', 'i');\n selector = selector.replace(matcher, '');\n }\n if (classNames && selector.length) {\n classNames = classNames.split(' ');\n for (i = classNames.length; i--;) {\n matcher = new RegExp('\\\\.' + classNames[i] + '(?![a-zA-Z\\\\-]+)', 'i');\n selector = selector.replace(matcher, '');\n }\n }\n return selector.length === 0;\n }\n\n /**\n * @private\n * to support IE8 missing getElementById on SVGdocument and on node xmlDOM\n */\n function elementById(doc, id) {\n var el;\n doc.getElementById && (el = doc.getElementById(id));\n if (el) {\n return el;\n }\n var node, i, len, nodelist = doc.getElementsByTagName('*');\n for (i = 0, len = nodelist.length; i < len; i++) {\n node = nodelist[i];\n if (id === node.getAttribute('id')) {\n return node;\n }\n }\n }\n\n /**\n * @private\n */\n function parseUseDirectives(doc) {\n var nodelist = _getMultipleNodes(doc, ['use', 'svg:use']), i = 0;\n while (nodelist.length && i < nodelist.length) {\n var el = nodelist[i],\n xlinkAttribute = el.getAttribute('xlink:href') || el.getAttribute('href');\n\n if (xlinkAttribute === null) {\n return;\n }\n\n var xlink = xlinkAttribute.slice(1),\n x = el.getAttribute('x') || 0,\n y = el.getAttribute('y') || 0,\n el2 = elementById(doc, xlink).cloneNode(true),\n currentTrans = (el2.getAttribute('transform') || '') + ' translate(' + x + ', ' + y + ')',\n parentNode,\n oldLength = nodelist.length, attr,\n j,\n attrs,\n len,\n namespace = fabric.svgNS;\n\n applyViewboxTransform(el2);\n if (/^svg$/i.test(el2.nodeName)) {\n var el3 = el2.ownerDocument.createElementNS(namespace, 'g');\n for (j = 0, attrs = el2.attributes, len = attrs.length; j < len; j++) {\n attr = attrs.item(j);\n el3.setAttributeNS(namespace, attr.nodeName, attr.nodeValue);\n }\n // el2.firstChild != null\n while (el2.firstChild) {\n el3.appendChild(el2.firstChild);\n }\n el2 = el3;\n }\n\n for (j = 0, attrs = el.attributes, len = attrs.length; j < len; j++) {\n attr = attrs.item(j);\n if (attr.nodeName === 'x' || attr.nodeName === 'y' ||\n attr.nodeName === 'xlink:href' || attr.nodeName === 'href') {\n continue;\n }\n\n if (attr.nodeName === 'transform') {\n currentTrans = attr.nodeValue + ' ' + currentTrans;\n }\n else {\n el2.setAttribute(attr.nodeName, attr.nodeValue);\n }\n }\n\n el2.setAttribute('transform', currentTrans);\n el2.setAttribute('instantiated_by_use', '1');\n el2.removeAttribute('id');\n parentNode = el.parentNode;\n parentNode.replaceChild(el2, el);\n // some browsers do not shorten nodelist after replaceChild (IE8)\n if (nodelist.length === oldLength) {\n i++;\n }\n }\n }\n\n // http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute\n // matches, e.g.: +14.56e-12, etc.\n var reViewBoxAttrValue = new RegExp(\n '^' +\n '\\\\s*(' + fabric.reNum + '+)\\\\s*,?' +\n '\\\\s*(' + fabric.reNum + '+)\\\\s*,?' +\n '\\\\s*(' + fabric.reNum + '+)\\\\s*,?' +\n '\\\\s*(' + fabric.reNum + '+)\\\\s*' +\n '$'\n );\n\n /**\n * Add a element that envelop all child elements and makes the viewbox transformMatrix descend on all elements\n */\n function applyViewboxTransform(element) {\n if (!fabric.svgViewBoxElementsRegEx.test(element.nodeName)) {\n return {};\n }\n var viewBoxAttr = element.getAttribute('viewBox'),\n scaleX = 1,\n scaleY = 1,\n minX = 0,\n minY = 0,\n viewBoxWidth, viewBoxHeight, matrix, el,\n widthAttr = element.getAttribute('width'),\n heightAttr = element.getAttribute('height'),\n x = element.getAttribute('x') || 0,\n y = element.getAttribute('y') || 0,\n preserveAspectRatio = element.getAttribute('preserveAspectRatio') || '',\n missingViewBox = (!viewBoxAttr || !(viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))),\n missingDimAttr = (!widthAttr || !heightAttr || widthAttr === '100%' || heightAttr === '100%'),\n toBeParsed = missingViewBox && missingDimAttr,\n parsedDim = { }, translateMatrix = '', widthDiff = 0, heightDiff = 0;\n\n parsedDim.width = 0;\n parsedDim.height = 0;\n parsedDim.toBeParsed = toBeParsed;\n\n if (missingViewBox) {\n if (((x || y) && element.parentNode && element.parentNode.nodeName !== '#document')) {\n translateMatrix = ' translate(' + parseUnit(x) + ' ' + parseUnit(y) + ') ';\n matrix = (element.getAttribute('transform') || '') + translateMatrix;\n element.setAttribute('transform', matrix);\n element.removeAttribute('x');\n element.removeAttribute('y');\n }\n }\n\n if (toBeParsed) {\n return parsedDim;\n }\n\n if (missingViewBox) {\n parsedDim.width = parseUnit(widthAttr);\n parsedDim.height = parseUnit(heightAttr);\n // set a transform for elements that have x y and are inner(only) SVGs\n return parsedDim;\n }\n minX = -parseFloat(viewBoxAttr[1]);\n minY = -parseFloat(viewBoxAttr[2]);\n viewBoxWidth = parseFloat(viewBoxAttr[3]);\n viewBoxHeight = parseFloat(viewBoxAttr[4]);\n parsedDim.minX = minX;\n parsedDim.minY = minY;\n parsedDim.viewBoxWidth = viewBoxWidth;\n parsedDim.viewBoxHeight = viewBoxHeight;\n if (!missingDimAttr) {\n parsedDim.width = parseUnit(widthAttr);\n parsedDim.height = parseUnit(heightAttr);\n scaleX = parsedDim.width / viewBoxWidth;\n scaleY = parsedDim.height / viewBoxHeight;\n }\n else {\n parsedDim.width = viewBoxWidth;\n parsedDim.height = viewBoxHeight;\n }\n\n // default is to preserve aspect ratio\n preserveAspectRatio = fabric.util.parsePreserveAspectRatioAttribute(preserveAspectRatio);\n if (preserveAspectRatio.alignX !== 'none') {\n //translate all container for the effect of Mid, Min, Max\n if (preserveAspectRatio.meetOrSlice === 'meet') {\n scaleY = scaleX = (scaleX > scaleY ? scaleY : scaleX);\n // calculate additional translation to move the viewbox\n }\n if (preserveAspectRatio.meetOrSlice === 'slice') {\n scaleY = scaleX = (scaleX > scaleY ? scaleX : scaleY);\n // calculate additional translation to move the viewbox\n }\n widthDiff = parsedDim.width - viewBoxWidth * scaleX;\n heightDiff = parsedDim.height - viewBoxHeight * scaleX;\n if (preserveAspectRatio.alignX === 'Mid') {\n widthDiff /= 2;\n }\n if (preserveAspectRatio.alignY === 'Mid') {\n heightDiff /= 2;\n }\n if (preserveAspectRatio.alignX === 'Min') {\n widthDiff = 0;\n }\n if (preserveAspectRatio.alignY === 'Min') {\n heightDiff = 0;\n }\n }\n\n if (scaleX === 1 && scaleY === 1 && minX === 0 && minY === 0 && x === 0 && y === 0) {\n return parsedDim;\n }\n if ((x || y) && element.parentNode.nodeName !== '#document') {\n translateMatrix = ' translate(' + parseUnit(x) + ' ' + parseUnit(y) + ') ';\n }\n\n matrix = translateMatrix + ' matrix(' + scaleX +\n ' 0' +\n ' 0 ' +\n scaleY + ' ' +\n (minX * scaleX + widthDiff) + ' ' +\n (minY * scaleY + heightDiff) + ') ';\n // seems unused.\n // parsedDim.viewboxTransform = fabric.parseTransformAttribute(matrix);\n if (element.nodeName === 'svg') {\n el = element.ownerDocument.createElementNS(fabric.svgNS, 'g');\n // element.firstChild != null\n while (element.firstChild) {\n el.appendChild(element.firstChild);\n }\n element.appendChild(el);\n }\n else {\n el = element;\n el.removeAttribute('x');\n el.removeAttribute('y');\n matrix = el.getAttribute('transform') + matrix;\n }\n el.setAttribute('transform', matrix);\n return parsedDim;\n }\n\n function hasAncestorWithNodeName(element, nodeName) {\n while (element && (element = element.parentNode)) {\n if (element.nodeName && nodeName.test(element.nodeName.replace('svg:', ''))\n && !element.getAttribute('instantiated_by_use')) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback\n * @static\n * @function\n * @memberOf fabric\n * @param {SVGDocument} doc SVG document to parse\n * @param {Function} callback Callback to call when parsing is finished;\n * It's being passed an array of elements (parsed from a document).\n * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.\n * @param {Object} [parsingOptions] options for parsing document\n * @param {String} [parsingOptions.crossOrigin] crossOrigin settings\n */\n fabric.parseSVGDocument = function(doc, callback, reviver, parsingOptions) {\n if (!doc) {\n return;\n }\n\n parseUseDirectives(doc);\n\n var svgUid = fabric.Object.__uid++, i, len,\n options = applyViewboxTransform(doc),\n descendants = fabric.util.toArray(doc.getElementsByTagName('*'));\n options.crossOrigin = parsingOptions && parsingOptions.crossOrigin;\n options.svgUid = svgUid;\n\n if (descendants.length === 0 && fabric.isLikelyNode) {\n // we're likely in node, where \"o3-xml\" library fails to gEBTN(\"*\")\n // https://github.com/ajaxorg/node-o3-xml/issues/21\n descendants = doc.selectNodes('//*[name(.)!=\"svg\"]');\n var arr = [];\n for (i = 0, len = descendants.length; i < len; i++) {\n arr[i] = descendants[i];\n }\n descendants = arr;\n }\n\n var elements = descendants.filter(function(el) {\n applyViewboxTransform(el);\n return fabric.svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', '')) &&\n !hasAncestorWithNodeName(el, fabric.svgInvalidAncestorsRegEx); // http://www.w3.org/TR/SVG/struct.html#DefsElement\n });\n if (!elements || (elements && !elements.length)) {\n callback && callback([], {});\n return;\n }\n var clipPaths = { };\n descendants.filter(function(el) {\n return el.nodeName.replace('svg:', '') === 'clipPath';\n }).forEach(function(el) {\n var id = el.getAttribute('id');\n clipPaths[id] = fabric.util.toArray(el.getElementsByTagName('*')).filter(function(el) {\n return fabric.svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', ''));\n });\n });\n fabric.gradientDefs[svgUid] = fabric.getGradientDefs(doc);\n fabric.cssRules[svgUid] = fabric.getCSSRules(doc);\n fabric.clipPaths[svgUid] = clipPaths;\n // Precedence of rules: style > class > attribute\n fabric.parseElements(elements, function(instances, elements) {\n if (callback) {\n callback(instances, options, elements, descendants);\n delete fabric.gradientDefs[svgUid];\n delete fabric.cssRules[svgUid];\n delete fabric.clipPaths[svgUid];\n }\n }, clone(options), reviver, parsingOptions);\n };\n\n function recursivelyParseGradientsXlink(doc, gradient) {\n var gradientsAttrs = ['gradientTransform', 'x1', 'x2', 'y1', 'y2', 'gradientUnits', 'cx', 'cy', 'r', 'fx', 'fy'],\n xlinkAttr = 'xlink:href',\n xLink = gradient.getAttribute(xlinkAttr).slice(1),\n referencedGradient = elementById(doc, xLink);\n if (referencedGradient && referencedGradient.getAttribute(xlinkAttr)) {\n recursivelyParseGradientsXlink(doc, referencedGradient);\n }\n gradientsAttrs.forEach(function(attr) {\n if (referencedGradient && !gradient.hasAttribute(attr) && referencedGradient.hasAttribute(attr)) {\n gradient.setAttribute(attr, referencedGradient.getAttribute(attr));\n }\n });\n if (!gradient.children.length) {\n var referenceClone = referencedGradient.cloneNode(true);\n while (referenceClone.firstChild) {\n gradient.appendChild(referenceClone.firstChild);\n }\n }\n gradient.removeAttribute(xlinkAttr);\n }\n\n var reFontDeclaration = new RegExp(\n '(normal|italic)?\\\\s*(normal|small-caps)?\\\\s*' +\n '(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\\\s*(' +\n fabric.reNum +\n '(?:px|cm|mm|em|pt|pc|in)*)(?:\\\\/(normal|' + fabric.reNum + '))?\\\\s+(.*)');\n\n extend(fabric, {\n /**\n * Parses a short font declaration, building adding its properties to a style object\n * @static\n * @function\n * @memberOf fabric\n * @param {String} value font declaration\n * @param {Object} oStyle definition\n */\n parseFontDeclaration: function(value, oStyle) {\n var match = value.match(reFontDeclaration);\n\n if (!match) {\n return;\n }\n var fontStyle = match[1],\n // font variant is not used\n // fontVariant = match[2],\n fontWeight = match[3],\n fontSize = match[4],\n lineHeight = match[5],\n fontFamily = match[6];\n\n if (fontStyle) {\n oStyle.fontStyle = fontStyle;\n }\n if (fontWeight) {\n oStyle.fontWeight = isNaN(parseFloat(fontWeight)) ? fontWeight : parseFloat(fontWeight);\n }\n if (fontSize) {\n oStyle.fontSize = parseUnit(fontSize);\n }\n if (fontFamily) {\n oStyle.fontFamily = fontFamily;\n }\n if (lineHeight) {\n oStyle.lineHeight = lineHeight === 'normal' ? 1 : lineHeight;\n }\n },\n\n /**\n * Parses an SVG document, returning all of the gradient declarations found in it\n * @static\n * @function\n * @memberOf fabric\n * @param {SVGDocument} doc SVG document to parse\n * @return {Object} Gradient definitions; key corresponds to element id, value -- to gradient definition element\n */\n getGradientDefs: function(doc) {\n var tagArray = [\n 'linearGradient',\n 'radialGradient',\n 'svg:linearGradient',\n 'svg:radialGradient'],\n elList = _getMultipleNodes(doc, tagArray),\n el, j = 0, gradientDefs = { };\n j = elList.length;\n while (j--) {\n el = elList[j];\n if (el.getAttribute('xlink:href')) {\n recursivelyParseGradientsXlink(doc, el);\n }\n gradientDefs[el.getAttribute('id')] = el;\n }\n return gradientDefs;\n },\n\n /**\n * Returns an object of attributes' name/value, given element and an array of attribute names;\n * Parses parent \"g\" nodes recursively upwards.\n * @static\n * @memberOf fabric\n * @param {DOMElement} element Element to parse\n * @param {Array} attributes Array of attributes to parse\n * @return {Object} object containing parsed attributes' names/values\n */\n parseAttributes: function(element, attributes, svgUid) {\n\n if (!element) {\n return;\n }\n\n var value,\n parentAttributes = { },\n fontSize, parentFontSize;\n\n if (typeof svgUid === 'undefined') {\n svgUid = element.getAttribute('svgUid');\n }\n // if there's a parent container (`g` or `a` or `symbol` node), parse its attributes recursively upwards\n if (element.parentNode && fabric.svgValidParentsRegEx.test(element.parentNode.nodeName)) {\n parentAttributes = fabric.parseAttributes(element.parentNode, attributes, svgUid);\n }\n\n var ownAttributes = attributes.reduce(function(memo, attr) {\n value = element.getAttribute(attr);\n if (value) { // eslint-disable-line\n memo[attr] = value;\n }\n return memo;\n }, { });\n // add values parsed from style, which take precedence over attributes\n // (see: http://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes)\n var cssAttrs = extend(\n getGlobalStylesForElement(element, svgUid),\n fabric.parseStyleAttribute(element)\n );\n ownAttributes = extend(\n ownAttributes,\n cssAttrs\n );\n if (cssAttrs[cPath]) {\n element.setAttribute(cPath, cssAttrs[cPath]);\n }\n fontSize = parentFontSize = parentAttributes.fontSize || fabric.Text.DEFAULT_SVG_FONT_SIZE;\n if (ownAttributes[fSize]) {\n // looks like the minimum should be 9px when dealing with ems. this is what looks like in browsers.\n ownAttributes[fSize] = fontSize = parseUnit(ownAttributes[fSize], parentFontSize);\n }\n\n var normalizedAttr, normalizedValue, normalizedStyle = {};\n for (var attr in ownAttributes) {\n normalizedAttr = normalizeAttr(attr);\n normalizedValue = normalizeValue(normalizedAttr, ownAttributes[attr], parentAttributes, fontSize);\n normalizedStyle[normalizedAttr] = normalizedValue;\n }\n if (normalizedStyle && normalizedStyle.font) {\n fabric.parseFontDeclaration(normalizedStyle.font, normalizedStyle);\n }\n var mergedAttrs = extend(parentAttributes, normalizedStyle);\n return fabric.svgValidParentsRegEx.test(element.nodeName) ? mergedAttrs : _setStrokeFillOpacity(mergedAttrs);\n },\n\n /**\n * Transforms an array of svg elements to corresponding fabric.* instances\n * @static\n * @memberOf fabric\n * @param {Array} elements Array of elements to parse\n * @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)\n * @param {Object} [options] Options object\n * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.\n */\n parseElements: function(elements, callback, options, reviver, parsingOptions) {\n new fabric.ElementsParser(elements, callback, options, reviver, parsingOptions).parse();\n },\n\n /**\n * Parses \"style\" attribute, retuning an object with values\n * @static\n * @memberOf fabric\n * @param {SVGElement} element Element to parse\n * @return {Object} Objects with values parsed from style attribute of an element\n */\n parseStyleAttribute: function(element) {\n var oStyle = { },\n style = element.getAttribute('style');\n\n if (!style) {\n return oStyle;\n }\n\n if (typeof style === 'string') {\n parseStyleString(style, oStyle);\n }\n else {\n parseStyleObject(style, oStyle);\n }\n\n return oStyle;\n },\n\n /**\n * Parses \"points\" attribute, returning an array of values\n * @static\n * @memberOf fabric\n * @param {String} points points attribute string\n * @return {Array} array of points\n */\n parsePointsAttribute: function(points) {\n\n // points attribute is required and must not be empty\n if (!points) {\n return null;\n }\n\n // replace commas with whitespace and remove bookending whitespace\n points = points.replace(/,/g, ' ').trim();\n\n points = points.split(/\\s+/);\n var parsedPoints = [], i, len;\n\n for (i = 0, len = points.length; i < len; i += 2) {\n parsedPoints.push({\n x: parseFloat(points[i]),\n y: parseFloat(points[i + 1])\n });\n }\n\n // odd number of points is an error\n // if (parsedPoints.length % 2 !== 0) {\n // return null;\n // }\n\n return parsedPoints;\n },\n\n /**\n * Returns CSS rules for a given SVG document\n * @static\n * @function\n * @memberOf fabric\n * @param {SVGDocument} doc SVG document to parse\n * @return {Object} CSS rules of this document\n */\n getCSSRules: function(doc) {\n var styles = doc.getElementsByTagName('style'), i, len,\n allRules = { }, rules;\n\n // very crude parsing of style contents\n for (i = 0, len = styles.length; i < len; i++) {\n var styleContents = styles[i].textContent;\n\n // remove comments\n styleContents = styleContents.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n if (styleContents.trim() === '') {\n continue;\n }\n // recovers all the rule in this form `body { style code... }`\n // rules = styleContents.match(/[^{]*\\{[\\s\\S]*?\\}/g);\n rules = styleContents.split('}');\n // remove empty rules.\n rules = rules.filter(function(rule) { return rule.trim(); });\n // at this point we have hopefully an array of rules `body { style code... `\n // eslint-disable-next-line no-loop-func\n rules.forEach(function(rule) {\n\n var match = rule.split('{'),\n ruleObj = { }, declaration = match[1].trim(),\n propertyValuePairs = declaration.split(';').filter(function(pair) { return pair.trim(); });\n\n for (i = 0, len = propertyValuePairs.length; i < len; i++) {\n var pair = propertyValuePairs[i].split(':'),\n property = pair[0].trim(),\n value = pair[1].trim();\n ruleObj[property] = value;\n }\n rule = match[0].trim();\n rule.split(',').forEach(function(_rule) {\n _rule = _rule.replace(/^svg/i, '').trim();\n if (_rule === '') {\n return;\n }\n if (allRules[_rule]) {\n fabric.util.object.extend(allRules[_rule], ruleObj);\n }\n else {\n allRules[_rule] = fabric.util.object.clone(ruleObj);\n }\n });\n });\n }\n return allRules;\n },\n\n /**\n * Takes url corresponding to an SVG document, and parses it into a set of fabric objects.\n * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy)\n * @memberOf fabric\n * @param {String} url\n * @param {Function} callback\n * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.\n * @param {Object} [options] Object containing options for parsing\n * @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources\n */\n loadSVGFromURL: function(url, callback, reviver, options) {\n\n url = url.replace(/^\\n\\s*/, '').trim();\n new fabric.util.request(url, {\n method: 'get',\n onComplete: onComplete\n });\n\n function onComplete(r) {\n\n var xml = r.responseXML;\n if (!xml || !xml.documentElement) {\n callback && callback(null);\n return false;\n }\n\n fabric.parseSVGDocument(xml.documentElement, function (results, _options, elements, allElements) {\n callback && callback(results, _options, elements, allElements);\n }, reviver, options);\n }\n },\n\n /**\n * Takes string corresponding to an SVG document, and parses it into a set of fabric objects\n * @memberOf fabric\n * @param {String} string\n * @param {Function} callback\n * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.\n * @param {Object} [options] Object containing options for parsing\n * @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources\n */\n loadSVGFromString: function(string, callback, reviver, options) {\n var parser = new fabric.window.DOMParser(),\n doc = parser.parseFromString(string.trim(), 'text/xml');\n fabric.parseSVGDocument(doc.documentElement, function (results, _options, elements, allElements) {\n callback(results, _options, elements, allElements);\n }, reviver, options);\n }\n });\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\nfabric.ElementsParser = function(elements, callback, options, reviver, parsingOptions, doc) {\n this.elements = elements;\n this.callback = callback;\n this.options = options;\n this.reviver = reviver;\n this.svgUid = (options && options.svgUid) || 0;\n this.parsingOptions = parsingOptions;\n this.regexUrl = /^url\\(['\"]?#([^'\"]+)['\"]?\\)/g;\n this.doc = doc;\n};\n\n(function(proto) {\n proto.parse = function() {\n this.instances = new Array(this.elements.length);\n this.numElements = this.elements.length;\n this.createObjects();\n };\n\n proto.createObjects = function() {\n var _this = this;\n this.elements.forEach(function(element, i) {\n element.setAttribute('svgUid', _this.svgUid);\n _this.createObject(element, i);\n });\n };\n\n proto.findTag = function(el) {\n return fabric[fabric.util.string.capitalize(el.tagName.replace('svg:', ''))];\n };\n\n proto.createObject = function(el, index) {\n var klass = this.findTag(el);\n if (klass && klass.fromElement) {\n try {\n klass.fromElement(el, this.createCallback(index, el), this.options);\n }\n catch (err) {\n fabric.log(err);\n }\n }\n else {\n this.checkIfDone();\n }\n };\n\n proto.createCallback = function(index, el) {\n var _this = this;\n return function(obj) {\n var _options;\n _this.resolveGradient(obj, el, 'fill');\n _this.resolveGradient(obj, el, 'stroke');\n if (obj instanceof fabric.Image && obj._originalElement) {\n _options = obj.parsePreserveAspectRatioAttribute(el);\n }\n obj._removeTransformMatrix(_options);\n _this.resolveClipPath(obj, el);\n _this.reviver && _this.reviver(el, obj);\n _this.instances[index] = obj;\n _this.checkIfDone();\n };\n };\n\n proto.extractPropertyDefinition = function(obj, property, storage) {\n var value = obj[property], regex = this.regexUrl;\n if (!regex.test(value)) {\n return;\n }\n regex.lastIndex = 0;\n var id = regex.exec(value)[1];\n regex.lastIndex = 0;\n return fabric[storage][this.svgUid][id];\n };\n\n proto.resolveGradient = function(obj, el, property) {\n var gradientDef = this.extractPropertyDefinition(obj, property, 'gradientDefs');\n if (gradientDef) {\n var opacityAttr = el.getAttribute(property + '-opacity');\n var gradient = fabric.Gradient.fromElement(gradientDef, obj, opacityAttr, this.options);\n obj.set(property, gradient);\n }\n };\n\n proto.createClipPathCallback = function(obj, container) {\n return function(_newObj) {\n _newObj._removeTransformMatrix();\n _newObj.fillRule = _newObj.clipRule;\n container.push(_newObj);\n };\n };\n\n proto.resolveClipPath = function(obj, usingElement) {\n var clipPath = this.extractPropertyDefinition(obj, 'clipPath', 'clipPaths'),\n element, klass, objTransformInv, container, gTransform, options;\n if (clipPath) {\n container = [];\n objTransformInv = fabric.util.invertTransform(obj.calcTransformMatrix());\n // move the clipPath tag as sibling to the real element that is using it\n var clipPathTag = clipPath[0].parentNode;\n var clipPathOwner = usingElement;\n while (clipPathOwner.parentNode && clipPathOwner.getAttribute('clip-path') !== obj.clipPath) {\n clipPathOwner = clipPathOwner.parentNode;\n }\n clipPathOwner.parentNode.appendChild(clipPathTag);\n for (var i = 0; i < clipPath.length; i++) {\n element = clipPath[i];\n klass = this.findTag(element);\n klass.fromElement(\n element,\n this.createClipPathCallback(obj, container),\n this.options\n );\n }\n if (container.length === 1) {\n clipPath = container[0];\n }\n else {\n clipPath = new fabric.Group(container);\n }\n gTransform = fabric.util.multiplyTransformMatrices(\n objTransformInv,\n clipPath.calcTransformMatrix()\n );\n if (clipPath.clipPath) {\n this.resolveClipPath(clipPath, clipPathOwner);\n }\n var options = fabric.util.qrDecompose(gTransform);\n clipPath.flipX = false;\n clipPath.flipY = false;\n clipPath.set('scaleX', options.scaleX);\n clipPath.set('scaleY', options.scaleY);\n clipPath.angle = options.angle;\n clipPath.skewX = options.skewX;\n clipPath.skewY = 0;\n clipPath.setPositionByOrigin({ x: options.translateX, y: options.translateY }, 'center', 'center');\n obj.clipPath = clipPath;\n }\n else {\n // if clip-path does not resolve to any element, delete the property.\n delete obj.clipPath;\n }\n };\n\n proto.checkIfDone = function() {\n if (--this.numElements === 0) {\n this.instances = this.instances.filter(function(el) {\n // eslint-disable-next-line no-eq-null, eqeqeq\n return el != null;\n });\n this.callback(this.instances, this.elements);\n }\n };\n})(fabric.ElementsParser.prototype);\n\n\n(function(global) {\n\n 'use strict';\n\n /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */\n\n var fabric = global.fabric || (global.fabric = { });\n\n if (fabric.Point) {\n fabric.warn('fabric.Point is already defined');\n return;\n }\n\n fabric.Point = Point;\n\n /**\n * Point class\n * @class fabric.Point\n * @memberOf fabric\n * @constructor\n * @param {Number} x\n * @param {Number} y\n * @return {fabric.Point} thisArg\n */\n function Point(x, y) {\n this.x = x;\n this.y = y;\n }\n\n Point.prototype = /** @lends fabric.Point.prototype */ {\n\n type: 'point',\n\n constructor: Point,\n\n /**\n * Adds another point to this one and returns another one\n * @param {fabric.Point} that\n * @return {fabric.Point} new Point instance with added values\n */\n add: function (that) {\n return new Point(this.x + that.x, this.y + that.y);\n },\n\n /**\n * Adds another point to this one\n * @param {fabric.Point} that\n * @return {fabric.Point} thisArg\n * @chainable\n */\n addEquals: function (that) {\n this.x += that.x;\n this.y += that.y;\n return this;\n },\n\n /**\n * Adds value to this point and returns a new one\n * @param {Number} scalar\n * @return {fabric.Point} new Point with added value\n */\n scalarAdd: function (scalar) {\n return new Point(this.x + scalar, this.y + scalar);\n },\n\n /**\n * Adds value to this point\n * @param {Number} scalar\n * @return {fabric.Point} thisArg\n * @chainable\n */\n scalarAddEquals: function (scalar) {\n this.x += scalar;\n this.y += scalar;\n return this;\n },\n\n /**\n * Subtracts another point from this point and returns a new one\n * @param {fabric.Point} that\n * @return {fabric.Point} new Point object with subtracted values\n */\n subtract: function (that) {\n return new Point(this.x - that.x, this.y - that.y);\n },\n\n /**\n * Subtracts another point from this point\n * @param {fabric.Point} that\n * @return {fabric.Point} thisArg\n * @chainable\n */\n subtractEquals: function (that) {\n this.x -= that.x;\n this.y -= that.y;\n return this;\n },\n\n /**\n * Subtracts value from this point and returns a new one\n * @param {Number} scalar\n * @return {fabric.Point}\n */\n scalarSubtract: function (scalar) {\n return new Point(this.x - scalar, this.y - scalar);\n },\n\n /**\n * Subtracts value from this point\n * @param {Number} scalar\n * @return {fabric.Point} thisArg\n * @chainable\n */\n scalarSubtractEquals: function (scalar) {\n this.x -= scalar;\n this.y -= scalar;\n return this;\n },\n\n /**\n * Multiplies this point by a value and returns a new one\n * TODO: rename in scalarMultiply in 2.0\n * @param {Number} scalar\n * @return {fabric.Point}\n */\n multiply: function (scalar) {\n return new Point(this.x * scalar, this.y * scalar);\n },\n\n /**\n * Multiplies this point by a value\n * TODO: rename in scalarMultiplyEquals in 2.0\n * @param {Number} scalar\n * @return {fabric.Point} thisArg\n * @chainable\n */\n multiplyEquals: function (scalar) {\n this.x *= scalar;\n this.y *= scalar;\n return this;\n },\n\n /**\n * Divides this point by a value and returns a new one\n * TODO: rename in scalarDivide in 2.0\n * @param {Number} scalar\n * @return {fabric.Point}\n */\n divide: function (scalar) {\n return new Point(this.x / scalar, this.y / scalar);\n },\n\n /**\n * Divides this point by a value\n * TODO: rename in scalarDivideEquals in 2.0\n * @param {Number} scalar\n * @return {fabric.Point} thisArg\n * @chainable\n */\n divideEquals: function (scalar) {\n this.x /= scalar;\n this.y /= scalar;\n return this;\n },\n\n /**\n * Returns true if this point is equal to another one\n * @param {fabric.Point} that\n * @return {Boolean}\n */\n eq: function (that) {\n return (this.x === that.x && this.y === that.y);\n },\n\n /**\n * Returns true if this point is less than another one\n * @param {fabric.Point} that\n * @return {Boolean}\n */\n lt: function (that) {\n return (this.x < that.x && this.y < that.y);\n },\n\n /**\n * Returns true if this point is less than or equal to another one\n * @param {fabric.Point} that\n * @return {Boolean}\n */\n lte: function (that) {\n return (this.x <= that.x && this.y <= that.y);\n },\n\n /**\n\n * Returns true if this point is greater another one\n * @param {fabric.Point} that\n * @return {Boolean}\n */\n gt: function (that) {\n return (this.x > that.x && this.y > that.y);\n },\n\n /**\n * Returns true if this point is greater than or equal to another one\n * @param {fabric.Point} that\n * @return {Boolean}\n */\n gte: function (that) {\n return (this.x >= that.x && this.y >= that.y);\n },\n\n /**\n * Returns new point which is the result of linear interpolation with this one and another one\n * @param {fabric.Point} that\n * @param {Number} t , position of interpolation, between 0 and 1 default 0.5\n * @return {fabric.Point}\n */\n lerp: function (that, t) {\n if (typeof t === 'undefined') {\n t = 0.5;\n }\n t = Math.max(Math.min(1, t), 0);\n return new Point(this.x + (that.x - this.x) * t, this.y + (that.y - this.y) * t);\n },\n\n /**\n * Returns distance from this point and another one\n * @param {fabric.Point} that\n * @return {Number}\n */\n distanceFrom: function (that) {\n var dx = this.x - that.x,\n dy = this.y - that.y;\n return Math.sqrt(dx * dx + dy * dy);\n },\n\n /**\n * Returns the point between this point and another one\n * @param {fabric.Point} that\n * @return {fabric.Point}\n */\n midPointFrom: function (that) {\n return this.lerp(that);\n },\n\n /**\n * Returns a new point which is the min of this and another one\n * @param {fabric.Point} that\n * @return {fabric.Point}\n */\n min: function (that) {\n return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));\n },\n\n /**\n * Returns a new point which is the max of this and another one\n * @param {fabric.Point} that\n * @return {fabric.Point}\n */\n max: function (that) {\n return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));\n },\n\n /**\n * Returns string representation of this point\n * @return {String}\n */\n toString: function () {\n return this.x + ',' + this.y;\n },\n\n /**\n * Sets x/y of this point\n * @param {Number} x\n * @param {Number} y\n * @chainable\n */\n setXY: function (x, y) {\n this.x = x;\n this.y = y;\n return this;\n },\n\n /**\n * Sets x of this point\n * @param {Number} x\n * @chainable\n */\n setX: function (x) {\n this.x = x;\n return this;\n },\n\n /**\n * Sets y of this point\n * @param {Number} y\n * @chainable\n */\n setY: function (y) {\n this.y = y;\n return this;\n },\n\n /**\n * Sets x/y of this point from another point\n * @param {fabric.Point} that\n * @chainable\n */\n setFromPoint: function (that) {\n this.x = that.x;\n this.y = that.y;\n return this;\n },\n\n /**\n * Swaps x/y of this point and another point\n * @param {fabric.Point} that\n */\n swap: function (that) {\n var x = this.x,\n y = this.y;\n this.x = that.x;\n this.y = that.y;\n that.x = x;\n that.y = y;\n },\n\n /**\n * return a cloned instance of the point\n * @return {fabric.Point}\n */\n clone: function () {\n return new Point(this.x, this.y);\n }\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */\n var fabric = global.fabric || (global.fabric = { });\n\n if (fabric.Intersection) {\n fabric.warn('fabric.Intersection is already defined');\n return;\n }\n\n /**\n * Intersection class\n * @class fabric.Intersection\n * @memberOf fabric\n * @constructor\n */\n function Intersection(status) {\n this.status = status;\n this.points = [];\n }\n\n fabric.Intersection = Intersection;\n\n fabric.Intersection.prototype = /** @lends fabric.Intersection.prototype */ {\n\n constructor: Intersection,\n\n /**\n * Appends a point to intersection\n * @param {fabric.Point} point\n * @return {fabric.Intersection} thisArg\n * @chainable\n */\n appendPoint: function (point) {\n this.points.push(point);\n return this;\n },\n\n /**\n * Appends points to intersection\n * @param {Array} points\n * @return {fabric.Intersection} thisArg\n * @chainable\n */\n appendPoints: function (points) {\n this.points = this.points.concat(points);\n return this;\n }\n };\n\n /**\n * Checks if one line intersects another\n * TODO: rename in intersectSegmentSegment\n * @static\n * @param {fabric.Point} a1\n * @param {fabric.Point} a2\n * @param {fabric.Point} b1\n * @param {fabric.Point} b2\n * @return {fabric.Intersection}\n */\n fabric.Intersection.intersectLineLine = function (a1, a2, b1, b2) {\n var result,\n uaT = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),\n ubT = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),\n uB = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);\n if (uB !== 0) {\n var ua = uaT / uB,\n ub = ubT / uB;\n if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {\n result = new Intersection('Intersection');\n result.appendPoint(new fabric.Point(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y)));\n }\n else {\n result = new Intersection();\n }\n }\n else {\n if (uaT === 0 || ubT === 0) {\n result = new Intersection('Coincident');\n }\n else {\n result = new Intersection('Parallel');\n }\n }\n return result;\n };\n\n /**\n * Checks if line intersects polygon\n * TODO: rename in intersectSegmentPolygon\n * fix detection of coincident\n * @static\n * @param {fabric.Point} a1\n * @param {fabric.Point} a2\n * @param {Array} points\n * @return {fabric.Intersection}\n */\n fabric.Intersection.intersectLinePolygon = function(a1, a2, points) {\n var result = new Intersection(),\n length = points.length,\n b1, b2, inter, i;\n\n for (i = 0; i < length; i++) {\n b1 = points[i];\n b2 = points[(i + 1) % length];\n inter = Intersection.intersectLineLine(a1, a2, b1, b2);\n\n result.appendPoints(inter.points);\n }\n if (result.points.length > 0) {\n result.status = 'Intersection';\n }\n return result;\n };\n\n /**\n * Checks if polygon intersects another polygon\n * @static\n * @param {Array} points1\n * @param {Array} points2\n * @return {fabric.Intersection}\n */\n fabric.Intersection.intersectPolygonPolygon = function (points1, points2) {\n var result = new Intersection(),\n length = points1.length, i;\n\n for (i = 0; i < length; i++) {\n var a1 = points1[i],\n a2 = points1[(i + 1) % length],\n inter = Intersection.intersectLinePolygon(a1, a2, points2);\n\n result.appendPoints(inter.points);\n }\n if (result.points.length > 0) {\n result.status = 'Intersection';\n }\n return result;\n };\n\n /**\n * Checks if polygon intersects rectangle\n * @static\n * @param {Array} points\n * @param {fabric.Point} r1\n * @param {fabric.Point} r2\n * @return {fabric.Intersection}\n */\n fabric.Intersection.intersectPolygonRectangle = function (points, r1, r2) {\n var min = r1.min(r2),\n max = r1.max(r2),\n topRight = new fabric.Point(max.x, min.y),\n bottomLeft = new fabric.Point(min.x, max.y),\n inter1 = Intersection.intersectLinePolygon(min, topRight, points),\n inter2 = Intersection.intersectLinePolygon(topRight, max, points),\n inter3 = Intersection.intersectLinePolygon(max, bottomLeft, points),\n inter4 = Intersection.intersectLinePolygon(bottomLeft, min, points),\n result = new Intersection();\n\n result.appendPoints(inter1.points);\n result.appendPoints(inter2.points);\n result.appendPoints(inter3.points);\n result.appendPoints(inter4.points);\n\n if (result.points.length > 0) {\n result.status = 'Intersection';\n }\n return result;\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { });\n\n if (fabric.Color) {\n fabric.warn('fabric.Color is already defined.');\n return;\n }\n\n /**\n * Color class\n * The purpose of {@link fabric.Color} is to abstract and encapsulate common color operations;\n * {@link fabric.Color} is a constructor and creates instances of {@link fabric.Color} objects.\n *\n * @class fabric.Color\n * @param {String} color optional in hex or rgb(a) or hsl format or from known color list\n * @return {fabric.Color} thisArg\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#colors}\n */\n function Color(color) {\n if (!color) {\n this.setSource([0, 0, 0, 1]);\n }\n else {\n this._tryParsingColor(color);\n }\n }\n\n fabric.Color = Color;\n\n fabric.Color.prototype = /** @lends fabric.Color.prototype */ {\n\n /**\n * @private\n * @param {String|Array} color Color value to parse\n */\n _tryParsingColor: function(color) {\n var source;\n\n if (color in Color.colorNameMap) {\n color = Color.colorNameMap[color];\n }\n\n if (color === 'transparent') {\n source = [255, 255, 255, 0];\n }\n\n if (!source) {\n source = Color.sourceFromHex(color);\n }\n if (!source) {\n source = Color.sourceFromRgb(color);\n }\n if (!source) {\n source = Color.sourceFromHsl(color);\n }\n if (!source) {\n //if color is not recognize let's make black as canvas does\n source = [0, 0, 0, 1];\n }\n if (source) {\n this.setSource(source);\n }\n },\n\n /**\n * Adapted from https://github.com/mjijackson\n * @private\n * @param {Number} r Red color value\n * @param {Number} g Green color value\n * @param {Number} b Blue color value\n * @return {Array} Hsl color\n */\n _rgbToHsl: function(r, g, b) {\n r /= 255; g /= 255; b /= 255;\n\n var h, s, l,\n max = fabric.util.array.max([r, g, b]),\n min = fabric.util.array.min([r, g, b]);\n\n l = (max + min) / 2;\n\n if (max === min) {\n h = s = 0; // achromatic\n }\n else {\n var d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n\n return [\n Math.round(h * 360),\n Math.round(s * 100),\n Math.round(l * 100)\n ];\n },\n\n /**\n * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])\n * @return {Array}\n */\n getSource: function() {\n return this._source;\n },\n\n /**\n * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])\n * @param {Array} source\n */\n setSource: function(source) {\n this._source = source;\n },\n\n /**\n * Returns color representation in RGB format\n * @return {String} ex: rgb(0-255,0-255,0-255)\n */\n toRgb: function() {\n var source = this.getSource();\n return 'rgb(' + source[0] + ',' + source[1] + ',' + source[2] + ')';\n },\n\n /**\n * Returns color representation in RGBA format\n * @return {String} ex: rgba(0-255,0-255,0-255,0-1)\n */\n toRgba: function() {\n var source = this.getSource();\n return 'rgba(' + source[0] + ',' + source[1] + ',' + source[2] + ',' + source[3] + ')';\n },\n\n /**\n * Returns color representation in HSL format\n * @return {String} ex: hsl(0-360,0%-100%,0%-100%)\n */\n toHsl: function() {\n var source = this.getSource(),\n hsl = this._rgbToHsl(source[0], source[1], source[2]);\n\n return 'hsl(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%)';\n },\n\n /**\n * Returns color representation in HSLA format\n * @return {String} ex: hsla(0-360,0%-100%,0%-100%,0-1)\n */\n toHsla: function() {\n var source = this.getSource(),\n hsl = this._rgbToHsl(source[0], source[1], source[2]);\n\n return 'hsla(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%,' + source[3] + ')';\n },\n\n /**\n * Returns color representation in HEX format\n * @return {String} ex: FF5555\n */\n toHex: function() {\n var source = this.getSource(), r, g, b;\n\n r = source[0].toString(16);\n r = (r.length === 1) ? ('0' + r) : r;\n\n g = source[1].toString(16);\n g = (g.length === 1) ? ('0' + g) : g;\n\n b = source[2].toString(16);\n b = (b.length === 1) ? ('0' + b) : b;\n\n return r.toUpperCase() + g.toUpperCase() + b.toUpperCase();\n },\n\n /**\n * Returns color representation in HEXA format\n * @return {String} ex: FF5555CC\n */\n toHexa: function() {\n var source = this.getSource(), a;\n\n a = Math.round(source[3] * 255);\n a = a.toString(16);\n a = (a.length === 1) ? ('0' + a) : a;\n\n return this.toHex() + a.toUpperCase();\n },\n\n /**\n * Gets value of alpha channel for this color\n * @return {Number} 0-1\n */\n getAlpha: function() {\n return this.getSource()[3];\n },\n\n /**\n * Sets value of alpha channel for this color\n * @param {Number} alpha Alpha value 0-1\n * @return {fabric.Color} thisArg\n */\n setAlpha: function(alpha) {\n var source = this.getSource();\n source[3] = alpha;\n this.setSource(source);\n return this;\n },\n\n /**\n * Transforms color to its grayscale representation\n * @return {fabric.Color} thisArg\n */\n toGrayscale: function() {\n var source = this.getSource(),\n average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10),\n currentAlpha = source[3];\n this.setSource([average, average, average, currentAlpha]);\n return this;\n },\n\n /**\n * Transforms color to its black and white representation\n * @param {Number} threshold\n * @return {fabric.Color} thisArg\n */\n toBlackWhite: function(threshold) {\n var source = this.getSource(),\n average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0),\n currentAlpha = source[3];\n\n threshold = threshold || 127;\n\n average = (Number(average) < Number(threshold)) ? 0 : 255;\n this.setSource([average, average, average, currentAlpha]);\n return this;\n },\n\n /**\n * Overlays color with another color\n * @param {String|fabric.Color} otherColor\n * @return {fabric.Color} thisArg\n */\n overlayWith: function(otherColor) {\n if (!(otherColor instanceof Color)) {\n otherColor = new Color(otherColor);\n }\n\n var result = [],\n alpha = this.getAlpha(),\n otherAlpha = 0.5,\n source = this.getSource(),\n otherSource = otherColor.getSource(), i;\n\n for (i = 0; i < 3; i++) {\n result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha)));\n }\n\n result[3] = alpha;\n this.setSource(result);\n return this;\n }\n };\n\n /**\n * Regex matching color in RGB or RGBA formats (ex: rgb(0, 0, 0), rgba(255, 100, 10, 0.5), rgba( 255 , 100 , 10 , 0.5 ), rgb(1,1,1), rgba(100%, 60%, 10%, 0.5))\n * @static\n * @field\n * @memberOf fabric.Color\n */\n // eslint-disable-next-line max-len\n fabric.Color.reRGBa = /^rgba?\\(\\s*(\\d{1,3}(?:\\.\\d+)?\\%?)\\s*,\\s*(\\d{1,3}(?:\\.\\d+)?\\%?)\\s*,\\s*(\\d{1,3}(?:\\.\\d+)?\\%?)\\s*(?:\\s*,\\s*((?:\\d*\\.?\\d+)?)\\s*)?\\)$/i;\n\n /**\n * Regex matching color in HSL or HSLA formats (ex: hsl(200, 80%, 10%), hsla(300, 50%, 80%, 0.5), hsla( 300 , 50% , 80% , 0.5 ))\n * @static\n * @field\n * @memberOf fabric.Color\n */\n fabric.Color.reHSLa = /^hsla?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3}\\%)\\s*,\\s*(\\d{1,3}\\%)\\s*(?:\\s*,\\s*(\\d+(?:\\.\\d+)?)\\s*)?\\)$/i;\n\n /**\n * Regex matching color in HEX format (ex: #FF5544CC, #FF5555, 010155, aff)\n * @static\n * @field\n * @memberOf fabric.Color\n */\n fabric.Color.reHex = /^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i;\n\n /**\n * Map of the 148 color names with HEX code\n * @static\n * @field\n * @memberOf fabric.Color\n * @see: https://www.w3.org/TR/css3-color/#svg-color\n */\n fabric.Color.colorNameMap = {\n aliceblue: '#F0F8FF',\n antiquewhite: '#FAEBD7',\n aqua: '#00FFFF',\n aquamarine: '#7FFFD4',\n azure: '#F0FFFF',\n beige: '#F5F5DC',\n bisque: '#FFE4C4',\n black: '#000000',\n blanchedalmond: '#FFEBCD',\n blue: '#0000FF',\n blueviolet: '#8A2BE2',\n brown: '#A52A2A',\n burlywood: '#DEB887',\n cadetblue: '#5F9EA0',\n chartreuse: '#7FFF00',\n chocolate: '#D2691E',\n coral: '#FF7F50',\n cornflowerblue: '#6495ED',\n cornsilk: '#FFF8DC',\n crimson: '#DC143C',\n cyan: '#00FFFF',\n darkblue: '#00008B',\n darkcyan: '#008B8B',\n darkgoldenrod: '#B8860B',\n darkgray: '#A9A9A9',\n darkgrey: '#A9A9A9',\n darkgreen: '#006400',\n darkkhaki: '#BDB76B',\n darkmagenta: '#8B008B',\n darkolivegreen: '#556B2F',\n darkorange: '#FF8C00',\n darkorchid: '#9932CC',\n darkred: '#8B0000',\n darksalmon: '#E9967A',\n darkseagreen: '#8FBC8F',\n darkslateblue: '#483D8B',\n darkslategray: '#2F4F4F',\n darkslategrey: '#2F4F4F',\n darkturquoise: '#00CED1',\n darkviolet: '#9400D3',\n deeppink: '#FF1493',\n deepskyblue: '#00BFFF',\n dimgray: '#696969',\n dimgrey: '#696969',\n dodgerblue: '#1E90FF',\n firebrick: '#B22222',\n floralwhite: '#FFFAF0',\n forestgreen: '#228B22',\n fuchsia: '#FF00FF',\n gainsboro: '#DCDCDC',\n ghostwhite: '#F8F8FF',\n gold: '#FFD700',\n goldenrod: '#DAA520',\n gray: '#808080',\n grey: '#808080',\n green: '#008000',\n greenyellow: '#ADFF2F',\n honeydew: '#F0FFF0',\n hotpink: '#FF69B4',\n indianred: '#CD5C5C',\n indigo: '#4B0082',\n ivory: '#FFFFF0',\n khaki: '#F0E68C',\n lavender: '#E6E6FA',\n lavenderblush: '#FFF0F5',\n lawngreen: '#7CFC00',\n lemonchiffon: '#FFFACD',\n lightblue: '#ADD8E6',\n lightcoral: '#F08080',\n lightcyan: '#E0FFFF',\n lightgoldenrodyellow: '#FAFAD2',\n lightgray: '#D3D3D3',\n lightgrey: '#D3D3D3',\n lightgreen: '#90EE90',\n lightpink: '#FFB6C1',\n lightsalmon: '#FFA07A',\n lightseagreen: '#20B2AA',\n lightskyblue: '#87CEFA',\n lightslategray: '#778899',\n lightslategrey: '#778899',\n lightsteelblue: '#B0C4DE',\n lightyellow: '#FFFFE0',\n lime: '#00FF00',\n limegreen: '#32CD32',\n linen: '#FAF0E6',\n magenta: '#FF00FF',\n maroon: '#800000',\n mediumaquamarine: '#66CDAA',\n mediumblue: '#0000CD',\n mediumorchid: '#BA55D3',\n mediumpurple: '#9370DB',\n mediumseagreen: '#3CB371',\n mediumslateblue: '#7B68EE',\n mediumspringgreen: '#00FA9A',\n mediumturquoise: '#48D1CC',\n mediumvioletred: '#C71585',\n midnightblue: '#191970',\n mintcream: '#F5FFFA',\n mistyrose: '#FFE4E1',\n moccasin: '#FFE4B5',\n navajowhite: '#FFDEAD',\n navy: '#000080',\n oldlace: '#FDF5E6',\n olive: '#808000',\n olivedrab: '#6B8E23',\n orange: '#FFA500',\n orangered: '#FF4500',\n orchid: '#DA70D6',\n palegoldenrod: '#EEE8AA',\n palegreen: '#98FB98',\n paleturquoise: '#AFEEEE',\n palevioletred: '#DB7093',\n papayawhip: '#FFEFD5',\n peachpuff: '#FFDAB9',\n peru: '#CD853F',\n pink: '#FFC0CB',\n plum: '#DDA0DD',\n powderblue: '#B0E0E6',\n purple: '#800080',\n rebeccapurple: '#663399',\n red: '#FF0000',\n rosybrown: '#BC8F8F',\n royalblue: '#4169E1',\n saddlebrown: '#8B4513',\n salmon: '#FA8072',\n sandybrown: '#F4A460',\n seagreen: '#2E8B57',\n seashell: '#FFF5EE',\n sienna: '#A0522D',\n silver: '#C0C0C0',\n skyblue: '#87CEEB',\n slateblue: '#6A5ACD',\n slategray: '#708090',\n slategrey: '#708090',\n snow: '#FFFAFA',\n springgreen: '#00FF7F',\n steelblue: '#4682B4',\n tan: '#D2B48C',\n teal: '#008080',\n thistle: '#D8BFD8',\n tomato: '#FF6347',\n turquoise: '#40E0D0',\n violet: '#EE82EE',\n wheat: '#F5DEB3',\n white: '#FFFFFF',\n whitesmoke: '#F5F5F5',\n yellow: '#FFFF00',\n yellowgreen: '#9ACD32'\n };\n\n /**\n * @private\n * @param {Number} p\n * @param {Number} q\n * @param {Number} t\n * @return {Number}\n */\n function hue2rgb(p, q, t) {\n if (t < 0) {\n t += 1;\n }\n if (t > 1) {\n t -= 1;\n }\n if (t < 1 / 6) {\n return p + (q - p) * 6 * t;\n }\n if (t < 1 / 2) {\n return q;\n }\n if (t < 2 / 3) {\n return p + (q - p) * (2 / 3 - t) * 6;\n }\n return p;\n }\n\n /**\n * Returns new color object, when given a color in RGB format\n * @memberOf fabric.Color\n * @param {String} color Color value ex: rgb(0-255,0-255,0-255)\n * @return {fabric.Color}\n */\n fabric.Color.fromRgb = function(color) {\n return Color.fromSource(Color.sourceFromRgb(color));\n };\n\n /**\n * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format\n * @memberOf fabric.Color\n * @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)\n * @return {Array} source\n */\n fabric.Color.sourceFromRgb = function(color) {\n var match = color.match(Color.reRGBa);\n if (match) {\n var r = parseInt(match[1], 10) / (/%$/.test(match[1]) ? 100 : 1) * (/%$/.test(match[1]) ? 255 : 1),\n g = parseInt(match[2], 10) / (/%$/.test(match[2]) ? 100 : 1) * (/%$/.test(match[2]) ? 255 : 1),\n b = parseInt(match[3], 10) / (/%$/.test(match[3]) ? 100 : 1) * (/%$/.test(match[3]) ? 255 : 1);\n\n return [\n parseInt(r, 10),\n parseInt(g, 10),\n parseInt(b, 10),\n match[4] ? parseFloat(match[4]) : 1\n ];\n }\n };\n\n /**\n * Returns new color object, when given a color in RGBA format\n * @static\n * @function\n * @memberOf fabric.Color\n * @param {String} color\n * @return {fabric.Color}\n */\n fabric.Color.fromRgba = Color.fromRgb;\n\n /**\n * Returns new color object, when given a color in HSL format\n * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)\n * @memberOf fabric.Color\n * @return {fabric.Color}\n */\n fabric.Color.fromHsl = function(color) {\n return Color.fromSource(Color.sourceFromHsl(color));\n };\n\n /**\n * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.\n * Adapted from https://github.com/mjijackson\n * @memberOf fabric.Color\n * @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)\n * @return {Array} source\n * @see http://http://www.w3.org/TR/css3-color/#hsl-color\n */\n fabric.Color.sourceFromHsl = function(color) {\n var match = color.match(Color.reHSLa);\n if (!match) {\n return;\n }\n\n var h = (((parseFloat(match[1]) % 360) + 360) % 360) / 360,\n s = parseFloat(match[2]) / (/%$/.test(match[2]) ? 100 : 1),\n l = parseFloat(match[3]) / (/%$/.test(match[3]) ? 100 : 1),\n r, g, b;\n\n if (s === 0) {\n r = g = b = l;\n }\n else {\n var q = l <= 0.5 ? l * (s + 1) : l + s - l * s,\n p = l * 2 - q;\n\n r = hue2rgb(p, q, h + 1 / 3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1 / 3);\n }\n\n return [\n Math.round(r * 255),\n Math.round(g * 255),\n Math.round(b * 255),\n match[4] ? parseFloat(match[4]) : 1\n ];\n };\n\n /**\n * Returns new color object, when given a color in HSLA format\n * @static\n * @function\n * @memberOf fabric.Color\n * @param {String} color\n * @return {fabric.Color}\n */\n fabric.Color.fromHsla = Color.fromHsl;\n\n /**\n * Returns new color object, when given a color in HEX format\n * @static\n * @memberOf fabric.Color\n * @param {String} color Color value ex: FF5555\n * @return {fabric.Color}\n */\n fabric.Color.fromHex = function(color) {\n return Color.fromSource(Color.sourceFromHex(color));\n };\n\n /**\n * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in HEX format\n * @static\n * @memberOf fabric.Color\n * @param {String} color ex: FF5555 or FF5544CC (RGBa)\n * @return {Array} source\n */\n fabric.Color.sourceFromHex = function(color) {\n if (color.match(Color.reHex)) {\n var value = color.slice(color.indexOf('#') + 1),\n isShortNotation = (value.length === 3 || value.length === 4),\n isRGBa = (value.length === 8 || value.length === 4),\n r = isShortNotation ? (value.charAt(0) + value.charAt(0)) : value.substring(0, 2),\n g = isShortNotation ? (value.charAt(1) + value.charAt(1)) : value.substring(2, 4),\n b = isShortNotation ? (value.charAt(2) + value.charAt(2)) : value.substring(4, 6),\n a = isRGBa ? (isShortNotation ? (value.charAt(3) + value.charAt(3)) : value.substring(6, 8)) : 'FF';\n\n return [\n parseInt(r, 16),\n parseInt(g, 16),\n parseInt(b, 16),\n parseFloat((parseInt(a, 16) / 255).toFixed(2))\n ];\n }\n };\n\n /**\n * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])\n * @static\n * @memberOf fabric.Color\n * @param {Array} source\n * @return {fabric.Color}\n */\n fabric.Color.fromSource = function(source) {\n var oColor = new Color();\n oColor.setSource(source);\n return oColor;\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n scaleMap = ['e', 'se', 's', 'sw', 'w', 'nw', 'n', 'ne', 'e'],\n skewMap = ['ns', 'nesw', 'ew', 'nwse'],\n controls = {},\n LEFT = 'left', TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', CENTER = 'center',\n opposite = {\n top: BOTTOM,\n bottom: TOP,\n left: RIGHT,\n right: LEFT,\n center: CENTER,\n }, radiansToDegrees = fabric.util.radiansToDegrees,\n sign = (Math.sign || function(x) { return ((x > 0) - (x < 0)) || +x; });\n\n /**\n * Combine control position and object angle to find the control direction compared\n * to the object center.\n * @param {fabric.Object} fabricObject the fabric object for which we are rendering controls\n * @param {fabric.Control} control the control class\n * @return {Number} 0 - 7 a quadrant number\n */\n function findCornerQuadrant(fabricObject, control) {\n var cornerAngle = fabricObject.angle + radiansToDegrees(Math.atan2(control.y, control.x)) + 360;\n return Math.round((cornerAngle % 360) / 45);\n }\n\n function fireEvent(eventName, options) {\n var target = options.transform.target,\n canvas = target.canvas,\n canvasOptions = fabric.util.object.clone(options);\n canvasOptions.target = target;\n canvas && canvas.fire('object:' + eventName, canvasOptions);\n target.fire(eventName, options);\n }\n\n /**\n * Inspect event and fabricObject properties to understand if the scaling action\n * @param {Event} eventData from the user action\n * @param {fabric.Object} fabricObject the fabric object about to scale\n * @return {Boolean} true if scale is proportional\n */\n function scaleIsProportional(eventData, fabricObject) {\n var canvas = fabricObject.canvas, uniScaleKey = canvas.uniScaleKey,\n uniformIsToggled = eventData[uniScaleKey];\n return (canvas.uniformScaling && !uniformIsToggled) ||\n (!canvas.uniformScaling && uniformIsToggled);\n }\n\n /**\n * Checks if transform is centered\n * @param {Object} transform transform data\n * @return {Boolean} true if transform is centered\n */\n function isTransformCentered(transform) {\n return transform.originX === CENTER && transform.originY === CENTER;\n }\n\n /**\n * Inspect fabricObject to understand if the current scaling action is allowed\n * @param {fabric.Object} fabricObject the fabric object about to scale\n * @param {String} by 'x' or 'y' or ''\n * @param {Boolean} scaleProportionally true if we are trying to scale proportionally\n * @return {Boolean} true if scaling is not allowed at current conditions\n */\n function scalingIsForbidden(fabricObject, by, scaleProportionally) {\n var lockX = fabricObject.lockScalingX, lockY = fabricObject.lockScalingY;\n if (lockX && lockY) {\n return true;\n }\n if (!by && (lockX || lockY) && scaleProportionally) {\n return true;\n }\n if (lockX && by === 'x') {\n return true;\n }\n if (lockY && by === 'y') {\n return true;\n }\n return false;\n }\n\n /**\n * return the correct cursor style for the scale action\n * @param {Event} eventData the javascript event that is causing the scale\n * @param {fabric.Control} control the control that is interested in the action\n * @param {fabric.Object} fabricObject the fabric object that is interested in the action\n * @return {String} a valid css string for the cursor\n */\n function scaleCursorStyleHandler(eventData, control, fabricObject) {\n var notAllowed = 'not-allowed',\n scaleProportionally = scaleIsProportional(eventData, fabricObject),\n by = '';\n if (control.x !== 0 && control.y === 0) {\n by = 'x';\n }\n else if (control.x === 0 && control.y !== 0) {\n by = 'y';\n }\n if (scalingIsForbidden(fabricObject, by, scaleProportionally)) {\n return notAllowed;\n }\n var n = findCornerQuadrant(fabricObject, control);\n return scaleMap[n] + '-resize';\n }\n\n /**\n * return the correct cursor style for the skew action\n * @param {Event} eventData the javascript event that is causing the scale\n * @param {fabric.Control} control the control that is interested in the action\n * @param {fabric.Object} fabricObject the fabric object that is interested in the action\n * @return {String} a valid css string for the cursor\n */\n function skewCursorStyleHandler(eventData, control, fabricObject) {\n var notAllowed = 'not-allowed';\n if (control.x !== 0 && fabricObject.lockSkewingY) {\n return notAllowed;\n }\n if (control.y !== 0 && fabricObject.lockSkewingX) {\n return notAllowed;\n }\n var n = findCornerQuadrant(fabricObject, control) % 4;\n return skewMap[n] + '-resize';\n }\n\n /**\n * Combine skew and scale style handlers to cover fabric standard use case\n * @param {Event} eventData the javascript event that is causing the scale\n * @param {fabric.Control} control the control that is interested in the action\n * @param {fabric.Object} fabricObject the fabric object that is interested in the action\n * @return {String} a valid css string for the cursor\n */\n function scaleSkewCursorStyleHandler(eventData, control, fabricObject) {\n if (eventData[fabricObject.canvas.altActionKey]) {\n return controls.skewCursorStyleHandler(eventData, control, fabricObject);\n }\n return controls.scaleCursorStyleHandler(eventData, control, fabricObject);\n }\n\n /**\n * Inspect event, control and fabricObject to return the correct action name\n * @param {Event} eventData the javascript event that is causing the scale\n * @param {fabric.Control} control the control that is interested in the action\n * @param {fabric.Object} fabricObject the fabric object that is interested in the action\n * @return {String} an action name\n */\n function scaleOrSkewActionName(eventData, control, fabricObject) {\n var isAlternative = eventData[fabricObject.canvas.altActionKey];\n if (control.x === 0) {\n // then is scaleY or skewX\n return isAlternative ? 'skewX' : 'scaleY';\n }\n if (control.y === 0) {\n // then is scaleY or skewX\n return isAlternative ? 'skewY' : 'scaleX';\n }\n }\n\n /**\n * Find the correct style for the control that is used for rotation.\n * this function is very simple and it just take care of not-allowed or standard cursor\n * @param {Event} eventData the javascript event that is causing the scale\n * @param {fabric.Control} control the control that is interested in the action\n * @param {fabric.Object} fabricObject the fabric object that is interested in the action\n * @return {String} a valid css string for the cursor\n */\n function rotationStyleHandler(eventData, control, fabricObject) {\n if (fabricObject.lockRotation) {\n return 'not-allowed';\n }\n return control.cursorStyle;\n }\n\n function commonEventInfo(eventData, transform, x, y) {\n return {\n e: eventData,\n transform: transform,\n pointer: {\n x: x,\n y: y,\n }\n };\n }\n\n /**\n * Wrap an action handler with saving/restoring object position on the transform.\n * this is the code that permits to objects to keep their position while transforming.\n * @param {Function} actionHandler the function to wrap\n * @return {Function} a function with an action handler signature\n */\n function wrapWithFixedAnchor(actionHandler) {\n return function(eventData, transform, x, y) {\n var target = transform.target, centerPoint = target.getCenterPoint(),\n constraint = target.translateToOriginPoint(centerPoint, transform.originX, transform.originY),\n actionPerformed = actionHandler(eventData, transform, x, y);\n target.setPositionByOrigin(constraint, transform.originX, transform.originY);\n return actionPerformed;\n };\n }\n\n /**\n * Wrap an action handler with firing an event if the action is performed\n * @param {Function} actionHandler the function to wrap\n * @return {Function} a function with an action handler signature\n */\n function wrapWithFireEvent(eventName, actionHandler) {\n return function(eventData, transform, x, y) {\n var actionPerformed = actionHandler(eventData, transform, x, y);\n if (actionPerformed) {\n fireEvent(eventName, commonEventInfo(eventData, transform, x, y));\n }\n return actionPerformed;\n };\n }\n\n /**\n * Transforms a point described by x and y in a distance from the top left corner of the object\n * bounding box.\n * @param {Object} transform\n * @param {String} originX\n * @param {String} originY\n * @param {number} x\n * @param {number} y\n * @return {Fabric.Point} the normalized point\n */\n function getLocalPoint(transform, originX, originY, x, y) {\n var target = transform.target,\n control = target.controls[transform.corner],\n zoom = target.canvas.getZoom(),\n padding = target.padding / zoom,\n localPoint = target.toLocalPoint(new fabric.Point(x, y), originX, originY);\n if (localPoint.x >= padding) {\n localPoint.x -= padding;\n }\n if (localPoint.x <= -padding) {\n localPoint.x += padding;\n }\n if (localPoint.y >= padding) {\n localPoint.y -= padding;\n }\n if (localPoint.y <= padding) {\n localPoint.y += padding;\n }\n localPoint.x -= control.offsetX;\n localPoint.y -= control.offsetY;\n return localPoint;\n }\n\n /**\n * Detect if the fabric object is flipped on one side.\n * @param {fabric.Object} target\n * @return {Boolean} true if one flip, but not two.\n */\n function targetHasOneFlip(target) {\n return target.flipX !== target.flipY;\n }\n\n /**\n * Utility function to compensate the scale factor when skew is applied on both axes\n * @private\n */\n function compensateScaleForSkew(target, oppositeSkew, scaleToCompensate, axis, reference) {\n if (target[oppositeSkew] !== 0) {\n var newDim = target._getTransformedDimensions()[axis];\n var newValue = reference / newDim * target[scaleToCompensate];\n target.set(scaleToCompensate, newValue);\n }\n }\n\n /**\n * Action handler for skewing on the X axis\n * @private\n */\n function skewObjectX(eventData, transform, x, y) {\n var target = transform.target,\n // find how big the object would be, if there was no skewX. takes in account scaling\n dimNoSkew = target._getTransformedDimensions(0, target.skewY),\n localPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y),\n // the mouse is in the center of the object, and we want it to stay there.\n // so the object will grow twice as much as the mouse.\n // this makes the skew growth to localPoint * 2 - dimNoSkew.\n totalSkewSize = Math.abs(localPoint.x * 2) - dimNoSkew.x,\n currentSkew = target.skewX, newSkew;\n if (totalSkewSize < 2) {\n // let's make it easy to go back to position 0.\n newSkew = 0;\n }\n else {\n newSkew = radiansToDegrees(\n Math.atan2((totalSkewSize / target.scaleX), (dimNoSkew.y / target.scaleY))\n );\n // now we have to find the sign of the skew.\n // it mostly depend on the origin of transformation.\n if (transform.originX === LEFT && transform.originY === BOTTOM) {\n newSkew = -newSkew;\n }\n if (transform.originX === RIGHT && transform.originY === TOP) {\n newSkew = -newSkew;\n }\n if (targetHasOneFlip(target)) {\n newSkew = -newSkew;\n }\n }\n var hasSkewed = currentSkew !== newSkew;\n if (hasSkewed) {\n var dimBeforeSkewing = target._getTransformedDimensions().y;\n target.set('skewX', newSkew);\n compensateScaleForSkew(target, 'skewY', 'scaleY', 'y', dimBeforeSkewing);\n }\n return hasSkewed;\n }\n\n /**\n * Action handler for skewing on the Y axis\n * @private\n */\n function skewObjectY(eventData, transform, x, y) {\n var target = transform.target,\n // find how big the object would be, if there was no skewX. takes in account scaling\n dimNoSkew = target._getTransformedDimensions(target.skewX, 0),\n localPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y),\n // the mouse is in the center of the object, and we want it to stay there.\n // so the object will grow twice as much as the mouse.\n // this makes the skew growth to localPoint * 2 - dimNoSkew.\n totalSkewSize = Math.abs(localPoint.y * 2) - dimNoSkew.y,\n currentSkew = target.skewY, newSkew;\n if (totalSkewSize < 2) {\n // let's make it easy to go back to position 0.\n newSkew = 0;\n }\n else {\n newSkew = radiansToDegrees(\n Math.atan2((totalSkewSize / target.scaleY), (dimNoSkew.x / target.scaleX))\n );\n // now we have to find the sign of the skew.\n // it mostly depend on the origin of transformation.\n if (transform.originX === LEFT && transform.originY === BOTTOM) {\n newSkew = -newSkew;\n }\n if (transform.originX === RIGHT && transform.originY === TOP) {\n newSkew = -newSkew;\n }\n if (targetHasOneFlip(target)) {\n newSkew = -newSkew;\n }\n }\n var hasSkewed = currentSkew !== newSkew;\n if (hasSkewed) {\n var dimBeforeSkewing = target._getTransformedDimensions().x;\n target.set('skewY', newSkew);\n compensateScaleForSkew(target, 'skewX', 'scaleX', 'x', dimBeforeSkewing);\n }\n return hasSkewed;\n }\n\n /**\n * Wrapped Action handler for skewing on the Y axis, takes care of the\n * skew direction and determine the correct transform origin for the anchor point\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n */\n function skewHandlerX(eventData, transform, x, y) {\n // step1 figure out and change transform origin.\n // if skewX > 0 and originY bottom we anchor on right\n // if skewX > 0 and originY top we anchor on left\n // if skewX < 0 and originY bottom we anchor on left\n // if skewX < 0 and originY top we anchor on right\n // if skewX is 0, we look for mouse position to understand where are we going.\n var target = transform.target, currentSkew = target.skewX, originX, originY = transform.originY;\n if (target.lockSkewingX) {\n return false;\n }\n if (currentSkew === 0) {\n var localPointFromCenter = getLocalPoint(transform, CENTER, CENTER, x, y);\n if (localPointFromCenter.x > 0) {\n // we are pulling right, anchor left;\n originX = LEFT;\n }\n else {\n // we are pulling right, anchor right\n originX = RIGHT;\n }\n }\n else {\n if (currentSkew > 0) {\n originX = originY === TOP ? LEFT : RIGHT;\n }\n if (currentSkew < 0) {\n originX = originY === TOP ? RIGHT : LEFT;\n }\n // is the object flipped on one side only? swap the origin.\n if (targetHasOneFlip(target)) {\n originX = originX === LEFT ? RIGHT : LEFT;\n }\n }\n\n // once we have the origin, we find the anchor point\n transform.originX = originX;\n var finalHandler = wrapWithFireEvent('skewing', wrapWithFixedAnchor(skewObjectX));\n return finalHandler(eventData, transform, x, y);\n }\n\n /**\n * Wrapped Action handler for skewing on the Y axis, takes care of the\n * skew direction and determine the correct transform origin for the anchor point\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n */\n function skewHandlerY(eventData, transform, x, y) {\n // step1 figure out and change transform origin.\n // if skewY > 0 and originX left we anchor on top\n // if skewY > 0 and originX right we anchor on bottom\n // if skewY < 0 and originX left we anchor on bottom\n // if skewY < 0 and originX right we anchor on top\n // if skewY is 0, we look for mouse position to understand where are we going.\n var target = transform.target, currentSkew = target.skewY, originY, originX = transform.originX;\n if (target.lockSkewingY) {\n return false;\n }\n if (currentSkew === 0) {\n var localPointFromCenter = getLocalPoint(transform, CENTER, CENTER, x, y);\n if (localPointFromCenter.y > 0) {\n // we are pulling down, anchor up;\n originY = TOP;\n }\n else {\n // we are pulling up, anchor down\n originY = BOTTOM;\n }\n }\n else {\n if (currentSkew > 0) {\n originY = originX === LEFT ? TOP : BOTTOM;\n }\n if (currentSkew < 0) {\n originY = originX === LEFT ? BOTTOM : TOP;\n }\n // is the object flipped on one side only? swap the origin.\n if (targetHasOneFlip(target)) {\n originY = originY === TOP ? BOTTOM : TOP;\n }\n }\n\n // once we have the origin, we find the anchor point\n transform.originY = originY;\n var finalHandler = wrapWithFireEvent('skewing', wrapWithFixedAnchor(skewObjectY));\n return finalHandler(eventData, transform, x, y);\n }\n\n /**\n * Action handler for rotation and snapping, without anchor point.\n * Needs to be wrapped with `wrapWithFixedAnchor` to be effective\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n * @private\n */\n function rotationWithSnapping(eventData, transform, x, y) {\n var t = transform,\n target = t.target,\n pivotPoint = target.translateToOriginPoint(target.getCenterPoint(), t.originX, t.originY);\n\n if (target.lockRotation) {\n return false;\n }\n\n var lastAngle = Math.atan2(t.ey - pivotPoint.y, t.ex - pivotPoint.x),\n curAngle = Math.atan2(y - pivotPoint.y, x - pivotPoint.x),\n angle = radiansToDegrees(curAngle - lastAngle + t.theta),\n hasRotated = true;\n\n if (target.snapAngle > 0) {\n var snapAngle = target.snapAngle,\n snapThreshold = target.snapThreshold || snapAngle,\n rightAngleLocked = Math.ceil(angle / snapAngle) * snapAngle,\n leftAngleLocked = Math.floor(angle / snapAngle) * snapAngle;\n\n if (Math.abs(angle - leftAngleLocked) < snapThreshold) {\n angle = leftAngleLocked;\n }\n else if (Math.abs(angle - rightAngleLocked) < snapThreshold) {\n angle = rightAngleLocked;\n }\n }\n\n // normalize angle to positive value\n if (angle < 0) {\n angle = 360 + angle;\n }\n angle %= 360;\n\n hasRotated = target.angle !== angle;\n target.angle = angle;\n return hasRotated;\n }\n\n /**\n * Basic scaling logic, reused with different constrain for scaling X,Y, freely or equally.\n * Needs to be wrapped with `wrapWithFixedAnchor` to be effective\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @param {Object} options additional information for scaling\n * @param {String} options.by 'x', 'y', 'equally' or '' to indicate type of scaling\n * @return {Boolean} true if some change happened\n * @private\n */\n function scaleObject(eventData, transform, x, y, options) {\n options = options || {};\n var target = transform.target,\n lockScalingX = target.lockScalingX, lockScalingY = target.lockScalingY,\n by = options.by, newPoint, scaleX, scaleY, dim,\n scaleProportionally = scaleIsProportional(eventData, target),\n forbidScaling = scalingIsForbidden(target, by, scaleProportionally),\n signX, signY, gestureScale = transform.gestureScale;\n\n if (forbidScaling) {\n return false;\n }\n if (gestureScale) {\n scaleX = transform.scaleX * gestureScale;\n scaleY = transform.scaleY * gestureScale;\n }\n else {\n newPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y);\n // use of sign: We use sign to detect change of direction of an action. sign usually change when\n // we cross the origin point with the mouse. So a scale flip for example. There is an issue when scaling\n // by center and scaling using one middle control ( default: mr, mt, ml, mb), the mouse movement can easily\n // cross many time the origin point and flip the object. so we need a way to filter out the noise.\n // This ternary here should be ok to filter out X scaling when we want Y only and vice versa.\n signX = by !== 'y' ? sign(newPoint.x) : 1;\n signY = by !== 'x' ? sign(newPoint.y) : 1;\n if (!transform.signX) {\n transform.signX = signX;\n }\n if (!transform.signY) {\n transform.signY = signY;\n }\n\n if (target.lockScalingFlip &&\n (transform.signX !== signX || transform.signY !== signY)\n ) {\n return false;\n }\n\n dim = target._getTransformedDimensions();\n // missing detection of flip and logic to switch the origin\n if (scaleProportionally && !by) {\n // uniform scaling\n var distance = Math.abs(newPoint.x) + Math.abs(newPoint.y),\n original = transform.original,\n originalDistance = Math.abs(dim.x * original.scaleX / target.scaleX) +\n Math.abs(dim.y * original.scaleY / target.scaleY),\n scale = distance / originalDistance;\n scaleX = original.scaleX * scale;\n scaleY = original.scaleY * scale;\n }\n else {\n scaleX = Math.abs(newPoint.x * target.scaleX / dim.x);\n scaleY = Math.abs(newPoint.y * target.scaleY / dim.y);\n }\n // if we are scaling by center, we need to double the scale\n if (isTransformCentered(transform)) {\n scaleX *= 2;\n scaleY *= 2;\n }\n if (transform.signX !== signX && by !== 'y') {\n transform.originX = opposite[transform.originX];\n scaleX *= -1;\n transform.signX = signX;\n }\n if (transform.signY !== signY && by !== 'x') {\n transform.originY = opposite[transform.originY];\n scaleY *= -1;\n transform.signY = signY;\n }\n }\n // minScale is taken are in the setter.\n var oldScaleX = target.scaleX, oldScaleY = target.scaleY;\n if (!by) {\n !lockScalingX && target.set('scaleX', scaleX);\n !lockScalingY && target.set('scaleY', scaleY);\n }\n else {\n // forbidden cases already handled on top here.\n by === 'x' && target.set('scaleX', scaleX);\n by === 'y' && target.set('scaleY', scaleY);\n }\n return oldScaleX !== target.scaleX || oldScaleY !== target.scaleY;\n }\n\n /**\n * Generic scaling logic, to scale from corners either equally or freely.\n * Needs to be wrapped with `wrapWithFixedAnchor` to be effective\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n */\n function scaleObjectFromCorner(eventData, transform, x, y) {\n return scaleObject(eventData, transform, x, y);\n }\n\n /**\n * Scaling logic for the X axis.\n * Needs to be wrapped with `wrapWithFixedAnchor` to be effective\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n */\n function scaleObjectX(eventData, transform, x, y) {\n return scaleObject(eventData, transform, x, y , { by: 'x' });\n }\n\n /**\n * Scaling logic for the Y axis.\n * Needs to be wrapped with `wrapWithFixedAnchor` to be effective\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n */\n function scaleObjectY(eventData, transform, x, y) {\n return scaleObject(eventData, transform, x, y , { by: 'y' });\n }\n\n /**\n * Composed action handler to either scale Y or skew X\n * Needs to be wrapped with `wrapWithFixedAnchor` to be effective\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n */\n function scalingYOrSkewingX(eventData, transform, x, y) {\n // ok some safety needed here.\n if (eventData[transform.target.canvas.altActionKey]) {\n return controls.skewHandlerX(eventData, transform, x, y);\n }\n return controls.scalingY(eventData, transform, x, y);\n }\n\n /**\n * Composed action handler to either scale X or skew Y\n * Needs to be wrapped with `wrapWithFixedAnchor` to be effective\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n */\n function scalingXOrSkewingY(eventData, transform, x, y) {\n // ok some safety needed here.\n if (eventData[transform.target.canvas.altActionKey]) {\n return controls.skewHandlerY(eventData, transform, x, y);\n }\n return controls.scalingX(eventData, transform, x, y);\n }\n\n /**\n * Action handler to change textbox width\n * Needs to be wrapped with `wrapWithFixedAnchor` to be effective\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if some change happened\n */\n function changeWidth(eventData, transform, x, y) {\n var target = transform.target, localPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y),\n strokePadding = target.strokeWidth / (target.strokeUniform ? target.scaleX : 1),\n multiplier = isTransformCentered(transform) ? 2 : 1,\n oldWidth = target.width,\n newWidth = Math.abs(localPoint.x * multiplier / target.scaleX) - strokePadding;\n target.set('width', Math.max(newWidth, 0));\n return oldWidth !== newWidth;\n }\n\n /**\n * Action handler\n * @private\n * @param {Event} eventData javascript event that is doing the transform\n * @param {Object} transform javascript object containing a series of information around the current transform\n * @param {number} x current mouse x position, canvas normalized\n * @param {number} y current mouse y position, canvas normalized\n * @return {Boolean} true if the translation occurred\n */\n function dragHandler(eventData, transform, x, y) {\n var target = transform.target,\n newLeft = x - transform.offsetX,\n newTop = y - transform.offsetY,\n moveX = !target.get('lockMovementX') && target.left !== newLeft,\n moveY = !target.get('lockMovementY') && target.top !== newTop;\n moveX && target.set('left', newLeft);\n moveY && target.set('top', newTop);\n if (moveX || moveY) {\n fireEvent('moving', commonEventInfo(eventData, transform, x, y));\n }\n return moveX || moveY;\n }\n\n controls.scaleCursorStyleHandler = scaleCursorStyleHandler;\n controls.skewCursorStyleHandler = skewCursorStyleHandler;\n controls.scaleSkewCursorStyleHandler = scaleSkewCursorStyleHandler;\n controls.rotationWithSnapping = wrapWithFireEvent('rotating', wrapWithFixedAnchor(rotationWithSnapping));\n controls.scalingEqually = wrapWithFireEvent('scaling', wrapWithFixedAnchor( scaleObjectFromCorner));\n controls.scalingX = wrapWithFireEvent('scaling', wrapWithFixedAnchor(scaleObjectX));\n controls.scalingY = wrapWithFireEvent('scaling', wrapWithFixedAnchor(scaleObjectY));\n controls.scalingYOrSkewingX = scalingYOrSkewingX;\n controls.scalingXOrSkewingY = scalingXOrSkewingY;\n controls.changeWidth = wrapWithFireEvent('resizing', wrapWithFixedAnchor(changeWidth));\n controls.skewHandlerX = skewHandlerX;\n controls.skewHandlerY = skewHandlerY;\n controls.dragHandler = dragHandler;\n controls.scaleOrSkewActionName = scaleOrSkewActionName;\n controls.rotationStyleHandler = rotationStyleHandler;\n controls.fireEvent = fireEvent;\n controls.wrapWithFixedAnchor = wrapWithFixedAnchor;\n controls.wrapWithFireEvent = wrapWithFireEvent;\n controls.getLocalPoint = getLocalPoint;\n fabric.controlsUtils = controls;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n degreesToRadians = fabric.util.degreesToRadians,\n controls = fabric.controlsUtils;\n\n /**\n * Render a round control, as per fabric features.\n * This function is written to respect object properties like transparentCorners, cornerSize\n * cornerColor, cornerStrokeColor\n * plus the addition of offsetY and offsetX.\n * @param {CanvasRenderingContext2D} ctx context to render on\n * @param {Number} left x coordinate where the control center should be\n * @param {Number} top y coordinate where the control center should be\n * @param {Object} styleOverride override for fabric.Object controls style\n * @param {fabric.Object} fabricObject the fabric object for which we are rendering controls\n */\n function renderCircleControl (ctx, left, top, styleOverride, fabricObject) {\n styleOverride = styleOverride || {};\n var xSize = this.sizeX || styleOverride.cornerSize || fabricObject.cornerSize,\n ySize = this.sizeY || styleOverride.cornerSize || fabricObject.cornerSize,\n transparentCorners = typeof styleOverride.transparentCorners !== 'undefined' ?\n styleOverride.transparentCorners : fabricObject.transparentCorners,\n methodName = transparentCorners ? 'stroke' : 'fill',\n stroke = !transparentCorners && (styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor),\n myLeft = left,\n myTop = top, size;\n ctx.save();\n ctx.fillStyle = styleOverride.cornerColor || fabricObject.cornerColor;\n ctx.strokeStyle = styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor;\n // as soon as fabric react v5, remove ie11, use proper ellipse code.\n if (xSize > ySize) {\n size = xSize;\n ctx.scale(1.0, ySize / xSize);\n myTop = top * xSize / ySize;\n }\n else if (ySize > xSize) {\n size = ySize;\n ctx.scale(xSize / ySize, 1.0);\n myLeft = left * ySize / xSize;\n }\n else {\n size = xSize;\n }\n // this is still wrong\n ctx.lineWidth = 1;\n ctx.beginPath();\n ctx.arc(myLeft, myTop, size / 2, 0, 2 * Math.PI, false);\n ctx[methodName]();\n if (stroke) {\n ctx.stroke();\n }\n ctx.restore();\n }\n\n /**\n * Render a square control, as per fabric features.\n * This function is written to respect object properties like transparentCorners, cornerSize\n * cornerColor, cornerStrokeColor\n * plus the addition of offsetY and offsetX.\n * @param {CanvasRenderingContext2D} ctx context to render on\n * @param {Number} left x coordinate where the control center should be\n * @param {Number} top y coordinate where the control center should be\n * @param {Object} styleOverride override for fabric.Object controls style\n * @param {fabric.Object} fabricObject the fabric object for which we are rendering controls\n */\n function renderSquareControl(ctx, left, top, styleOverride, fabricObject) {\n styleOverride = styleOverride || {};\n var xSize = this.sizeX || styleOverride.cornerSize || fabricObject.cornerSize,\n ySize = this.sizeY || styleOverride.cornerSize || fabricObject.cornerSize,\n transparentCorners = typeof styleOverride.transparentCorners !== 'undefined' ?\n styleOverride.transparentCorners : fabricObject.transparentCorners,\n methodName = transparentCorners ? 'stroke' : 'fill',\n stroke = !transparentCorners && (\n styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor\n ), xSizeBy2 = xSize / 2, ySizeBy2 = ySize / 2;\n ctx.save();\n ctx.fillStyle = styleOverride.cornerColor || fabricObject.cornerColor;\n ctx.strokeStyle = styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor;\n // this is still wrong\n ctx.lineWidth = 1;\n ctx.translate(left, top);\n ctx.rotate(degreesToRadians(fabricObject.angle));\n // this does not work, and fixed with ( && ) does not make sense.\n // to have real transparent corners we need the controls on upperCanvas\n // transparentCorners || ctx.clearRect(-xSizeBy2, -ySizeBy2, xSize, ySize);\n ctx[methodName + 'Rect'](-xSizeBy2, -ySizeBy2, xSize, ySize);\n if (stroke) {\n ctx.strokeRect(-xSizeBy2, -ySizeBy2, xSize, ySize);\n }\n ctx.restore();\n }\n\n controls.renderCircleControl = renderCircleControl;\n controls.renderSquareControl = renderSquareControl;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { });\n\n function Control(options) {\n for (var i in options) {\n this[i] = options[i];\n }\n }\n\n fabric.Control = Control;\n\n fabric.Control.prototype = /** @lends fabric.Control.prototype */ {\n\n /**\n * keep track of control visibility.\n * mainly for backward compatibility.\n * if you do not want to see a control, you can remove it\n * from the controlset.\n * @type {Boolean}\n * @default true\n */\n visible: true,\n\n /**\n * Name of the action that the control will likely execute.\n * This is optional. FabricJS uses to identify what the user is doing for some\n * extra optimizations. If you are writing a custom control and you want to know\n * somewhere else in the code what is going on, you can use this string here.\n * you can also provide a custom getActionName if your control run multiple actions\n * depending on some external state.\n * default to scale since is the most common, used on 4 corners by default\n * @type {String}\n * @default 'scale'\n */\n actionName: 'scale',\n\n /**\n * Drawing angle of the control.\n * NOT used for now, but name marked as needed for internal logic\n * example: to reuse the same drawing function for different rotated controls\n * @type {Number}\n * @default 0\n */\n angle: 0,\n\n /**\n * Relative position of the control. X\n * 0,0 is the center of the Object, while -0.5 (left) or 0.5 (right) are the extremities\n * of the bounding box.\n * @type {Number}\n * @default 0\n */\n x: 0,\n\n /**\n * Relative position of the control. Y\n * 0,0 is the center of the Object, while -0.5 (top) or 0.5 (bottom) are the extremities\n * of the bounding box.\n * @type {Number}\n * @default 0\n */\n y: 0,\n\n /**\n * Horizontal offset of the control from the defined position. In pixels\n * Positive offset moves the control to the right, negative to the left.\n * It used when you want to have position of control that does not scale with\n * the bounding box. Example: rotation control is placed at x:0, y: 0.5 on\n * the boundindbox, with an offset of 30 pixels vertically. Those 30 pixels will\n * stay 30 pixels no matter how the object is big. Another example is having 2\n * controls in the corner, that stay in the same position when the object scale.\n * of the bounding box.\n * @type {Number}\n * @default 0\n */\n offsetX: 0,\n\n /**\n * Vertical offset of the control from the defined position. In pixels\n * Positive offset moves the control to the bottom, negative to the top.\n * @type {Number}\n * @default 0\n */\n offsetY: 0,\n\n /**\n * Sets the length of the control. If null, defaults to object's cornerSize.\n * Expects both sizeX and sizeY to be set when set.\n * @type {?Number}\n * @default null\n */\n sizeX: null,\n\n /**\n * Sets the height of the control. If null, defaults to object's cornerSize.\n * Expects both sizeX and sizeY to be set when set.\n * @type {?Number}\n * @default null\n */\n sizeY: null,\n\n /**\n * Sets the length of the touch area of the control. If null, defaults to object's touchCornerSize.\n * Expects both touchSizeX and touchSizeY to be set when set.\n * @type {?Number}\n * @default null\n */\n touchSizeX: null,\n\n /**\n * Sets the height of the touch area of the control. If null, defaults to object's touchCornerSize.\n * Expects both touchSizeX and touchSizeY to be set when set.\n * @type {?Number}\n * @default null\n */\n touchSizeY: null,\n\n /**\n * Css cursor style to display when the control is hovered.\n * if the method `cursorStyleHandler` is provided, this property is ignored.\n * @type {String}\n * @default 'crosshair'\n */\n cursorStyle: 'crosshair',\n\n /**\n * If controls has an offsetY or offsetX, draw a line that connects\n * the control to the bounding box\n * @type {Boolean}\n * @default false\n */\n withConnection: false,\n\n /**\n * The control actionHandler, provide one to handle action ( control being moved )\n * @param {Event} eventData the native mouse event\n * @param {Object} transformData properties of the current transform\n * @param {Number} x x position of the cursor\n * @param {Number} y y position of the cursor\n * @return {Boolean} true if the action/event modified the object\n */\n actionHandler: function(/* eventData, transformData, x, y */) { },\n\n /**\n * The control handler for mouse down, provide one to handle mouse down on control\n * @param {Event} eventData the native mouse event\n * @param {Object} transformData properties of the current transform\n * @param {Number} x x position of the cursor\n * @param {Number} y y position of the cursor\n * @return {Boolean} true if the action/event modified the object\n */\n mouseDownHandler: function(/* eventData, transformData, x, y */) { },\n\n /**\n * The control mouseUpHandler, provide one to handle an effect on mouse up.\n * @param {Event} eventData the native mouse event\n * @param {Object} transformData properties of the current transform\n * @param {Number} x x position of the cursor\n * @param {Number} y y position of the cursor\n * @return {Boolean} true if the action/event modified the object\n */\n mouseUpHandler: function(/* eventData, transformData, x, y */) { },\n\n /**\n * Returns control actionHandler\n * @param {Event} eventData the native mouse event\n * @param {fabric.Object} fabricObject on which the control is displayed\n * @param {fabric.Control} control control for which the action handler is being asked\n * @return {Function} the action handler\n */\n getActionHandler: function(/* eventData, fabricObject, control */) {\n return this.actionHandler;\n },\n\n /**\n * Returns control mouseDown handler\n * @param {Event} eventData the native mouse event\n * @param {fabric.Object} fabricObject on which the control is displayed\n * @param {fabric.Control} control control for which the action handler is being asked\n * @return {Function} the action handler\n */\n getMouseDownHandler: function(/* eventData, fabricObject, control */) {\n return this.mouseDownHandler;\n },\n\n /**\n * Returns control mouseUp handler\n * @param {Event} eventData the native mouse event\n * @param {fabric.Object} fabricObject on which the control is displayed\n * @param {fabric.Control} control control for which the action handler is being asked\n * @return {Function} the action handler\n */\n getMouseUpHandler: function(/* eventData, fabricObject, control */) {\n return this.mouseUpHandler;\n },\n\n /**\n * Returns control cursorStyle for css using cursorStyle. If you need a more elaborate\n * function you can pass one in the constructor\n * the cursorStyle property\n * @param {Event} eventData the native mouse event\n * @param {fabric.Control} control the current control ( likely this)\n * @param {fabric.Object} object on which the control is displayed\n * @return {String}\n */\n cursorStyleHandler: function(eventData, control /* fabricObject */) {\n return control.cursorStyle;\n },\n\n /**\n * Returns the action name. The basic implementation just return the actionName property.\n * @param {Event} eventData the native mouse event\n * @param {fabric.Control} control the current control ( likely this)\n * @param {fabric.Object} object on which the control is displayed\n * @return {String}\n */\n getActionName: function(eventData, control /* fabricObject */) {\n return control.actionName;\n },\n\n /**\n * Returns controls visibility\n * @param {fabric.Object} object on which the control is displayed\n * @param {String} controlKey key where the control is memorized on the\n * @return {Boolean}\n */\n getVisibility: function(fabricObject, controlKey) {\n var objectVisibility = fabricObject._controlsVisibility;\n if (objectVisibility && typeof objectVisibility[controlKey] !== 'undefined') {\n return objectVisibility[controlKey];\n }\n return this.visible;\n },\n\n /**\n * Sets controls visibility\n * @param {Boolean} visibility for the object\n * @return {Void}\n */\n setVisibility: function(visibility /* name, fabricObject */) {\n this.visible = visibility;\n },\n\n\n positionHandler: function(dim, finalMatrix /*, fabricObject, currentControl */) {\n var point = fabric.util.transformPoint({\n x: this.x * dim.x + this.offsetX,\n y: this.y * dim.y + this.offsetY }, finalMatrix);\n return point;\n },\n\n /**\n * Returns the coords for this control based on object values.\n * @param {Number} objectAngle angle from the fabric object holding the control\n * @param {Number} objectCornerSize cornerSize from the fabric object holding the control (or touchCornerSize if\n * isTouch is true)\n * @param {Number} centerX x coordinate where the control center should be\n * @param {Number} centerY y coordinate where the control center should be\n * @param {boolean} isTouch true if touch corner, false if normal corner\n */\n calcCornerCoords: function(objectAngle, objectCornerSize, centerX, centerY, isTouch) {\n var cosHalfOffset,\n sinHalfOffset,\n cosHalfOffsetComp,\n sinHalfOffsetComp,\n xSize = (isTouch) ? this.touchSizeX : this.sizeX,\n ySize = (isTouch) ? this.touchSizeY : this.sizeY;\n if (xSize && ySize && xSize !== ySize) {\n // handle rectangular corners\n var controlTriangleAngle = Math.atan2(ySize, xSize);\n var cornerHypotenuse = Math.sqrt(xSize * xSize + ySize * ySize) / 2;\n var newTheta = controlTriangleAngle - fabric.util.degreesToRadians(objectAngle);\n var newThetaComp = Math.PI / 2 - controlTriangleAngle - fabric.util.degreesToRadians(objectAngle);\n cosHalfOffset = cornerHypotenuse * fabric.util.cos(newTheta);\n sinHalfOffset = cornerHypotenuse * fabric.util.sin(newTheta);\n // use complementary angle for two corners\n cosHalfOffsetComp = cornerHypotenuse * fabric.util.cos(newThetaComp);\n sinHalfOffsetComp = cornerHypotenuse * fabric.util.sin(newThetaComp);\n }\n else {\n // handle square corners\n // use default object corner size unless size is defined\n var cornerSize = (xSize && ySize) ? xSize : objectCornerSize;\n /* 0.7071067812 stands for sqrt(2)/2 */\n cornerHypotenuse = cornerSize * 0.7071067812;\n // complementary angles are equal since they're both 45 degrees\n var newTheta = fabric.util.degreesToRadians(45 - objectAngle);\n cosHalfOffset = cosHalfOffsetComp = cornerHypotenuse * fabric.util.cos(newTheta);\n sinHalfOffset = sinHalfOffsetComp = cornerHypotenuse * fabric.util.sin(newTheta);\n }\n\n return {\n tl: {\n x: centerX - sinHalfOffsetComp,\n y: centerY - cosHalfOffsetComp,\n },\n tr: {\n x: centerX + cosHalfOffset,\n y: centerY - sinHalfOffset,\n },\n bl: {\n x: centerX - cosHalfOffset,\n y: centerY + sinHalfOffset,\n },\n br: {\n x: centerX + sinHalfOffsetComp,\n y: centerY + cosHalfOffsetComp,\n },\n };\n },\n\n /**\n * Render function for the control.\n * When this function runs the context is unscaled. unrotate. Just retina scaled.\n * all the functions will have to translate to the point left,top before starting Drawing\n * if they want to draw a control where the position is detected.\n * left and top are the result of the positionHandler function\n * @param {RenderingContext2D} ctx the context where the control will be drawn\n * @param {Number} left position of the canvas where we are about to render the control.\n * @param {Number} top position of the canvas where we are about to render the control.\n * @param {Object} styleOverride\n * @param {fabric.Object} fabricObject the object where the control is about to be rendered\n */\n render: function(ctx, left, top, styleOverride, fabricObject) {\n styleOverride = styleOverride || {};\n switch (styleOverride.cornerStyle || fabricObject.cornerStyle) {\n case 'circle':\n fabric.controlsUtils.renderCircleControl.call(this, ctx, left, top, styleOverride, fabricObject);\n break;\n default:\n fabric.controlsUtils.renderSquareControl.call(this, ctx, left, top, styleOverride, fabricObject);\n }\n },\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function() {\n\n /* _FROM_SVG_START_ */\n function getColorStop(el, multiplier) {\n var style = el.getAttribute('style'),\n offset = el.getAttribute('offset') || 0,\n color, colorAlpha, opacity, i;\n\n // convert percents to absolute values\n offset = parseFloat(offset) / (/%$/.test(offset) ? 100 : 1);\n offset = offset < 0 ? 0 : offset > 1 ? 1 : offset;\n if (style) {\n var keyValuePairs = style.split(/\\s*;\\s*/);\n\n if (keyValuePairs[keyValuePairs.length - 1] === '') {\n keyValuePairs.pop();\n }\n\n for (i = keyValuePairs.length; i--; ) {\n\n var split = keyValuePairs[i].split(/\\s*:\\s*/),\n key = split[0].trim(),\n value = split[1].trim();\n\n if (key === 'stop-color') {\n color = value;\n }\n else if (key === 'stop-opacity') {\n opacity = value;\n }\n }\n }\n\n if (!color) {\n color = el.getAttribute('stop-color') || 'rgb(0,0,0)';\n }\n if (!opacity) {\n opacity = el.getAttribute('stop-opacity');\n }\n\n color = new fabric.Color(color);\n colorAlpha = color.getAlpha();\n opacity = isNaN(parseFloat(opacity)) ? 1 : parseFloat(opacity);\n opacity *= colorAlpha * multiplier;\n\n return {\n offset: offset,\n color: color.toRgb(),\n opacity: opacity\n };\n }\n\n function getLinearCoords(el) {\n return {\n x1: el.getAttribute('x1') || 0,\n y1: el.getAttribute('y1') || 0,\n x2: el.getAttribute('x2') || '100%',\n y2: el.getAttribute('y2') || 0\n };\n }\n\n function getRadialCoords(el) {\n return {\n x1: el.getAttribute('fx') || el.getAttribute('cx') || '50%',\n y1: el.getAttribute('fy') || el.getAttribute('cy') || '50%',\n r1: 0,\n x2: el.getAttribute('cx') || '50%',\n y2: el.getAttribute('cy') || '50%',\n r2: el.getAttribute('r') || '50%'\n };\n }\n /* _FROM_SVG_END_ */\n\n var clone = fabric.util.object.clone;\n\n /**\n * Gradient class\n * @class fabric.Gradient\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#gradients}\n * @see {@link fabric.Gradient#initialize} for constructor definition\n */\n fabric.Gradient = fabric.util.createClass(/** @lends fabric.Gradient.prototype */ {\n\n /**\n * Horizontal offset for aligning gradients coming from SVG when outside pathgroups\n * @type Number\n * @default 0\n */\n offsetX: 0,\n\n /**\n * Vertical offset for aligning gradients coming from SVG when outside pathgroups\n * @type Number\n * @default 0\n */\n offsetY: 0,\n\n /**\n * A transform matrix to apply to the gradient before painting.\n * Imported from svg gradients, is not applied with the current transform in the center.\n * Before this transform is applied, the origin point is at the top left corner of the object\n * plus the addition of offsetY and offsetX.\n * @type Number[]\n * @default null\n */\n gradientTransform: null,\n\n /**\n * coordinates units for coords.\n * If `pixels`, the number of coords are in the same unit of width / height.\n * If set as `percentage` the coords are still a number, but 1 means 100% of width\n * for the X and 100% of the height for the y. It can be bigger than 1 and negative.\n * allowed values pixels or percentage.\n * @type String\n * @default 'pixels'\n */\n gradientUnits: 'pixels',\n\n /**\n * Gradient type linear or radial\n * @type String\n * @default 'pixels'\n */\n type: 'linear',\n\n /**\n * Constructor\n * @param {Object} options Options object with type, coords, gradientUnits and colorStops\n * @param {Object} [options.type] gradient type linear or radial\n * @param {Object} [options.gradientUnits] gradient units\n * @param {Object} [options.offsetX] SVG import compatibility\n * @param {Object} [options.offsetY] SVG import compatibility\n * @param {Object[]} options.colorStops contains the colorstops.\n * @param {Object} options.coords contains the coords of the gradient\n * @param {Number} [options.coords.x1] X coordiante of the first point for linear or of the focal point for radial\n * @param {Number} [options.coords.y1] Y coordiante of the first point for linear or of the focal point for radial\n * @param {Number} [options.coords.x2] X coordiante of the second point for linear or of the center point for radial\n * @param {Number} [options.coords.y2] Y coordiante of the second point for linear or of the center point for radial\n * @param {Number} [options.coords.r1] only for radial gradient, radius of the inner circle\n * @param {Number} [options.coords.r2] only for radial gradient, radius of the external circle\n * @return {fabric.Gradient} thisArg\n */\n initialize: function(options) {\n options || (options = { });\n options.coords || (options.coords = { });\n\n var coords, _this = this;\n\n // sets everything, then coords and colorstops get sets again\n Object.keys(options).forEach(function(option) {\n _this[option] = options[option];\n });\n\n if (this.id) {\n this.id += '_' + fabric.Object.__uid++;\n }\n else {\n this.id = fabric.Object.__uid++;\n }\n\n coords = {\n x1: options.coords.x1 || 0,\n y1: options.coords.y1 || 0,\n x2: options.coords.x2 || 0,\n y2: options.coords.y2 || 0\n };\n\n if (this.type === 'radial') {\n coords.r1 = options.coords.r1 || 0;\n coords.r2 = options.coords.r2 || 0;\n }\n\n this.coords = coords;\n this.colorStops = options.colorStops.slice();\n },\n\n /**\n * Adds another colorStop\n * @param {Object} colorStop Object with offset and color\n * @return {fabric.Gradient} thisArg\n */\n addColorStop: function(colorStops) {\n for (var position in colorStops) {\n var color = new fabric.Color(colorStops[position]);\n this.colorStops.push({\n offset: parseFloat(position),\n color: color.toRgb(),\n opacity: color.getAlpha()\n });\n }\n return this;\n },\n\n /**\n * Returns object representation of a gradient\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object}\n */\n toObject: function(propertiesToInclude) {\n var object = {\n type: this.type,\n coords: this.coords,\n colorStops: this.colorStops,\n offsetX: this.offsetX,\n offsetY: this.offsetY,\n gradientUnits: this.gradientUnits,\n gradientTransform: this.gradientTransform ? this.gradientTransform.concat() : this.gradientTransform\n };\n fabric.util.populateWithProperties(this, object, propertiesToInclude);\n\n return object;\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns SVG representation of an gradient\n * @param {Object} object Object to create a gradient for\n * @return {String} SVG representation of an gradient (linear/radial)\n */\n toSVG: function(object, options) {\n var coords = clone(this.coords, true), i, len, options = options || {},\n markup, commonAttributes, colorStops = clone(this.colorStops, true),\n needsSwap = coords.r1 > coords.r2,\n transform = this.gradientTransform ? this.gradientTransform.concat() : fabric.iMatrix.concat(),\n offsetX = -this.offsetX, offsetY = -this.offsetY,\n withViewport = !!options.additionalTransform,\n gradientUnits = this.gradientUnits === 'pixels' ? 'userSpaceOnUse' : 'objectBoundingBox';\n // colorStops must be sorted ascending\n colorStops.sort(function(a, b) {\n return a.offset - b.offset;\n });\n\n if (gradientUnits === 'objectBoundingBox') {\n offsetX /= object.width;\n offsetY /= object.height;\n }\n else {\n offsetX += object.width / 2;\n offsetY += object.height / 2;\n }\n if (object.type === 'path' && this.gradientUnits !== 'percentage') {\n offsetX -= object.pathOffset.x;\n offsetY -= object.pathOffset.y;\n }\n\n\n transform[4] -= offsetX;\n transform[5] -= offsetY;\n\n commonAttributes = 'id=\"SVGID_' + this.id +\n '\" gradientUnits=\"' + gradientUnits + '\"';\n commonAttributes += ' gradientTransform=\"' + (withViewport ?\n options.additionalTransform + ' ' : '') + fabric.util.matrixToSVG(transform) + '\" ';\n\n if (this.type === 'linear') {\n markup = [\n '\\n'\n ];\n }\n else if (this.type === 'radial') {\n // svg radial gradient has just 1 radius. the biggest.\n markup = [\n '\\n'\n ];\n }\n\n if (this.type === 'radial') {\n if (needsSwap) {\n // svg goes from internal to external radius. if radius are inverted, swap color stops.\n colorStops = colorStops.concat();\n colorStops.reverse();\n for (i = 0, len = colorStops.length; i < len; i++) {\n colorStops[i].offset = 1 - colorStops[i].offset;\n }\n }\n var minRadius = Math.min(coords.r1, coords.r2);\n if (minRadius > 0) {\n // i have to shift all colorStops and add new one in 0.\n var maxRadius = Math.max(coords.r1, coords.r2),\n percentageShift = minRadius / maxRadius;\n for (i = 0, len = colorStops.length; i < len; i++) {\n colorStops[i].offset += percentageShift * (1 - colorStops[i].offset);\n }\n }\n }\n\n for (i = 0, len = colorStops.length; i < len; i++) {\n var colorStop = colorStops[i];\n markup.push(\n '\\n'\n );\n }\n\n markup.push((this.type === 'linear' ? '\\n' : '\\n'));\n\n return markup.join('');\n },\n /* _TO_SVG_END_ */\n\n /**\n * Returns an instance of CanvasGradient\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @return {CanvasGradient}\n */\n toLive: function(ctx) {\n var gradient, coords = fabric.util.object.clone(this.coords), i, len;\n\n if (!this.type) {\n return;\n }\n\n if (this.type === 'linear') {\n gradient = ctx.createLinearGradient(\n coords.x1, coords.y1, coords.x2, coords.y2);\n }\n else if (this.type === 'radial') {\n gradient = ctx.createRadialGradient(\n coords.x1, coords.y1, coords.r1, coords.x2, coords.y2, coords.r2);\n }\n\n for (i = 0, len = this.colorStops.length; i < len; i++) {\n var color = this.colorStops[i].color,\n opacity = this.colorStops[i].opacity,\n offset = this.colorStops[i].offset;\n\n if (typeof opacity !== 'undefined') {\n color = new fabric.Color(color).setAlpha(opacity).toRgba();\n }\n gradient.addColorStop(offset, color);\n }\n\n return gradient;\n }\n });\n\n fabric.util.object.extend(fabric.Gradient, {\n\n /* _FROM_SVG_START_ */\n /**\n * Returns {@link fabric.Gradient} instance from an SVG element\n * @static\n * @memberOf fabric.Gradient\n * @param {SVGGradientElement} el SVG gradient element\n * @param {fabric.Object} instance\n * @param {String} opacityAttr A fill-opacity or stroke-opacity attribute to multiply to each stop's opacity.\n * @param {Object} svgOptions an object containing the size of the SVG in order to parse correctly gradients\n * that uses gradientUnits as 'userSpaceOnUse' and percentages.\n * @param {Object.number} viewBoxWidth width part of the viewBox attribute on svg\n * @param {Object.number} viewBoxHeight height part of the viewBox attribute on svg\n * @param {Object.number} width width part of the svg tag if viewBox is not specified\n * @param {Object.number} height height part of the svg tag if viewBox is not specified\n * @return {fabric.Gradient} Gradient instance\n * @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement\n * @see http://www.w3.org/TR/SVG/pservers.html#RadialGradientElement\n */\n fromElement: function(el, instance, opacityAttr, svgOptions) {\n /**\n * @example:\n *\n * \n * \n * \n * \n *\n * OR\n *\n * \n * \n * \n * \n *\n * OR\n *\n * \n * \n * \n * \n * \n *\n * OR\n *\n * \n * \n * \n * \n * \n *\n */\n\n var multiplier = parseFloat(opacityAttr) / (/%$/.test(opacityAttr) ? 100 : 1);\n multiplier = multiplier < 0 ? 0 : multiplier > 1 ? 1 : multiplier;\n if (isNaN(multiplier)) {\n multiplier = 1;\n }\n\n var colorStopEls = el.getElementsByTagName('stop'),\n type,\n gradientUnits = el.getAttribute('gradientUnits') === 'userSpaceOnUse' ?\n 'pixels' : 'percentage',\n gradientTransform = el.getAttribute('gradientTransform') || '',\n colorStops = [],\n coords, i, offsetX = 0, offsetY = 0,\n transformMatrix;\n if (el.nodeName === 'linearGradient' || el.nodeName === 'LINEARGRADIENT') {\n type = 'linear';\n coords = getLinearCoords(el);\n }\n else {\n type = 'radial';\n coords = getRadialCoords(el);\n }\n\n for (i = colorStopEls.length; i--; ) {\n colorStops.push(getColorStop(colorStopEls[i], multiplier));\n }\n\n transformMatrix = fabric.parseTransformAttribute(gradientTransform);\n\n __convertPercentUnitsToValues(instance, coords, svgOptions, gradientUnits);\n\n if (gradientUnits === 'pixels') {\n offsetX = -instance.left;\n offsetY = -instance.top;\n }\n\n var gradient = new fabric.Gradient({\n id: el.getAttribute('id'),\n type: type,\n coords: coords,\n colorStops: colorStops,\n gradientUnits: gradientUnits,\n gradientTransform: transformMatrix,\n offsetX: offsetX,\n offsetY: offsetY,\n });\n\n return gradient;\n }\n /* _FROM_SVG_END_ */\n });\n\n /**\n * @private\n */\n function __convertPercentUnitsToValues(instance, options, svgOptions, gradientUnits) {\n var propValue, finalValue;\n Object.keys(options).forEach(function(prop) {\n propValue = options[prop];\n if (propValue === 'Infinity') {\n finalValue = 1;\n }\n else if (propValue === '-Infinity') {\n finalValue = 0;\n }\n else {\n finalValue = parseFloat(options[prop], 10);\n if (typeof propValue === 'string' && /^(\\d+\\.\\d+)%|(\\d+)%$/.test(propValue)) {\n finalValue *= 0.01;\n if (gradientUnits === 'pixels') {\n // then we need to fix those percentages here in svg parsing\n if (prop === 'x1' || prop === 'x2' || prop === 'r2') {\n finalValue *= svgOptions.viewBoxWidth || svgOptions.width;\n }\n if (prop === 'y1' || prop === 'y2') {\n finalValue *= svgOptions.viewBoxHeight || svgOptions.height;\n }\n }\n }\n }\n options[prop] = finalValue;\n });\n }\n})();\n\n\n(function() {\n\n 'use strict';\n\n var toFixed = fabric.util.toFixed;\n\n /**\n * Pattern class\n * @class fabric.Pattern\n * @see {@link http://fabricjs.com/patterns|Pattern demo}\n * @see {@link http://fabricjs.com/dynamic-patterns|DynamicPattern demo}\n * @see {@link fabric.Pattern#initialize} for constructor definition\n */\n\n\n fabric.Pattern = fabric.util.createClass(/** @lends fabric.Pattern.prototype */ {\n\n /**\n * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)\n * @type String\n * @default\n */\n repeat: 'repeat',\n\n /**\n * Pattern horizontal offset from object's left/top corner\n * @type Number\n * @default\n */\n offsetX: 0,\n\n /**\n * Pattern vertical offset from object's left/top corner\n * @type Number\n * @default\n */\n offsetY: 0,\n\n /**\n * crossOrigin value (one of \"\", \"anonymous\", \"use-credentials\")\n * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes\n * @type String\n * @default\n */\n crossOrigin: '',\n\n /**\n * transform matrix to change the pattern, imported from svgs.\n * @type Array\n * @default\n */\n patternTransform: null,\n\n /**\n * Constructor\n * @param {Object} [options] Options object\n * @param {Function} [callback] function to invoke after callback init.\n * @return {fabric.Pattern} thisArg\n */\n initialize: function(options, callback) {\n options || (options = { });\n\n this.id = fabric.Object.__uid++;\n this.setOptions(options);\n if (!options.source || (options.source && typeof options.source !== 'string')) {\n callback && callback(this);\n return;\n }\n else {\n // img src string\n var _this = this;\n this.source = fabric.util.createImage();\n fabric.util.loadImage(options.source, function(img, isError) {\n _this.source = img;\n callback && callback(_this, isError);\n }, null, this.crossOrigin);\n }\n },\n\n /**\n * Returns object representation of a pattern\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} Object representation of a pattern instance\n */\n toObject: function(propertiesToInclude) {\n var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,\n source, object;\n\n // element\n if (typeof this.source.src === 'string') {\n source = this.source.src;\n }\n // element\n else if (typeof this.source === 'object' && this.source.toDataURL) {\n source = this.source.toDataURL();\n }\n\n object = {\n type: 'pattern',\n source: source,\n repeat: this.repeat,\n crossOrigin: this.crossOrigin,\n offsetX: toFixed(this.offsetX, NUM_FRACTION_DIGITS),\n offsetY: toFixed(this.offsetY, NUM_FRACTION_DIGITS),\n patternTransform: this.patternTransform ? this.patternTransform.concat() : null\n };\n fabric.util.populateWithProperties(this, object, propertiesToInclude);\n\n return object;\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns SVG representation of a pattern\n * @param {fabric.Object} object\n * @return {String} SVG representation of a pattern\n */\n toSVG: function(object) {\n var patternSource = typeof this.source === 'function' ? this.source() : this.source,\n patternWidth = patternSource.width / object.width,\n patternHeight = patternSource.height / object.height,\n patternOffsetX = this.offsetX / object.width,\n patternOffsetY = this.offsetY / object.height,\n patternImgSrc = '';\n if (this.repeat === 'repeat-x' || this.repeat === 'no-repeat') {\n patternHeight = 1;\n if (patternOffsetY) {\n patternHeight += Math.abs(patternOffsetY);\n }\n }\n if (this.repeat === 'repeat-y' || this.repeat === 'no-repeat') {\n patternWidth = 1;\n if (patternOffsetX) {\n patternWidth += Math.abs(patternOffsetX);\n }\n\n }\n if (patternSource.src) {\n patternImgSrc = patternSource.src;\n }\n else if (patternSource.toDataURL) {\n patternImgSrc = patternSource.toDataURL();\n }\n\n return '\\n' +\n '\\n' +\n '\\n';\n },\n /* _TO_SVG_END_ */\n\n setOptions: function(options) {\n for (var prop in options) {\n this[prop] = options[prop];\n }\n },\n\n /**\n * Returns an instance of CanvasPattern\n * @param {CanvasRenderingContext2D} ctx Context to create pattern\n * @return {CanvasPattern}\n */\n toLive: function(ctx) {\n var source = this.source;\n // if the image failed to load, return, and allow rest to continue loading\n if (!source) {\n return '';\n }\n\n // if an image\n if (typeof source.src !== 'undefined') {\n if (!source.complete) {\n return '';\n }\n if (source.naturalWidth === 0 || source.naturalHeight === 0) {\n return '';\n }\n }\n return ctx.createPattern(source, this.repeat);\n }\n });\n})();\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n toFixed = fabric.util.toFixed;\n\n if (fabric.Shadow) {\n fabric.warn('fabric.Shadow is already defined.');\n return;\n }\n\n /**\n * Shadow class\n * @class fabric.Shadow\n * @see {@link http://fabricjs.com/shadows|Shadow demo}\n * @see {@link fabric.Shadow#initialize} for constructor definition\n */\n fabric.Shadow = fabric.util.createClass(/** @lends fabric.Shadow.prototype */ {\n\n /**\n * Shadow color\n * @type String\n * @default\n */\n color: 'rgb(0,0,0)',\n\n /**\n * Shadow blur\n * @type Number\n */\n blur: 0,\n\n /**\n * Shadow horizontal offset\n * @type Number\n * @default\n */\n offsetX: 0,\n\n /**\n * Shadow vertical offset\n * @type Number\n * @default\n */\n offsetY: 0,\n\n /**\n * Whether the shadow should affect stroke operations\n * @type Boolean\n * @default\n */\n affectStroke: false,\n\n /**\n * Indicates whether toObject should include default values\n * @type Boolean\n * @default\n */\n includeDefaultValues: true,\n\n /**\n * When `false`, the shadow will scale with the object.\n * When `true`, the shadow's offsetX, offsetY, and blur will not be affected by the object's scale.\n * default to false\n * @type Boolean\n * @default\n */\n nonScaling: false,\n\n /**\n * Constructor\n * @param {Object|String} [options] Options object with any of color, blur, offsetX, offsetY properties or string (e.g. \"rgba(0,0,0,0.2) 2px 2px 10px\")\n * @return {fabric.Shadow} thisArg\n */\n initialize: function(options) {\n\n if (typeof options === 'string') {\n options = this._parseShadow(options);\n }\n\n for (var prop in options) {\n this[prop] = options[prop];\n }\n\n this.id = fabric.Object.__uid++;\n },\n\n /**\n * @private\n * @param {String} shadow Shadow value to parse\n * @return {Object} Shadow object with color, offsetX, offsetY and blur\n */\n _parseShadow: function(shadow) {\n var shadowStr = shadow.trim(),\n offsetsAndBlur = fabric.Shadow.reOffsetsAndBlur.exec(shadowStr) || [],\n color = shadowStr.replace(fabric.Shadow.reOffsetsAndBlur, '') || 'rgb(0,0,0)';\n\n return {\n color: color.trim(),\n offsetX: parseFloat(offsetsAndBlur[1], 10) || 0,\n offsetY: parseFloat(offsetsAndBlur[2], 10) || 0,\n blur: parseFloat(offsetsAndBlur[3], 10) || 0\n };\n },\n\n /**\n * Returns a string representation of an instance\n * @see http://www.w3.org/TR/css-text-decor-3/#text-shadow\n * @return {String} Returns CSS3 text-shadow declaration\n */\n toString: function() {\n return [this.offsetX, this.offsetY, this.blur, this.color].join('px ');\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns SVG representation of a shadow\n * @param {fabric.Object} object\n * @return {String} SVG representation of a shadow\n */\n toSVG: function(object) {\n var fBoxX = 40, fBoxY = 40, NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,\n offset = fabric.util.rotateVector(\n { x: this.offsetX, y: this.offsetY },\n fabric.util.degreesToRadians(-object.angle)),\n BLUR_BOX = 20, color = new fabric.Color(this.color);\n\n if (object.width && object.height) {\n //http://www.w3.org/TR/SVG/filters.html#FilterEffectsRegion\n // we add some extra space to filter box to contain the blur ( 20 )\n fBoxX = toFixed((Math.abs(offset.x) + this.blur) / object.width, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX;\n fBoxY = toFixed((Math.abs(offset.y) + this.blur) / object.height, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX;\n }\n if (object.flipX) {\n offset.x *= -1;\n }\n if (object.flipY) {\n offset.y *= -1;\n }\n\n return (\n '\\n' +\n '\\t\\n' +\n '\\t\\n' +\n '\\t\\n' +\n '\\t\\n' +\n '\\t\\n' +\n '\\t\\t\\n' +\n '\\t\\t\\n' +\n '\\t\\n' +\n '\\n');\n },\n /* _TO_SVG_END_ */\n\n /**\n * Returns object representation of a shadow\n * @return {Object} Object representation of a shadow instance\n */\n toObject: function() {\n if (this.includeDefaultValues) {\n return {\n color: this.color,\n blur: this.blur,\n offsetX: this.offsetX,\n offsetY: this.offsetY,\n affectStroke: this.affectStroke,\n nonScaling: this.nonScaling\n };\n }\n var obj = { }, proto = fabric.Shadow.prototype;\n\n ['color', 'blur', 'offsetX', 'offsetY', 'affectStroke', 'nonScaling'].forEach(function(prop) {\n if (this[prop] !== proto[prop]) {\n obj[prop] = this[prop];\n }\n }, this);\n\n return obj;\n }\n });\n\n /**\n * Regex matching shadow offsetX, offsetY and blur (ex: \"2px 2px 10px rgba(0,0,0,0.2)\", \"rgb(0,255,0) 2px 2px\")\n * @static\n * @field\n * @memberOf fabric.Shadow\n */\n // eslint-disable-next-line max-len\n fabric.Shadow.reOffsetsAndBlur = /(?:\\s|^)(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?(\\d+(?:\\.\\d*)?(?:px)?)?(?:\\s?|$)(?:$|\\s)/;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function () {\n\n 'use strict';\n\n if (fabric.StaticCanvas) {\n fabric.warn('fabric.StaticCanvas is already defined.');\n return;\n }\n\n // aliases for faster resolution\n var extend = fabric.util.object.extend,\n getElementOffset = fabric.util.getElementOffset,\n removeFromArray = fabric.util.removeFromArray,\n toFixed = fabric.util.toFixed,\n transformPoint = fabric.util.transformPoint,\n invertTransform = fabric.util.invertTransform,\n getNodeCanvas = fabric.util.getNodeCanvas,\n createCanvasElement = fabric.util.createCanvasElement,\n\n CANVAS_INIT_ERROR = new Error('Could not initialize `canvas` element');\n\n /**\n * Static canvas class\n * @class fabric.StaticCanvas\n * @mixes fabric.Collection\n * @mixes fabric.Observable\n * @see {@link http://fabricjs.com/static_canvas|StaticCanvas demo}\n * @see {@link fabric.StaticCanvas#initialize} for constructor definition\n * @fires before:render\n * @fires after:render\n * @fires canvas:cleared\n * @fires object:added\n * @fires object:removed\n */\n fabric.StaticCanvas = fabric.util.createClass(fabric.CommonMethods, /** @lends fabric.StaticCanvas.prototype */ {\n\n /**\n * Constructor\n * @param {HTMLElement | String} el <canvas> element to initialize instance on\n * @param {Object} [options] Options object\n * @return {Object} thisArg\n */\n initialize: function(el, options) {\n options || (options = { });\n this.renderAndResetBound = this.renderAndReset.bind(this);\n this.requestRenderAllBound = this.requestRenderAll.bind(this);\n this._initStatic(el, options);\n },\n\n /**\n * Background color of canvas instance.\n * Should be set via {@link fabric.StaticCanvas#setBackgroundColor}.\n * @type {(String|fabric.Pattern)}\n * @default\n */\n backgroundColor: '',\n\n /**\n * Background image of canvas instance.\n * since 2.4.0 image caching is active, please when putting an image as background, add to the\n * canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom\n * vale. As an alternative you can disable image objectCaching\n * @type fabric.Image\n * @default\n */\n backgroundImage: null,\n\n /**\n * Overlay color of canvas instance.\n * Should be set via {@link fabric.StaticCanvas#setOverlayColor}\n * @since 1.3.9\n * @type {(String|fabric.Pattern)}\n * @default\n */\n overlayColor: '',\n\n /**\n * Overlay image of canvas instance.\n * since 2.4.0 image caching is active, please when putting an image as overlay, add to the\n * canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom\n * vale. As an alternative you can disable image objectCaching\n * @type fabric.Image\n * @default\n */\n overlayImage: null,\n\n /**\n * Indicates whether toObject/toDatalessObject should include default values\n * if set to false, takes precedence over the object value.\n * @type Boolean\n * @default\n */\n includeDefaultValues: true,\n\n /**\n * Indicates whether objects' state should be saved\n * @type Boolean\n * @default\n */\n stateful: false,\n\n /**\n * Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove},\n * {@link fabric.StaticCanvas.moveTo}, {@link fabric.StaticCanvas.clear} and many more, should also re-render canvas.\n * Disabling this option will not give a performance boost when adding/removing a lot of objects to/from canvas at once\n * since the renders are quequed and executed one per frame.\n * Disabling is suggested anyway and managing the renders of the app manually is not a big effort ( canvas.requestRenderAll() )\n * Left default to true to do not break documentation and old app, fiddles.\n * @type Boolean\n * @default\n */\n renderOnAddRemove: true,\n\n /**\n * Indicates whether object controls (borders/controls) are rendered above overlay image\n * @type Boolean\n * @default\n */\n controlsAboveOverlay: false,\n\n /**\n * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas\n * @type Boolean\n * @default\n */\n allowTouchScrolling: false,\n\n /**\n * Indicates whether this canvas will use image smoothing, this is on by default in browsers\n * @type Boolean\n * @default\n */\n imageSmoothingEnabled: true,\n\n /**\n * The transformation (a Canvas 2D API transform matrix) which focuses the viewport\n * @type Array\n * @example Default transform\n * canvas.viewportTransform = [1, 0, 0, 1, 0, 0];\n * @example Scale by 70% and translate toward bottom-right by 50, without skewing\n * canvas.viewportTransform = [0.7, 0, 0, 0.7, 50, 50];\n * @default\n */\n viewportTransform: fabric.iMatrix.concat(),\n\n /**\n * if set to false background image is not affected by viewport transform\n * @since 1.6.3\n * @type Boolean\n * @default\n */\n backgroundVpt: true,\n\n /**\n * if set to false overlya image is not affected by viewport transform\n * @since 1.6.3\n * @type Boolean\n * @default\n */\n overlayVpt: true,\n\n /**\n * When true, canvas is scaled by devicePixelRatio for better rendering on retina screens\n * @type Boolean\n * @default\n */\n enableRetinaScaling: true,\n\n /**\n * Describe canvas element extension over design\n * properties are tl,tr,bl,br.\n * if canvas is not zoomed/panned those points are the four corner of canvas\n * if canvas is viewportTransformed you those points indicate the extension\n * of canvas element in plain untrasformed coordinates\n * The coordinates get updated with @method calcViewportBoundaries.\n * @memberOf fabric.StaticCanvas.prototype\n */\n vptCoords: { },\n\n /**\n * Based on vptCoords and object.aCoords, skip rendering of objects that\n * are not included in current viewport.\n * May greatly help in applications with crowded canvas and use of zoom/pan\n * If One of the corner of the bounding box of the object is on the canvas\n * the objects get rendered.\n * @memberOf fabric.StaticCanvas.prototype\n * @type Boolean\n * @default\n */\n skipOffscreen: true,\n\n /**\n * a fabricObject that, without stroke define a clipping area with their shape. filled in black\n * the clipPath object gets used when the canvas has rendered, and the context is placed in the\n * top left corner of the canvas.\n * clipPath will clip away controls, if you do not want this to happen use controlsAboveOverlay = true\n * @type fabric.Object\n */\n clipPath: undefined,\n\n /**\n * @private\n * @param {HTMLElement | String} el <canvas> element to initialize instance on\n * @param {Object} [options] Options object\n */\n _initStatic: function(el, options) {\n var cb = this.requestRenderAllBound;\n this._objects = [];\n this._createLowerCanvas(el);\n this._initOptions(options);\n // only initialize retina scaling once\n if (!this.interactive) {\n this._initRetinaScaling();\n }\n\n if (options.overlayImage) {\n this.setOverlayImage(options.overlayImage, cb);\n }\n if (options.backgroundImage) {\n this.setBackgroundImage(options.backgroundImage, cb);\n }\n if (options.backgroundColor) {\n this.setBackgroundColor(options.backgroundColor, cb);\n }\n if (options.overlayColor) {\n this.setOverlayColor(options.overlayColor, cb);\n }\n this.calcOffset();\n },\n\n /**\n * @private\n */\n _isRetinaScaling: function() {\n return (fabric.devicePixelRatio > 1 && this.enableRetinaScaling);\n },\n\n /**\n * @private\n * @return {Number} retinaScaling if applied, otherwise 1;\n */\n getRetinaScaling: function() {\n return this._isRetinaScaling() ? Math.max(1, fabric.devicePixelRatio) : 1;\n },\n\n /**\n * @private\n */\n _initRetinaScaling: function() {\n if (!this._isRetinaScaling()) {\n return;\n }\n var scaleRatio = fabric.devicePixelRatio;\n this.__initRetinaScaling(scaleRatio, this.lowerCanvasEl, this.contextContainer);\n if (this.upperCanvasEl) {\n this.__initRetinaScaling(scaleRatio, this.upperCanvasEl, this.contextTop);\n }\n },\n\n __initRetinaScaling: function(scaleRatio, canvas, context) {\n canvas.setAttribute('width', this.width * scaleRatio);\n canvas.setAttribute('height', this.height * scaleRatio);\n context.scale(scaleRatio, scaleRatio);\n },\n\n\n /**\n * Calculates canvas element offset relative to the document\n * This method is also attached as \"resize\" event handler of window\n * @return {fabric.Canvas} instance\n * @chainable\n */\n calcOffset: function () {\n this._offset = getElementOffset(this.lowerCanvasEl);\n return this;\n },\n\n /**\n * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas\n * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to\n * @param {Function} callback callback to invoke when image is loaded and set as an overlay\n * @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}.\n * @return {fabric.Canvas} thisArg\n * @chainable\n * @see {@link http://jsfiddle.net/fabricjs/MnzHT/|jsFiddle demo}\n * @example Normal overlayImage with left/top = 0\n * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {\n * // Needed to position overlayImage at 0/0\n * originX: 'left',\n * originY: 'top'\n * });\n * @example overlayImage with different properties\n * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {\n * opacity: 0.5,\n * angle: 45,\n * left: 400,\n * top: 400,\n * originX: 'left',\n * originY: 'top'\n * });\n * @example Stretched overlayImage #1 - width/height correspond to canvas width/height\n * fabric.Image.fromURL('http://fabricjs.com/assets/jail_cell_bars.png', function(img, isError) {\n * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});\n * canvas.setOverlayImage(img, canvas.renderAll.bind(canvas));\n * });\n * @example Stretched overlayImage #2 - width/height correspond to canvas width/height\n * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {\n * width: canvas.width,\n * height: canvas.height,\n * // Needed to position overlayImage at 0/0\n * originX: 'left',\n * originY: 'top'\n * });\n * @example overlayImage loaded from cross-origin\n * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {\n * opacity: 0.5,\n * angle: 45,\n * left: 400,\n * top: 400,\n * originX: 'left',\n * originY: 'top',\n * crossOrigin: 'anonymous'\n * });\n */\n setOverlayImage: function (image, callback, options) {\n return this.__setBgOverlayImage('overlayImage', image, callback, options);\n },\n\n /**\n * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas\n * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to\n * @param {Function} callback Callback to invoke when image is loaded and set as background\n * @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}.\n * @return {fabric.Canvas} thisArg\n * @chainable\n * @see {@link http://jsfiddle.net/djnr8o7a/28/|jsFiddle demo}\n * @example Normal backgroundImage with left/top = 0\n * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {\n * // Needed to position backgroundImage at 0/0\n * originX: 'left',\n * originY: 'top'\n * });\n * @example backgroundImage with different properties\n * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {\n * opacity: 0.5,\n * angle: 45,\n * left: 400,\n * top: 400,\n * originX: 'left',\n * originY: 'top'\n * });\n * @example Stretched backgroundImage #1 - width/height correspond to canvas width/height\n * fabric.Image.fromURL('http://fabricjs.com/assets/honey_im_subtle.png', function(img, isError) {\n * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});\n * canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));\n * });\n * @example Stretched backgroundImage #2 - width/height correspond to canvas width/height\n * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {\n * width: canvas.width,\n * height: canvas.height,\n * // Needed to position backgroundImage at 0/0\n * originX: 'left',\n * originY: 'top'\n * });\n * @example backgroundImage loaded from cross-origin\n * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {\n * opacity: 0.5,\n * angle: 45,\n * left: 400,\n * top: 400,\n * originX: 'left',\n * originY: 'top',\n * crossOrigin: 'anonymous'\n * });\n */\n // TODO: fix stretched examples\n setBackgroundImage: function (image, callback, options) {\n return this.__setBgOverlayImage('backgroundImage', image, callback, options);\n },\n\n /**\n * Sets {@link fabric.StaticCanvas#overlayColor|foreground color} for this canvas\n * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set foreground color to\n * @param {Function} callback Callback to invoke when foreground color is set\n * @return {fabric.Canvas} thisArg\n * @chainable\n * @see {@link http://jsfiddle.net/fabricjs/pB55h/|jsFiddle demo}\n * @example Normal overlayColor - color value\n * canvas.setOverlayColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));\n * @example fabric.Pattern used as overlayColor\n * canvas.setOverlayColor({\n * source: 'http://fabricjs.com/assets/escheresque_ste.png'\n * }, canvas.renderAll.bind(canvas));\n * @example fabric.Pattern used as overlayColor with repeat and offset\n * canvas.setOverlayColor({\n * source: 'http://fabricjs.com/assets/escheresque_ste.png',\n * repeat: 'repeat',\n * offsetX: 200,\n * offsetY: 100\n * }, canvas.renderAll.bind(canvas));\n */\n setOverlayColor: function(overlayColor, callback) {\n return this.__setBgOverlayColor('overlayColor', overlayColor, callback);\n },\n\n /**\n * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas\n * @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to\n * @param {Function} callback Callback to invoke when background color is set\n * @return {fabric.Canvas} thisArg\n * @chainable\n * @see {@link http://jsfiddle.net/fabricjs/hXzvk/|jsFiddle demo}\n * @example Normal backgroundColor - color value\n * canvas.setBackgroundColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));\n * @example fabric.Pattern used as backgroundColor\n * canvas.setBackgroundColor({\n * source: 'http://fabricjs.com/assets/escheresque_ste.png'\n * }, canvas.renderAll.bind(canvas));\n * @example fabric.Pattern used as backgroundColor with repeat and offset\n * canvas.setBackgroundColor({\n * source: 'http://fabricjs.com/assets/escheresque_ste.png',\n * repeat: 'repeat',\n * offsetX: 200,\n * offsetY: 100\n * }, canvas.renderAll.bind(canvas));\n */\n setBackgroundColor: function(backgroundColor, callback) {\n return this.__setBgOverlayColor('backgroundColor', backgroundColor, callback);\n },\n\n /**\n * @private\n * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundImage|backgroundImage}\n * or {@link fabric.StaticCanvas#overlayImage|overlayImage})\n * @param {(fabric.Image|String|null)} image fabric.Image instance, URL of an image or null to set background or overlay to\n * @param {Function} callback Callback to invoke when image is loaded and set as background or overlay. The first argument is the created image, the second argument is a flag indicating whether an error occurred or not.\n * @param {Object} [options] Optional options to set for the {@link fabric.Image|image}.\n */\n __setBgOverlayImage: function(property, image, callback, options) {\n if (typeof image === 'string') {\n fabric.util.loadImage(image, function(img, isError) {\n if (img) {\n var instance = new fabric.Image(img, options);\n this[property] = instance;\n instance.canvas = this;\n }\n callback && callback(img, isError);\n }, this, options && options.crossOrigin);\n }\n else {\n options && image.setOptions(options);\n this[property] = image;\n image && (image.canvas = this);\n callback && callback(image, false);\n }\n\n return this;\n },\n\n /**\n * @private\n * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundColor|backgroundColor}\n * or {@link fabric.StaticCanvas#overlayColor|overlayColor})\n * @param {(Object|String|null)} color Object with pattern information, color value or null\n * @param {Function} [callback] Callback is invoked when color is set\n */\n __setBgOverlayColor: function(property, color, callback) {\n this[property] = color;\n this._initGradient(color, property);\n this._initPattern(color, property, callback);\n return this;\n },\n\n /**\n * @private\n */\n _createCanvasElement: function() {\n var element = createCanvasElement();\n if (!element) {\n throw CANVAS_INIT_ERROR;\n }\n if (!element.style) {\n element.style = { };\n }\n if (typeof element.getContext === 'undefined') {\n throw CANVAS_INIT_ERROR;\n }\n return element;\n },\n\n /**\n * @private\n * @param {Object} [options] Options object\n */\n _initOptions: function (options) {\n var lowerCanvasEl = this.lowerCanvasEl;\n this._setOptions(options);\n\n this.width = this.width || parseInt(lowerCanvasEl.width, 10) || 0;\n this.height = this.height || parseInt(lowerCanvasEl.height, 10) || 0;\n\n if (!this.lowerCanvasEl.style) {\n return;\n }\n\n lowerCanvasEl.width = this.width;\n lowerCanvasEl.height = this.height;\n\n lowerCanvasEl.style.width = this.width + 'px';\n lowerCanvasEl.style.height = this.height + 'px';\n\n this.viewportTransform = this.viewportTransform.slice();\n },\n\n /**\n * Creates a bottom canvas\n * @private\n * @param {HTMLElement} [canvasEl]\n */\n _createLowerCanvas: function (canvasEl) {\n // canvasEl === 'HTMLCanvasElement' does not work on jsdom/node\n if (canvasEl && canvasEl.getContext) {\n this.lowerCanvasEl = canvasEl;\n }\n else {\n this.lowerCanvasEl = fabric.util.getById(canvasEl) || this._createCanvasElement();\n }\n\n fabric.util.addClass(this.lowerCanvasEl, 'lower-canvas');\n this._originalCanvasStyle = this.lowerCanvasEl.style;\n if (this.interactive) {\n this._applyCanvasStyle(this.lowerCanvasEl);\n }\n\n this.contextContainer = this.lowerCanvasEl.getContext('2d');\n },\n\n /**\n * Returns canvas width (in px)\n * @return {Number}\n */\n getWidth: function () {\n return this.width;\n },\n\n /**\n * Returns canvas height (in px)\n * @return {Number}\n */\n getHeight: function () {\n return this.height;\n },\n\n /**\n * Sets width of this canvas instance\n * @param {Number|String} value Value to set width to\n * @param {Object} [options] Options object\n * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions\n * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n setWidth: function (value, options) {\n return this.setDimensions({ width: value }, options);\n },\n\n /**\n * Sets height of this canvas instance\n * @param {Number|String} value Value to set height to\n * @param {Object} [options] Options object\n * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions\n * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n setHeight: function (value, options) {\n return this.setDimensions({ height: value }, options);\n },\n\n /**\n * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)\n * @param {Object} dimensions Object with width/height properties\n * @param {Number|String} [dimensions.width] Width of canvas element\n * @param {Number|String} [dimensions.height] Height of canvas element\n * @param {Object} [options] Options object\n * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions\n * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n setDimensions: function (dimensions, options) {\n var cssValue;\n\n options = options || {};\n\n for (var prop in dimensions) {\n cssValue = dimensions[prop];\n\n if (!options.cssOnly) {\n this._setBackstoreDimension(prop, dimensions[prop]);\n cssValue += 'px';\n this.hasLostContext = true;\n }\n\n if (!options.backstoreOnly) {\n this._setCssDimension(prop, cssValue);\n }\n }\n if (this._isCurrentlyDrawing) {\n this.freeDrawingBrush && this.freeDrawingBrush._setBrushStyles(this.contextTop);\n }\n this._initRetinaScaling();\n this.calcOffset();\n\n if (!options.cssOnly) {\n this.requestRenderAll();\n }\n\n return this;\n },\n\n /**\n * Helper for setting width/height\n * @private\n * @param {String} prop property (width|height)\n * @param {Number} value value to set property to\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n _setBackstoreDimension: function (prop, value) {\n this.lowerCanvasEl[prop] = value;\n\n if (this.upperCanvasEl) {\n this.upperCanvasEl[prop] = value;\n }\n\n if (this.cacheCanvasEl) {\n this.cacheCanvasEl[prop] = value;\n }\n\n this[prop] = value;\n\n return this;\n },\n\n /**\n * Helper for setting css width/height\n * @private\n * @param {String} prop property (width|height)\n * @param {String} value value to set property to\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n _setCssDimension: function (prop, value) {\n this.lowerCanvasEl.style[prop] = value;\n\n if (this.upperCanvasEl) {\n this.upperCanvasEl.style[prop] = value;\n }\n\n if (this.wrapperEl) {\n this.wrapperEl.style[prop] = value;\n }\n\n return this;\n },\n\n /**\n * Returns canvas zoom level\n * @return {Number}\n */\n getZoom: function () {\n return this.viewportTransform[0];\n },\n\n /**\n * Sets viewport transformation of this canvas instance\n * @param {Array} vpt a Canvas 2D API transform matrix\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n setViewportTransform: function (vpt) {\n var activeObject = this._activeObject,\n backgroundObject = this.backgroundImage,\n overlayObject = this.overlayImage,\n object, i, len;\n this.viewportTransform = vpt;\n for (i = 0, len = this._objects.length; i < len; i++) {\n object = this._objects[i];\n object.group || object.setCoords(true);\n }\n if (activeObject) {\n activeObject.setCoords();\n }\n if (backgroundObject) {\n backgroundObject.setCoords(true);\n }\n if (overlayObject) {\n overlayObject.setCoords(true);\n }\n this.calcViewportBoundaries();\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * Sets zoom level of this canvas instance, the zoom centered around point\n * meaning that following zoom to point with the same point will have the visual\n * effect of the zoom originating from that point. The point won't move.\n * It has nothing to do with canvas center or visual center of the viewport.\n * @param {fabric.Point} point to zoom with respect to\n * @param {Number} value to set zoom to, less than 1 zooms out\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n zoomToPoint: function (point, value) {\n // TODO: just change the scale, preserve other transformations\n var before = point, vpt = this.viewportTransform.slice(0);\n point = transformPoint(point, invertTransform(this.viewportTransform));\n vpt[0] = value;\n vpt[3] = value;\n var after = transformPoint(point, vpt);\n vpt[4] += before.x - after.x;\n vpt[5] += before.y - after.y;\n return this.setViewportTransform(vpt);\n },\n\n /**\n * Sets zoom level of this canvas instance\n * @param {Number} value to set zoom to, less than 1 zooms out\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n setZoom: function (value) {\n this.zoomToPoint(new fabric.Point(0, 0), value);\n return this;\n },\n\n /**\n * Pan viewport so as to place point at top left corner of canvas\n * @param {fabric.Point} point to move to\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n absolutePan: function (point) {\n var vpt = this.viewportTransform.slice(0);\n vpt[4] = -point.x;\n vpt[5] = -point.y;\n return this.setViewportTransform(vpt);\n },\n\n /**\n * Pans viewpoint relatively\n * @param {fabric.Point} point (position vector) to move by\n * @return {fabric.Canvas} instance\n * @chainable true\n */\n relativePan: function (point) {\n return this.absolutePan(new fabric.Point(\n -point.x - this.viewportTransform[4],\n -point.y - this.viewportTransform[5]\n ));\n },\n\n /**\n * Returns <canvas> element corresponding to this instance\n * @return {HTMLCanvasElement}\n */\n getElement: function () {\n return this.lowerCanvasEl;\n },\n\n /**\n * @private\n * @param {fabric.Object} obj Object that was added\n */\n _onObjectAdded: function(obj) {\n this.stateful && obj.setupState();\n obj._set('canvas', this);\n obj.setCoords();\n this.fire('object:added', { target: obj });\n obj.fire('added');\n },\n\n /**\n * @private\n * @param {fabric.Object} obj Object that was removed\n */\n _onObjectRemoved: function(obj) {\n this.fire('object:removed', { target: obj });\n obj.fire('removed');\n delete obj.canvas;\n },\n\n /**\n * Clears specified context of canvas element\n * @param {CanvasRenderingContext2D} ctx Context to clear\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n clearContext: function(ctx) {\n ctx.clearRect(0, 0, this.width, this.height);\n return this;\n },\n\n /**\n * Returns context of canvas where objects are drawn\n * @return {CanvasRenderingContext2D}\n */\n getContext: function () {\n return this.contextContainer;\n },\n\n /**\n * Clears all contexts (background, main, top) of an instance\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n clear: function () {\n this.remove.apply(this, this.getObjects());\n this.backgroundImage = null;\n this.overlayImage = null;\n this.backgroundColor = '';\n this.overlayColor = '';\n if (this._hasITextHandlers) {\n this.off('mouse:up', this._mouseUpITextHandler);\n this._iTextInstances = null;\n this._hasITextHandlers = false;\n }\n this.clearContext(this.contextContainer);\n this.fire('canvas:cleared');\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * Renders the canvas\n * @return {fabric.Canvas} instance\n * @chainable\n */\n renderAll: function () {\n var canvasToDrawOn = this.contextContainer;\n this.renderCanvas(canvasToDrawOn, this._objects);\n return this;\n },\n\n /**\n * Function created to be instance bound at initialization\n * used in requestAnimationFrame rendering\n * Let the fabricJS call it. If you call it manually you could have more\n * animationFrame stacking on to of each other\n * for an imperative rendering, use canvas.renderAll\n * @private\n * @return {fabric.Canvas} instance\n * @chainable\n */\n renderAndReset: function() {\n this.isRendering = 0;\n this.renderAll();\n },\n\n /**\n * Append a renderAll request to next animation frame.\n * unless one is already in progress, in that case nothing is done\n * a boolean flag will avoid appending more.\n * @return {fabric.Canvas} instance\n * @chainable\n */\n requestRenderAll: function () {\n if (!this.isRendering) {\n this.isRendering = fabric.util.requestAnimFrame(this.renderAndResetBound);\n }\n return this;\n },\n\n /**\n * Calculate the position of the 4 corner of canvas with current viewportTransform.\n * helps to determinate when an object is in the current rendering viewport using\n * object absolute coordinates ( aCoords )\n * @return {Object} points.tl\n * @chainable\n */\n calcViewportBoundaries: function() {\n var points = { }, width = this.width, height = this.height,\n iVpt = invertTransform(this.viewportTransform);\n points.tl = transformPoint({ x: 0, y: 0 }, iVpt);\n points.br = transformPoint({ x: width, y: height }, iVpt);\n points.tr = new fabric.Point(points.br.x, points.tl.y);\n points.bl = new fabric.Point(points.tl.x, points.br.y);\n this.vptCoords = points;\n return points;\n },\n\n cancelRequestedRender: function() {\n if (this.isRendering) {\n fabric.util.cancelAnimFrame(this.isRendering);\n this.isRendering = 0;\n }\n },\n\n /**\n * Renders background, objects, overlay and controls.\n * @param {CanvasRenderingContext2D} ctx\n * @param {Array} objects to render\n * @return {fabric.Canvas} instance\n * @chainable\n */\n renderCanvas: function(ctx, objects) {\n var v = this.viewportTransform, path = this.clipPath;\n this.cancelRequestedRender();\n this.calcViewportBoundaries();\n this.clearContext(ctx);\n fabric.util.setImageSmoothing(ctx, this.imageSmoothingEnabled);\n this.fire('before:render', { ctx: ctx, });\n this._renderBackground(ctx);\n\n ctx.save();\n //apply viewport transform once for all rendering process\n ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);\n this._renderObjects(ctx, objects);\n ctx.restore();\n if (!this.controlsAboveOverlay && this.interactive) {\n this.drawControls(ctx);\n }\n if (path) {\n path.canvas = this;\n // needed to setup a couple of variables\n path.shouldCache();\n path._transformDone = true;\n path.renderCache({ forClipping: true });\n this.drawClipPathOnCanvas(ctx);\n }\n this._renderOverlay(ctx);\n if (this.controlsAboveOverlay && this.interactive) {\n this.drawControls(ctx);\n }\n this.fire('after:render', { ctx: ctx, });\n },\n\n /**\n * Paint the cached clipPath on the lowerCanvasEl\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n drawClipPathOnCanvas: function(ctx) {\n var v = this.viewportTransform, path = this.clipPath;\n ctx.save();\n ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);\n // DEBUG: uncomment this line, comment the following\n // ctx.globalAlpha = 0.4;\n ctx.globalCompositeOperation = 'destination-in';\n path.transform(ctx);\n ctx.scale(1 / path.zoomX, 1 / path.zoomY);\n ctx.drawImage(path._cacheCanvas, -path.cacheTranslationX, -path.cacheTranslationY);\n ctx.restore();\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {Array} objects to render\n */\n _renderObjects: function(ctx, objects) {\n var i, len;\n for (i = 0, len = objects.length; i < len; ++i) {\n objects[i] && objects[i].render(ctx);\n }\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {string} property 'background' or 'overlay'\n */\n _renderBackgroundOrOverlay: function(ctx, property) {\n var fill = this[property + 'Color'], object = this[property + 'Image'],\n v = this.viewportTransform, needsVpt = this[property + 'Vpt'];\n if (!fill && !object) {\n return;\n }\n if (fill) {\n ctx.save();\n ctx.beginPath();\n ctx.moveTo(0, 0);\n ctx.lineTo(this.width, 0);\n ctx.lineTo(this.width, this.height);\n ctx.lineTo(0, this.height);\n ctx.closePath();\n ctx.fillStyle = fill.toLive\n ? fill.toLive(ctx, this)\n : fill;\n if (needsVpt) {\n ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);\n }\n ctx.transform(1, 0, 0, 1, fill.offsetX || 0, fill.offsetY || 0);\n var m = fill.gradientTransform || fill.patternTransform;\n m && ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);\n ctx.fill();\n ctx.restore();\n }\n if (object) {\n ctx.save();\n if (needsVpt) {\n ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);\n }\n object.render(ctx);\n ctx.restore();\n }\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderBackground: function(ctx) {\n this._renderBackgroundOrOverlay(ctx, 'background');\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderOverlay: function(ctx) {\n this._renderBackgroundOrOverlay(ctx, 'overlay');\n },\n\n /**\n * Returns coordinates of a center of canvas.\n * Returned value is an object with top and left properties\n * @return {Object} object with \"top\" and \"left\" number values\n * @deprecated migrate to `getCenterPoint`\n */\n getCenter: function () {\n return {\n top: this.height / 2,\n left: this.width / 2\n };\n },\n\n /**\n * Returns coordinates of a center of canvas.\n * @return {fabric.Point} \n */\n getCenterPoint: function () {\n return new fabric.Point(this.width / 2, this.height / 2);\n },\n\n /**\n * Centers object horizontally in the canvas\n * @param {fabric.Object} object Object to center horizontally\n * @return {fabric.Canvas} thisArg\n */\n centerObjectH: function (object) {\n return this._centerObject(object, new fabric.Point(this.getCenterPoint().x, object.getCenterPoint().y));\n },\n\n /**\n * Centers object vertically in the canvas\n * @param {fabric.Object} object Object to center vertically\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n centerObjectV: function (object) {\n return this._centerObject(object, new fabric.Point(object.getCenterPoint().x, this.getCenterPoint().y));\n },\n\n /**\n * Centers object vertically and horizontally in the canvas\n * @param {fabric.Object} object Object to center vertically and horizontally\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n centerObject: function(object) {\n var center = this.getCenterPoint();\n return this._centerObject(object, center);\n },\n\n /**\n * Centers object vertically and horizontally in the viewport\n * @param {fabric.Object} object Object to center vertically and horizontally\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n viewportCenterObject: function(object) {\n var vpCenter = this.getVpCenter();\n return this._centerObject(object, vpCenter);\n },\n\n /**\n * Centers object horizontally in the viewport, object.top is unchanged\n * @param {fabric.Object} object Object to center vertically and horizontally\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n viewportCenterObjectH: function(object) {\n var vpCenter = this.getVpCenter();\n this._centerObject(object, new fabric.Point(vpCenter.x, object.getCenterPoint().y));\n return this;\n },\n\n /**\n * Centers object Vertically in the viewport, object.top is unchanged\n * @param {fabric.Object} object Object to center vertically and horizontally\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n viewportCenterObjectV: function(object) {\n var vpCenter = this.getVpCenter();\n\n return this._centerObject(object, new fabric.Point(object.getCenterPoint().x, vpCenter.y));\n },\n\n /**\n * Calculate the point in canvas that correspond to the center of actual viewport.\n * @return {fabric.Point} vpCenter, viewport center\n * @chainable\n */\n getVpCenter: function() {\n var center = this.getCenterPoint(),\n iVpt = invertTransform(this.viewportTransform);\n return transformPoint(center, iVpt);\n },\n\n /**\n * @private\n * @param {fabric.Object} object Object to center\n * @param {fabric.Point} center Center point\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n _centerObject: function(object, center) {\n object.setPositionByOrigin(center, 'center', 'center');\n object.setCoords();\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * Returns dataless JSON representation of canvas\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {String} json string\n */\n toDatalessJSON: function (propertiesToInclude) {\n return this.toDatalessObject(propertiesToInclude);\n },\n\n /**\n * Returns object representation of canvas\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject: function (propertiesToInclude) {\n return this._toObjectMethod('toObject', propertiesToInclude);\n },\n\n /**\n * Returns dataless object representation of canvas\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toDatalessObject: function (propertiesToInclude) {\n return this._toObjectMethod('toDatalessObject', propertiesToInclude);\n },\n\n /**\n * @private\n */\n _toObjectMethod: function (methodName, propertiesToInclude) {\n\n var clipPath = this.clipPath, data = {\n version: fabric.version,\n objects: this._toObjects(methodName, propertiesToInclude),\n };\n if (clipPath && !clipPath.excludeFromExport) {\n data.clipPath = this._toObject(this.clipPath, methodName, propertiesToInclude);\n }\n extend(data, this.__serializeBgOverlay(methodName, propertiesToInclude));\n\n fabric.util.populateWithProperties(this, data, propertiesToInclude);\n\n return data;\n },\n\n /**\n * @private\n */\n _toObjects: function(methodName, propertiesToInclude) {\n return this._objects.filter(function(object) {\n return !object.excludeFromExport;\n }).map(function(instance) {\n return this._toObject(instance, methodName, propertiesToInclude);\n }, this);\n },\n\n /**\n * @private\n */\n _toObject: function(instance, methodName, propertiesToInclude) {\n var originalValue;\n\n if (!this.includeDefaultValues) {\n originalValue = instance.includeDefaultValues;\n instance.includeDefaultValues = false;\n }\n\n var object = instance[methodName](propertiesToInclude);\n if (!this.includeDefaultValues) {\n instance.includeDefaultValues = originalValue;\n }\n return object;\n },\n\n /**\n * @private\n */\n __serializeBgOverlay: function(methodName, propertiesToInclude) {\n var data = {}, bgImage = this.backgroundImage, overlayImage = this.overlayImage,\n bgColor = this.backgroundColor, overlayColor = this.overlayColor;\n\n if (bgColor && bgColor.toObject) {\n if (!bgColor.excludeFromExport) {\n data.background = bgColor.toObject(propertiesToInclude);\n }\n }\n else if (bgColor) {\n data.background = bgColor;\n }\n\n if (overlayColor && overlayColor.toObject) {\n if (!overlayColor.excludeFromExport) {\n data.overlay = overlayColor.toObject(propertiesToInclude);\n }\n }\n else if (overlayColor) {\n data.overlay = overlayColor;\n }\n\n if (bgImage && !bgImage.excludeFromExport) {\n data.backgroundImage = this._toObject(bgImage, methodName, propertiesToInclude);\n }\n if (overlayImage && !overlayImage.excludeFromExport) {\n data.overlayImage = this._toObject(overlayImage, methodName, propertiesToInclude);\n }\n\n return data;\n },\n\n /* _TO_SVG_START_ */\n /**\n * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true,\n * a zoomed canvas will then produce zoomed SVG output.\n * @type Boolean\n * @default\n */\n svgViewportTransformation: true,\n\n /**\n * Returns SVG representation of canvas\n * @function\n * @param {Object} [options] Options object for SVG output\n * @param {Boolean} [options.suppressPreamble=false] If true xml tag is not included\n * @param {Object} [options.viewBox] SVG viewbox object\n * @param {Number} [options.viewBox.x] x-coordinate of viewbox\n * @param {Number} [options.viewBox.y] y-coordinate of viewbox\n * @param {Number} [options.viewBox.width] Width of viewbox\n * @param {Number} [options.viewBox.height] Height of viewbox\n * @param {String} [options.encoding=UTF-8] Encoding of SVG output\n * @param {String} [options.width] desired width of svg with or without units\n * @param {String} [options.height] desired height of svg with or without units\n * @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation.\n * @return {String} SVG string\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#serialization}\n * @see {@link http://jsfiddle.net/fabricjs/jQ3ZZ/|jsFiddle demo}\n * @example Normal SVG output\n * var svg = canvas.toSVG();\n * @example SVG output without preamble (without <?xml ../>)\n * var svg = canvas.toSVG({suppressPreamble: true});\n * @example SVG output with viewBox attribute\n * var svg = canvas.toSVG({\n * viewBox: {\n * x: 100,\n * y: 100,\n * width: 200,\n * height: 300\n * }\n * });\n * @example SVG output with different encoding (default: UTF-8)\n * var svg = canvas.toSVG({encoding: 'ISO-8859-1'});\n * @example Modify SVG output with reviver function\n * var svg = canvas.toSVG(null, function(svg) {\n * return svg.replace('stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; ', '');\n * });\n */\n toSVG: function(options, reviver) {\n options || (options = { });\n options.reviver = reviver;\n var markup = [];\n\n this._setSVGPreamble(markup, options);\n this._setSVGHeader(markup, options);\n if (this.clipPath) {\n markup.push('\\n');\n }\n this._setSVGBgOverlayColor(markup, 'background');\n this._setSVGBgOverlayImage(markup, 'backgroundImage', reviver);\n this._setSVGObjects(markup, reviver);\n if (this.clipPath) {\n markup.push('\\n');\n }\n this._setSVGBgOverlayColor(markup, 'overlay');\n this._setSVGBgOverlayImage(markup, 'overlayImage', reviver);\n\n markup.push('');\n\n return markup.join('');\n },\n\n /**\n * @private\n */\n _setSVGPreamble: function(markup, options) {\n if (options.suppressPreamble) {\n return;\n }\n markup.push(\n '\\n',\n '\\n'\n );\n },\n\n /**\n * @private\n */\n _setSVGHeader: function(markup, options) {\n var width = options.width || this.width,\n height = options.height || this.height,\n vpt, viewBox = 'viewBox=\"0 0 ' + this.width + ' ' + this.height + '\" ',\n NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;\n\n if (options.viewBox) {\n viewBox = 'viewBox=\"' +\n options.viewBox.x + ' ' +\n options.viewBox.y + ' ' +\n options.viewBox.width + ' ' +\n options.viewBox.height + '\" ';\n }\n else {\n if (this.svgViewportTransformation) {\n vpt = this.viewportTransform;\n viewBox = 'viewBox=\"' +\n toFixed(-vpt[4] / vpt[0], NUM_FRACTION_DIGITS) + ' ' +\n toFixed(-vpt[5] / vpt[3], NUM_FRACTION_DIGITS) + ' ' +\n toFixed(this.width / vpt[0], NUM_FRACTION_DIGITS) + ' ' +\n toFixed(this.height / vpt[3], NUM_FRACTION_DIGITS) + '\" ';\n }\n }\n\n markup.push(\n '\\n',\n 'Created with Fabric.js ', fabric.version, '\\n',\n '\\n',\n this.createSVGFontFacesMarkup(),\n this.createSVGRefElementsMarkup(),\n this.createSVGClipPathMarkup(options),\n '\\n'\n );\n },\n\n createSVGClipPathMarkup: function(options) {\n var clipPath = this.clipPath;\n if (clipPath) {\n clipPath.clipPathId = 'CLIPPATH_' + fabric.Object.__uid++;\n return '\\n' +\n this.clipPath.toClipPathSVG(options.reviver) +\n '\\n';\n }\n return '';\n },\n\n /**\n * Creates markup containing SVG referenced elements like patterns, gradients etc.\n * @return {String}\n */\n createSVGRefElementsMarkup: function() {\n var _this = this,\n markup = ['background', 'overlay'].map(function(prop) {\n var fill = _this[prop + 'Color'];\n if (fill && fill.toLive) {\n var shouldTransform = _this[prop + 'Vpt'], vpt = _this.viewportTransform,\n object = {\n width: _this.width / (shouldTransform ? vpt[0] : 1),\n height: _this.height / (shouldTransform ? vpt[3] : 1)\n };\n return fill.toSVG(\n object,\n { additionalTransform: shouldTransform ? fabric.util.matrixToSVG(vpt) : '' }\n );\n }\n });\n return markup.join('');\n },\n\n /**\n * Creates markup containing SVG font faces,\n * font URLs for font faces must be collected by developers\n * and are not extracted from the DOM by fabricjs\n * @param {Array} objects Array of fabric objects\n * @return {String}\n */\n createSVGFontFacesMarkup: function() {\n var markup = '', fontList = { }, obj, fontFamily,\n style, row, rowIndex, _char, charIndex, i, len,\n fontPaths = fabric.fontPaths, objects = [];\n\n this._objects.forEach(function add(object) {\n objects.push(object);\n if (object._objects) {\n object._objects.forEach(add);\n }\n });\n\n for (i = 0, len = objects.length; i < len; i++) {\n obj = objects[i];\n fontFamily = obj.fontFamily;\n if (obj.type.indexOf('text') === -1 || fontList[fontFamily] || !fontPaths[fontFamily]) {\n continue;\n }\n fontList[fontFamily] = true;\n if (!obj.styles) {\n continue;\n }\n style = obj.styles;\n for (rowIndex in style) {\n row = style[rowIndex];\n for (charIndex in row) {\n _char = row[charIndex];\n fontFamily = _char.fontFamily;\n if (!fontList[fontFamily] && fontPaths[fontFamily]) {\n fontList[fontFamily] = true;\n }\n }\n }\n }\n\n for (var j in fontList) {\n markup += [\n '\\t\\t@font-face {\\n',\n '\\t\\t\\tfont-family: \\'', j, '\\';\\n',\n '\\t\\t\\tsrc: url(\\'', fontPaths[j], '\\');\\n',\n '\\t\\t}\\n'\n ].join('');\n }\n\n if (markup) {\n markup = [\n '\\t\\n'\n ].join('');\n }\n\n return markup;\n },\n\n /**\n * @private\n */\n _setSVGObjects: function(markup, reviver) {\n var instance, i, len, objects = this._objects;\n for (i = 0, len = objects.length; i < len; i++) {\n instance = objects[i];\n if (instance.excludeFromExport) {\n continue;\n }\n this._setSVGObject(markup, instance, reviver);\n }\n },\n\n /**\n * @private\n */\n _setSVGObject: function(markup, instance, reviver) {\n markup.push(instance.toSVG(reviver));\n },\n\n /**\n * @private\n */\n _setSVGBgOverlayImage: function(markup, property, reviver) {\n if (this[property] && !this[property].excludeFromExport && this[property].toSVG) {\n markup.push(this[property].toSVG(reviver));\n }\n },\n\n /**\n * @private\n */\n _setSVGBgOverlayColor: function(markup, property) {\n var filler = this[property + 'Color'], vpt = this.viewportTransform, finalWidth = this.width,\n finalHeight = this.height;\n if (!filler) {\n return;\n }\n if (filler.toLive) {\n var repeat = filler.repeat, iVpt = fabric.util.invertTransform(vpt), shouldInvert = this[property + 'Vpt'],\n additionalTransform = shouldInvert ? fabric.util.matrixToSVG(iVpt) : '';\n markup.push(\n '\\n'\n );\n }\n else {\n markup.push(\n '\\n'\n );\n }\n },\n /* _TO_SVG_END_ */\n\n /**\n * Moves an object or the objects of a multiple selection\n * to the bottom of the stack of drawn objects\n * @param {fabric.Object} object Object to send to back\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n sendToBack: function (object) {\n if (!object) {\n return this;\n }\n var activeSelection = this._activeObject,\n i, obj, objs;\n if (object === activeSelection && object.type === 'activeSelection') {\n objs = activeSelection._objects;\n for (i = objs.length; i--;) {\n obj = objs[i];\n removeFromArray(this._objects, obj);\n this._objects.unshift(obj);\n }\n }\n else {\n removeFromArray(this._objects, object);\n this._objects.unshift(object);\n }\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * Moves an object or the objects of a multiple selection\n * to the top of the stack of drawn objects\n * @param {fabric.Object} object Object to send\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n bringToFront: function (object) {\n if (!object) {\n return this;\n }\n var activeSelection = this._activeObject,\n i, obj, objs;\n if (object === activeSelection && object.type === 'activeSelection') {\n objs = activeSelection._objects;\n for (i = 0; i < objs.length; i++) {\n obj = objs[i];\n removeFromArray(this._objects, obj);\n this._objects.push(obj);\n }\n }\n else {\n removeFromArray(this._objects, object);\n this._objects.push(object);\n }\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * Moves an object or a selection down in stack of drawn objects\n * An optional parameter, intersecting allows to move the object in behind\n * the first intersecting object. Where intersection is calculated with\n * bounding box. If no intersection is found, there will not be change in the\n * stack.\n * @param {fabric.Object} object Object to send\n * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n sendBackwards: function (object, intersecting) {\n if (!object) {\n return this;\n }\n var activeSelection = this._activeObject,\n i, obj, idx, newIdx, objs, objsMoved = 0;\n\n if (object === activeSelection && object.type === 'activeSelection') {\n objs = activeSelection._objects;\n for (i = 0; i < objs.length; i++) {\n obj = objs[i];\n idx = this._objects.indexOf(obj);\n if (idx > 0 + objsMoved) {\n newIdx = idx - 1;\n removeFromArray(this._objects, obj);\n this._objects.splice(newIdx, 0, obj);\n }\n objsMoved++;\n }\n }\n else {\n idx = this._objects.indexOf(object);\n if (idx !== 0) {\n // if object is not on the bottom of stack\n newIdx = this._findNewLowerIndex(object, idx, intersecting);\n removeFromArray(this._objects, object);\n this._objects.splice(newIdx, 0, object);\n }\n }\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * @private\n */\n _findNewLowerIndex: function(object, idx, intersecting) {\n var newIdx, i;\n\n if (intersecting) {\n newIdx = idx;\n\n // traverse down the stack looking for the nearest intersecting object\n for (i = idx - 1; i >= 0; --i) {\n\n var isIntersecting = object.intersectsWithObject(this._objects[i]) ||\n object.isContainedWithinObject(this._objects[i]) ||\n this._objects[i].isContainedWithinObject(object);\n\n if (isIntersecting) {\n newIdx = i;\n break;\n }\n }\n }\n else {\n newIdx = idx - 1;\n }\n\n return newIdx;\n },\n\n /**\n * Moves an object or a selection up in stack of drawn objects\n * An optional parameter, intersecting allows to move the object in front\n * of the first intersecting object. Where intersection is calculated with\n * bounding box. If no intersection is found, there will not be change in the\n * stack.\n * @param {fabric.Object} object Object to send\n * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n bringForward: function (object, intersecting) {\n if (!object) {\n return this;\n }\n var activeSelection = this._activeObject,\n i, obj, idx, newIdx, objs, objsMoved = 0;\n\n if (object === activeSelection && object.type === 'activeSelection') {\n objs = activeSelection._objects;\n for (i = objs.length; i--;) {\n obj = objs[i];\n idx = this._objects.indexOf(obj);\n if (idx < this._objects.length - 1 - objsMoved) {\n newIdx = idx + 1;\n removeFromArray(this._objects, obj);\n this._objects.splice(newIdx, 0, obj);\n }\n objsMoved++;\n }\n }\n else {\n idx = this._objects.indexOf(object);\n if (idx !== this._objects.length - 1) {\n // if object is not on top of stack (last item in an array)\n newIdx = this._findNewUpperIndex(object, idx, intersecting);\n removeFromArray(this._objects, object);\n this._objects.splice(newIdx, 0, object);\n }\n }\n this.renderOnAddRemove && this.requestRenderAll();\n return this;\n },\n\n /**\n * @private\n */\n _findNewUpperIndex: function(object, idx, intersecting) {\n var newIdx, i, len;\n\n if (intersecting) {\n newIdx = idx;\n\n // traverse up the stack looking for the nearest intersecting object\n for (i = idx + 1, len = this._objects.length; i < len; ++i) {\n\n var isIntersecting = object.intersectsWithObject(this._objects[i]) ||\n object.isContainedWithinObject(this._objects[i]) ||\n this._objects[i].isContainedWithinObject(object);\n\n if (isIntersecting) {\n newIdx = i;\n break;\n }\n }\n }\n else {\n newIdx = idx + 1;\n }\n\n return newIdx;\n },\n\n /**\n * Moves an object to specified level in stack of drawn objects\n * @param {fabric.Object} object Object to send\n * @param {Number} index Position to move to\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n moveTo: function (object, index) {\n removeFromArray(this._objects, object);\n this._objects.splice(index, 0, object);\n return this.renderOnAddRemove && this.requestRenderAll();\n },\n\n /**\n * Clears a canvas element and dispose objects\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n dispose: function () {\n // cancel eventually ongoing renders\n if (this.isRendering) {\n fabric.util.cancelAnimFrame(this.isRendering);\n this.isRendering = 0;\n }\n this.forEachObject(function(object) {\n object.dispose && object.dispose();\n });\n this._objects = [];\n if (this.backgroundImage && this.backgroundImage.dispose) {\n this.backgroundImage.dispose();\n }\n this.backgroundImage = null;\n if (this.overlayImage && this.overlayImage.dispose) {\n this.overlayImage.dispose();\n }\n this.overlayImage = null;\n this._iTextInstances = null;\n this.contextContainer = null;\n // restore canvas style\n this.lowerCanvasEl.classList.remove('lower-canvas');\n fabric.util.setStyle(this.lowerCanvasEl, this._originalCanvasStyle);\n delete this._originalCanvasStyle;\n // restore canvas size to original size in case retina scaling was applied\n this.lowerCanvasEl.setAttribute('width', this.width);\n this.lowerCanvasEl.setAttribute('height', this.height);\n fabric.util.cleanUpJsdomNode(this.lowerCanvasEl);\n this.lowerCanvasEl = undefined;\n return this;\n },\n\n /**\n * Returns a string representation of an instance\n * @return {String} string representation of an instance\n */\n toString: function () {\n return '#';\n }\n });\n\n extend(fabric.StaticCanvas.prototype, fabric.Observable);\n extend(fabric.StaticCanvas.prototype, fabric.Collection);\n extend(fabric.StaticCanvas.prototype, fabric.DataURLExporter);\n\n extend(fabric.StaticCanvas, /** @lends fabric.StaticCanvas */ {\n\n /**\n * @static\n * @type String\n * @default\n */\n EMPTY_JSON: '{\"objects\": [], \"background\": \"white\"}',\n\n /**\n * Provides a way to check support of some of the canvas methods\n * (either those of HTMLCanvasElement itself, or rendering context)\n *\n * @param {String} methodName Method to check support for;\n * Could be one of \"setLineDash\"\n * @return {Boolean | null} `true` if method is supported (or at least exists),\n * `null` if canvas element or context can not be initialized\n */\n supports: function (methodName) {\n var el = createCanvasElement();\n\n if (!el || !el.getContext) {\n return null;\n }\n\n var ctx = el.getContext('2d');\n if (!ctx) {\n return null;\n }\n\n switch (methodName) {\n\n case 'setLineDash':\n return typeof ctx.setLineDash !== 'undefined';\n\n default:\n return null;\n }\n }\n });\n\n /**\n * Returns Object representation of canvas\n * this alias is provided because if you call JSON.stringify on an instance,\n * the toJSON object will be invoked if it exists.\n * Having a toJSON method means you can do JSON.stringify(myCanvas)\n * @function\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} JSON compatible object\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#serialization}\n * @see {@link http://jsfiddle.net/fabricjs/pec86/|jsFiddle demo}\n * @example JSON without additional properties\n * var json = canvas.toJSON();\n * @example JSON with additional properties included\n * var json = canvas.toJSON(['lockMovementX', 'lockMovementY', 'lockRotation', 'lockScalingX', 'lockScalingY']);\n * @example JSON without default values\n * canvas.includeDefaultValues = false;\n * var json = canvas.toJSON();\n */\n fabric.StaticCanvas.prototype.toJSON = fabric.StaticCanvas.prototype.toObject;\n\n if (fabric.isLikelyNode) {\n fabric.StaticCanvas.prototype.createPNGStream = function() {\n var impl = getNodeCanvas(this.lowerCanvasEl);\n return impl && impl.createPNGStream();\n };\n fabric.StaticCanvas.prototype.createJPEGStream = function(opts) {\n var impl = getNodeCanvas(this.lowerCanvasEl);\n return impl && impl.createJPEGStream(opts);\n };\n }\n})();\n\n\n/**\n * BaseBrush class\n * @class fabric.BaseBrush\n * @see {@link http://fabricjs.com/freedrawing|Freedrawing demo}\n */\nfabric.BaseBrush = fabric.util.createClass(/** @lends fabric.BaseBrush.prototype */ {\n\n /**\n * Color of a brush\n * @type String\n * @default\n */\n color: 'rgb(0, 0, 0)',\n\n /**\n * Width of a brush, has to be a Number, no string literals\n * @type Number\n * @default\n */\n width: 1,\n\n /**\n * Shadow object representing shadow of this shape.\n * Backwards incompatibility note: This property replaces \"shadowColor\" (String), \"shadowOffsetX\" (Number),\n * \"shadowOffsetY\" (Number) and \"shadowBlur\" (Number) since v1.2.12\n * @type fabric.Shadow\n * @default\n */\n shadow: null,\n\n /**\n * Line endings style of a brush (one of \"butt\", \"round\", \"square\")\n * @type String\n * @default\n */\n strokeLineCap: 'round',\n\n /**\n * Corner style of a brush (one of \"bevel\", \"round\", \"miter\")\n * @type String\n * @default\n */\n strokeLineJoin: 'round',\n\n /**\n * Maximum miter length (used for strokeLineJoin = \"miter\") of a brush's\n * @type Number\n * @default\n */\n strokeMiterLimit: 10,\n\n /**\n * Stroke Dash Array.\n * @type Array\n * @default\n */\n strokeDashArray: null,\n\n /**\n * When `true`, the free drawing is limited to the whiteboard size. Default to false.\n * @type Boolean\n * @default false\n */\n\n limitedToCanvasSize: false,\n\n\n /**\n * Sets brush styles\n * @private\n * @param {CanvasRenderingContext2D} ctx\n */\n _setBrushStyles: function (ctx) {\n ctx.strokeStyle = this.color;\n ctx.lineWidth = this.width;\n ctx.lineCap = this.strokeLineCap;\n ctx.miterLimit = this.strokeMiterLimit;\n ctx.lineJoin = this.strokeLineJoin;\n ctx.setLineDash(this.strokeDashArray || []);\n },\n\n /**\n * Sets the transformation on given context\n * @param {RenderingContext2d} ctx context to render on\n * @private\n */\n _saveAndTransform: function(ctx) {\n var v = this.canvas.viewportTransform;\n ctx.save();\n ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);\n },\n\n /**\n * Sets brush shadow styles\n * @private\n */\n _setShadow: function() {\n if (!this.shadow) {\n return;\n }\n\n var canvas = this.canvas,\n shadow = this.shadow,\n ctx = canvas.contextTop,\n zoom = canvas.getZoom();\n if (canvas && canvas._isRetinaScaling()) {\n zoom *= fabric.devicePixelRatio;\n }\n\n ctx.shadowColor = shadow.color;\n ctx.shadowBlur = shadow.blur * zoom;\n ctx.shadowOffsetX = shadow.offsetX * zoom;\n ctx.shadowOffsetY = shadow.offsetY * zoom;\n },\n\n needsFullRender: function() {\n var color = new fabric.Color(this.color);\n return color.getAlpha() < 1 || !!this.shadow;\n },\n\n /**\n * Removes brush shadow styles\n * @private\n */\n _resetShadow: function() {\n var ctx = this.canvas.contextTop;\n\n ctx.shadowColor = '';\n ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;\n },\n\n /**\n * Check is pointer is outside canvas boundaries\n * @param {Object} pointer\n * @private\n */\n _isOutSideCanvas: function(pointer) {\n return pointer.x < 0 || pointer.x > this.canvas.getWidth() || pointer.y < 0 || pointer.y > this.canvas.getHeight();\n }\n});\n\n\n(function() {\n /**\n * PencilBrush class\n * @class fabric.PencilBrush\n * @extends fabric.BaseBrush\n */\n fabric.PencilBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.PencilBrush.prototype */ {\n\n /**\n * Discard points that are less than `decimate` pixel distant from each other\n * @type Number\n * @default 0.4\n */\n decimate: 0.4,\n\n /**\n * Draws a straight line between last recorded point to current pointer\n * Used for `shift` functionality\n *\n * @type boolean\n * @default false\n */\n drawStraightLine: false,\n\n /**\n * The event modifier key that makes the brush draw a straight line.\n * If `null` or 'none' or any other string that is not a modifier key the feature is disabled.\n * @type {'altKey' | 'shiftKey' | 'ctrlKey' | 'none' | undefined | null}\n */\n straightLineKey: 'shiftKey',\n\n /**\n * Constructor\n * @param {fabric.Canvas} canvas\n * @return {fabric.PencilBrush} Instance of a pencil brush\n */\n initialize: function(canvas) {\n this.canvas = canvas;\n this._points = [];\n },\n\n needsFullRender: function () {\n return this.callSuper('needsFullRender') || this._hasStraightLine;\n },\n\n /**\n * Invoked inside on mouse down and mouse move\n * @param {Object} pointer\n */\n _drawSegment: function (ctx, p1, p2) {\n var midPoint = p1.midPointFrom(p2);\n ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);\n return midPoint;\n },\n\n /**\n * Invoked on mouse down\n * @param {Object} pointer\n */\n onMouseDown: function(pointer, options) {\n if (!this.canvas._isMainEvent(options.e)) {\n return;\n }\n this.drawStraightLine = options.e[this.straightLineKey];\n this._prepareForDrawing(pointer);\n // capture coordinates immediately\n // this allows to draw dots (when movement never occurs)\n this._captureDrawingPath(pointer);\n this._render();\n },\n\n /**\n * Invoked on mouse move\n * @param {Object} pointer\n */\n onMouseMove: function(pointer, options) {\n if (!this.canvas._isMainEvent(options.e)) {\n return;\n }\n this.drawStraightLine = options.e[this.straightLineKey];\n if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {\n return;\n }\n if (this._captureDrawingPath(pointer) && this._points.length > 1) {\n if (this.needsFullRender()) {\n // redraw curve\n // clear top canvas\n this.canvas.clearContext(this.canvas.contextTop);\n this._render();\n }\n else {\n var points = this._points, length = points.length, ctx = this.canvas.contextTop;\n // draw the curve update\n this._saveAndTransform(ctx);\n if (this.oldEnd) {\n ctx.beginPath();\n ctx.moveTo(this.oldEnd.x, this.oldEnd.y);\n }\n this.oldEnd = this._drawSegment(ctx, points[length - 2], points[length - 1], true);\n ctx.stroke();\n ctx.restore();\n }\n }\n },\n\n /**\n * Invoked on mouse up\n */\n onMouseUp: function(options) {\n if (!this.canvas._isMainEvent(options.e)) {\n return true;\n }\n this.drawStraightLine = false;\n this.oldEnd = undefined;\n this._finalizeAndAddPath();\n return false;\n },\n\n /**\n * @private\n * @param {Object} pointer Actual mouse position related to the canvas.\n */\n _prepareForDrawing: function(pointer) {\n\n var p = new fabric.Point(pointer.x, pointer.y);\n\n this._reset();\n this._addPoint(p);\n this.canvas.contextTop.moveTo(p.x, p.y);\n },\n\n /**\n * @private\n * @param {fabric.Point} point Point to be added to points array\n */\n _addPoint: function(point) {\n if (this._points.length > 1 && point.eq(this._points[this._points.length - 1])) {\n return false;\n }\n if (this.drawStraightLine && this._points.length > 1) {\n this._hasStraightLine = true;\n this._points.pop();\n }\n this._points.push(point);\n return true;\n },\n\n /**\n * Clear points array and set contextTop canvas style.\n * @private\n */\n _reset: function() {\n this._points = [];\n this._setBrushStyles(this.canvas.contextTop);\n this._setShadow();\n this._hasStraightLine = false;\n },\n\n /**\n * @private\n * @param {Object} pointer Actual mouse position related to the canvas.\n */\n _captureDrawingPath: function(pointer) {\n var pointerPoint = new fabric.Point(pointer.x, pointer.y);\n return this._addPoint(pointerPoint);\n },\n\n /**\n * Draw a smooth path on the topCanvas using quadraticCurveTo\n * @private\n * @param {CanvasRenderingContext2D} [ctx]\n */\n _render: function(ctx) {\n var i, len,\n p1 = this._points[0],\n p2 = this._points[1];\n ctx = ctx || this.canvas.contextTop;\n this._saveAndTransform(ctx);\n ctx.beginPath();\n //if we only have 2 points in the path and they are the same\n //it means that the user only clicked the canvas without moving the mouse\n //then we should be drawing a dot. A path isn't drawn between two identical dots\n //that's why we set them apart a bit\n if (this._points.length === 2 && p1.x === p2.x && p1.y === p2.y) {\n var width = this.width / 1000;\n p1 = new fabric.Point(p1.x, p1.y);\n p2 = new fabric.Point(p2.x, p2.y);\n p1.x -= width;\n p2.x += width;\n }\n ctx.moveTo(p1.x, p1.y);\n\n for (i = 1, len = this._points.length; i < len; i++) {\n // we pick the point between pi + 1 & pi + 2 as the\n // end point and p1 as our control point.\n this._drawSegment(ctx, p1, p2);\n p1 = this._points[i];\n p2 = this._points[i + 1];\n }\n // Draw last line as a straight line while\n // we wait for the next point to be able to calculate\n // the bezier control point\n ctx.lineTo(p1.x, p1.y);\n ctx.stroke();\n ctx.restore();\n },\n\n /**\n * Converts points to SVG path\n * @param {Array} points Array of points\n * @return {(string|number)[][]} SVG path commands\n */\n convertPointsToSVGPath: function (points) {\n var correction = this.width / 1000;\n return fabric.util.getSmoothPathFromPoints(points, correction);\n },\n\n /**\n * @private\n * @param {(string|number)[][]} pathData SVG path commands\n * @returns {boolean}\n */\n _isEmptySVGPath: function (pathData) {\n var pathString = fabric.util.joinPath(pathData);\n return pathString === 'M 0 0 Q 0 0 0 0 L 0 0';\n },\n\n /**\n * Creates fabric.Path object to add on canvas\n * @param {(string|number)[][]} pathData Path data\n * @return {fabric.Path} Path to add on canvas\n */\n createPath: function(pathData) {\n var path = new fabric.Path(pathData, {\n fill: null,\n stroke: this.color,\n strokeWidth: this.width,\n strokeLineCap: this.strokeLineCap,\n strokeMiterLimit: this.strokeMiterLimit,\n strokeLineJoin: this.strokeLineJoin,\n strokeDashArray: this.strokeDashArray,\n });\n if (this.shadow) {\n this.shadow.affectStroke = true;\n path.shadow = new fabric.Shadow(this.shadow);\n }\n\n return path;\n },\n\n /**\n * Decimate points array with the decimate value\n */\n decimatePoints: function(points, distance) {\n if (points.length <= 2) {\n return points;\n }\n var zoom = this.canvas.getZoom(), adjustedDistance = Math.pow(distance / zoom, 2),\n i, l = points.length - 1, lastPoint = points[0], newPoints = [lastPoint],\n cDistance;\n for (i = 1; i < l - 1; i++) {\n cDistance = Math.pow(lastPoint.x - points[i].x, 2) + Math.pow(lastPoint.y - points[i].y, 2);\n if (cDistance >= adjustedDistance) {\n lastPoint = points[i];\n newPoints.push(lastPoint);\n }\n }\n /**\n * Add the last point from the original line to the end of the array.\n * This ensures decimate doesn't delete the last point on the line, and ensures the line is > 1 point.\n */\n newPoints.push(points[l]);\n return newPoints;\n },\n\n /**\n * On mouseup after drawing the path on contextTop canvas\n * we use the points captured to create an new fabric path object\n * and add it to the fabric canvas.\n */\n _finalizeAndAddPath: function() {\n var ctx = this.canvas.contextTop;\n ctx.closePath();\n if (this.decimate) {\n this._points = this.decimatePoints(this._points, this.decimate);\n }\n var pathData = this.convertPointsToSVGPath(this._points);\n if (this._isEmptySVGPath(pathData)) {\n // do not create 0 width/height paths, as they are\n // rendered inconsistently across browsers\n // Firefox 4, for example, renders a dot,\n // whereas Chrome 10 renders nothing\n this.canvas.requestRenderAll();\n return;\n }\n\n var path = this.createPath(pathData);\n this.canvas.clearContext(this.canvas.contextTop);\n this.canvas.fire('before:path:created', { path: path });\n this.canvas.add(path);\n this.canvas.requestRenderAll();\n path.setCoords();\n this._resetShadow();\n\n\n // fire event 'path' created\n this.canvas.fire('path:created', { path: path });\n }\n });\n})();\n\n\n/**\n * CircleBrush class\n * @class fabric.CircleBrush\n */\nfabric.CircleBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.CircleBrush.prototype */ {\n\n /**\n * Width of a brush\n * @type Number\n * @default\n */\n width: 10,\n\n /**\n * Constructor\n * @param {fabric.Canvas} canvas\n * @return {fabric.CircleBrush} Instance of a circle brush\n */\n initialize: function(canvas) {\n this.canvas = canvas;\n this.points = [];\n },\n\n /**\n * Invoked inside on mouse down and mouse move\n * @param {Object} pointer\n */\n drawDot: function(pointer) {\n var point = this.addPoint(pointer),\n ctx = this.canvas.contextTop;\n this._saveAndTransform(ctx);\n this.dot(ctx, point);\n ctx.restore();\n },\n\n dot: function(ctx, point) {\n ctx.fillStyle = point.fill;\n ctx.beginPath();\n ctx.arc(point.x, point.y, point.radius, 0, Math.PI * 2, false);\n ctx.closePath();\n ctx.fill();\n },\n\n /**\n * Invoked on mouse down\n */\n onMouseDown: function(pointer) {\n this.points.length = 0;\n this.canvas.clearContext(this.canvas.contextTop);\n this._setShadow();\n this.drawDot(pointer);\n },\n\n /**\n * Render the full state of the brush\n * @private\n */\n _render: function() {\n var ctx = this.canvas.contextTop, i, len,\n points = this.points;\n this._saveAndTransform(ctx);\n for (i = 0, len = points.length; i < len; i++) {\n this.dot(ctx, points[i]);\n }\n ctx.restore();\n },\n\n /**\n * Invoked on mouse move\n * @param {Object} pointer\n */\n onMouseMove: function(pointer) {\n if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {\n return;\n }\n if (this.needsFullRender()) {\n this.canvas.clearContext(this.canvas.contextTop);\n this.addPoint(pointer);\n this._render();\n }\n else {\n this.drawDot(pointer);\n }\n },\n\n /**\n * Invoked on mouse up\n */\n onMouseUp: function() {\n var originalRenderOnAddRemove = this.canvas.renderOnAddRemove, i, len;\n this.canvas.renderOnAddRemove = false;\n\n var circles = [];\n\n for (i = 0, len = this.points.length; i < len; i++) {\n var point = this.points[i],\n circle = new fabric.Circle({\n radius: point.radius,\n left: point.x,\n top: point.y,\n originX: 'center',\n originY: 'center',\n fill: point.fill\n });\n\n this.shadow && (circle.shadow = new fabric.Shadow(this.shadow));\n\n circles.push(circle);\n }\n var group = new fabric.Group(circles);\n group.canvas = this.canvas;\n\n this.canvas.fire('before:path:created', { path: group });\n this.canvas.add(group);\n this.canvas.fire('path:created', { path: group });\n\n this.canvas.clearContext(this.canvas.contextTop);\n this._resetShadow();\n this.canvas.renderOnAddRemove = originalRenderOnAddRemove;\n this.canvas.requestRenderAll();\n },\n\n /**\n * @param {Object} pointer\n * @return {fabric.Point} Just added pointer point\n */\n addPoint: function(pointer) {\n var pointerPoint = new fabric.Point(pointer.x, pointer.y),\n\n circleRadius = fabric.util.getRandomInt(\n Math.max(0, this.width - 20), this.width + 20) / 2,\n\n circleColor = new fabric.Color(this.color)\n .setAlpha(fabric.util.getRandomInt(0, 100) / 100)\n .toRgba();\n\n pointerPoint.radius = circleRadius;\n pointerPoint.fill = circleColor;\n\n this.points.push(pointerPoint);\n\n return pointerPoint;\n }\n});\n\n\n/**\n * SprayBrush class\n * @class fabric.SprayBrush\n */\nfabric.SprayBrush = fabric.util.createClass( fabric.BaseBrush, /** @lends fabric.SprayBrush.prototype */ {\n\n /**\n * Width of a spray\n * @type Number\n * @default\n */\n width: 10,\n\n /**\n * Density of a spray (number of dots per chunk)\n * @type Number\n * @default\n */\n density: 20,\n\n /**\n * Width of spray dots\n * @type Number\n * @default\n */\n dotWidth: 1,\n\n /**\n * Width variance of spray dots\n * @type Number\n * @default\n */\n dotWidthVariance: 1,\n\n /**\n * Whether opacity of a dot should be random\n * @type Boolean\n * @default\n */\n randomOpacity: false,\n\n /**\n * Whether overlapping dots (rectangles) should be removed (for performance reasons)\n * @type Boolean\n * @default\n */\n optimizeOverlapping: true,\n\n /**\n * Constructor\n * @param {fabric.Canvas} canvas\n * @return {fabric.SprayBrush} Instance of a spray brush\n */\n initialize: function(canvas) {\n this.canvas = canvas;\n this.sprayChunks = [];\n },\n\n /**\n * Invoked on mouse down\n * @param {Object} pointer\n */\n onMouseDown: function(pointer) {\n this.sprayChunks.length = 0;\n this.canvas.clearContext(this.canvas.contextTop);\n this._setShadow();\n\n this.addSprayChunk(pointer);\n this.render(this.sprayChunkPoints);\n },\n\n /**\n * Invoked on mouse move\n * @param {Object} pointer\n */\n onMouseMove: function(pointer) {\n if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {\n return;\n }\n this.addSprayChunk(pointer);\n this.render(this.sprayChunkPoints);\n },\n\n /**\n * Invoked on mouse up\n */\n onMouseUp: function() {\n var originalRenderOnAddRemove = this.canvas.renderOnAddRemove;\n this.canvas.renderOnAddRemove = false;\n\n var rects = [];\n\n for (var i = 0, ilen = this.sprayChunks.length; i < ilen; i++) {\n var sprayChunk = this.sprayChunks[i];\n\n for (var j = 0, jlen = sprayChunk.length; j < jlen; j++) {\n\n var rect = new fabric.Rect({\n width: sprayChunk[j].width,\n height: sprayChunk[j].width,\n left: sprayChunk[j].x + 1,\n top: sprayChunk[j].y + 1,\n originX: 'center',\n originY: 'center',\n fill: this.color\n });\n rects.push(rect);\n }\n }\n\n if (this.optimizeOverlapping) {\n rects = this._getOptimizedRects(rects);\n }\n\n var group = new fabric.Group(rects);\n this.shadow && group.set('shadow', new fabric.Shadow(this.shadow));\n this.canvas.fire('before:path:created', { path: group });\n this.canvas.add(group);\n this.canvas.fire('path:created', { path: group });\n\n this.canvas.clearContext(this.canvas.contextTop);\n this._resetShadow();\n this.canvas.renderOnAddRemove = originalRenderOnAddRemove;\n this.canvas.requestRenderAll();\n },\n\n /**\n * @private\n * @param {Array} rects\n */\n _getOptimizedRects: function(rects) {\n\n // avoid creating duplicate rects at the same coordinates\n var uniqueRects = { }, key, i, len;\n\n for (i = 0, len = rects.length; i < len; i++) {\n key = rects[i].left + '' + rects[i].top;\n if (!uniqueRects[key]) {\n uniqueRects[key] = rects[i];\n }\n }\n var uniqueRectsArray = [];\n for (key in uniqueRects) {\n uniqueRectsArray.push(uniqueRects[key]);\n }\n\n return uniqueRectsArray;\n },\n\n /**\n * Render new chunk of spray brush\n */\n render: function(sprayChunk) {\n var ctx = this.canvas.contextTop, i, len;\n ctx.fillStyle = this.color;\n\n this._saveAndTransform(ctx);\n\n for (i = 0, len = sprayChunk.length; i < len; i++) {\n var point = sprayChunk[i];\n if (typeof point.opacity !== 'undefined') {\n ctx.globalAlpha = point.opacity;\n }\n ctx.fillRect(point.x, point.y, point.width, point.width);\n }\n ctx.restore();\n },\n\n /**\n * Render all spray chunks\n */\n _render: function() {\n var ctx = this.canvas.contextTop, i, ilen;\n ctx.fillStyle = this.color;\n\n this._saveAndTransform(ctx);\n\n for (i = 0, ilen = this.sprayChunks.length; i < ilen; i++) {\n this.render(this.sprayChunks[i]);\n }\n ctx.restore();\n },\n\n /**\n * @param {Object} pointer\n */\n addSprayChunk: function(pointer) {\n this.sprayChunkPoints = [];\n\n var x, y, width, radius = this.width / 2, i;\n\n for (i = 0; i < this.density; i++) {\n\n x = fabric.util.getRandomInt(pointer.x - radius, pointer.x + radius);\n y = fabric.util.getRandomInt(pointer.y - radius, pointer.y + radius);\n\n if (this.dotWidthVariance) {\n width = fabric.util.getRandomInt(\n // bottom clamp width to 1\n Math.max(1, this.dotWidth - this.dotWidthVariance),\n this.dotWidth + this.dotWidthVariance);\n }\n else {\n width = this.dotWidth;\n }\n\n var point = new fabric.Point(x, y);\n point.width = width;\n\n if (this.randomOpacity) {\n point.opacity = fabric.util.getRandomInt(0, 100) / 100;\n }\n\n this.sprayChunkPoints.push(point);\n }\n\n this.sprayChunks.push(this.sprayChunkPoints);\n }\n});\n\n\n/**\n * PatternBrush class\n * @class fabric.PatternBrush\n * @extends fabric.BaseBrush\n */\nfabric.PatternBrush = fabric.util.createClass(fabric.PencilBrush, /** @lends fabric.PatternBrush.prototype */ {\n\n getPatternSrc: function() {\n\n var dotWidth = 20,\n dotDistance = 5,\n patternCanvas = fabric.util.createCanvasElement(),\n patternCtx = patternCanvas.getContext('2d');\n\n patternCanvas.width = patternCanvas.height = dotWidth + dotDistance;\n\n patternCtx.fillStyle = this.color;\n patternCtx.beginPath();\n patternCtx.arc(dotWidth / 2, dotWidth / 2, dotWidth / 2, 0, Math.PI * 2, false);\n patternCtx.closePath();\n patternCtx.fill();\n\n return patternCanvas;\n },\n\n getPatternSrcFunction: function() {\n return String(this.getPatternSrc).replace('this.color', '\"' + this.color + '\"');\n },\n\n /**\n * Creates \"pattern\" instance property\n * @param {CanvasRenderingContext2D} ctx\n */\n getPattern: function(ctx) {\n return ctx.createPattern(this.source || this.getPatternSrc(), 'repeat');\n },\n\n /**\n * Sets brush styles\n * @param {CanvasRenderingContext2D} ctx\n */\n _setBrushStyles: function(ctx) {\n this.callSuper('_setBrushStyles', ctx);\n ctx.strokeStyle = this.getPattern(ctx);\n },\n\n /**\n * Creates path\n */\n createPath: function(pathData) {\n var path = this.callSuper('createPath', pathData),\n topLeft = path._getLeftTopCoords().scalarAdd(path.strokeWidth / 2);\n\n path.stroke = new fabric.Pattern({\n source: this.source || this.getPatternSrcFunction(),\n offsetX: -topLeft.x,\n offsetY: -topLeft.y\n });\n return path;\n }\n});\n\n\n(function() {\n\n var getPointer = fabric.util.getPointer,\n degreesToRadians = fabric.util.degreesToRadians,\n isTouchEvent = fabric.util.isTouchEvent;\n\n /**\n * Canvas class\n * @class fabric.Canvas\n * @extends fabric.StaticCanvas\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#canvas}\n * @see {@link fabric.Canvas#initialize} for constructor definition\n *\n * @fires object:modified at the end of a transform or any change when statefull is true\n * @fires object:rotating while an object is being rotated from the control\n * @fires object:scaling while an object is being scaled by controls\n * @fires object:moving while an object is being dragged\n * @fires object:skewing while an object is being skewed from the controls\n *\n * @fires before:transform before a transform is is started\n * @fires before:selection:cleared\n * @fires selection:cleared\n * @fires selection:updated\n * @fires selection:created\n *\n * @fires path:created after a drawing operation ends and the path is added\n * @fires mouse:down\n * @fires mouse:move\n * @fires mouse:up\n * @fires mouse:down:before on mouse down, before the inner fabric logic runs\n * @fires mouse:move:before on mouse move, before the inner fabric logic runs\n * @fires mouse:up:before on mouse up, before the inner fabric logic runs\n * @fires mouse:over\n * @fires mouse:out\n * @fires mouse:dblclick whenever a native dbl click event fires on the canvas.\n *\n * @fires dragover\n * @fires dragenter\n * @fires dragleave\n * @fires drop:before before drop event. same native event. This is added to handle edge cases\n * @fires drop\n * @fires after:render at the end of the render process, receives the context in the callback\n * @fires before:render at start the render process, receives the context in the callback\n *\n */\n fabric.Canvas = fabric.util.createClass(fabric.StaticCanvas, /** @lends fabric.Canvas.prototype */ {\n\n /**\n * Constructor\n * @param {HTMLElement | String} el <canvas> element to initialize instance on\n * @param {Object} [options] Options object\n * @return {Object} thisArg\n */\n initialize: function(el, options) {\n options || (options = { });\n this.renderAndResetBound = this.renderAndReset.bind(this);\n this.requestRenderAllBound = this.requestRenderAll.bind(this);\n this._initStatic(el, options);\n this._initInteractive();\n this._createCacheCanvas();\n },\n\n /**\n * When true, objects can be transformed by one side (unproportionally)\n * when dragged on the corners that normally would not do that.\n * @type Boolean\n * @default\n * @since fabric 4.0 // changed name and default value\n */\n uniformScaling: true,\n\n /**\n * Indicates which key switches uniform scaling.\n * values: 'altKey', 'shiftKey', 'ctrlKey'.\n * If `null` or 'none' or any other string that is not a modifier key\n * feature is disabled.\n * totally wrong named. this sounds like `uniform scaling`\n * if Canvas.uniformScaling is true, pressing this will set it to false\n * and viceversa.\n * @since 1.6.2\n * @type String\n * @default\n */\n uniScaleKey: 'shiftKey',\n\n /**\n * When true, objects use center point as the origin of scale transformation.\n * Backwards incompatibility note: This property replaces \"centerTransform\" (Boolean).\n * @since 1.3.4\n * @type Boolean\n * @default\n */\n centeredScaling: false,\n\n /**\n * When true, objects use center point as the origin of rotate transformation.\n * Backwards incompatibility note: This property replaces \"centerTransform\" (Boolean).\n * @since 1.3.4\n * @type Boolean\n * @default\n */\n centeredRotation: false,\n\n /**\n * Indicates which key enable centered Transform\n * values: 'altKey', 'shiftKey', 'ctrlKey'.\n * If `null` or 'none' or any other string that is not a modifier key\n * feature is disabled feature disabled.\n * @since 1.6.2\n * @type String\n * @default\n */\n centeredKey: 'altKey',\n\n /**\n * Indicates which key enable alternate action on corner\n * values: 'altKey', 'shiftKey', 'ctrlKey'.\n * If `null` or 'none' or any other string that is not a modifier key\n * feature is disabled feature disabled.\n * @since 1.6.2\n * @type String\n * @default\n */\n altActionKey: 'shiftKey',\n\n /**\n * Indicates that canvas is interactive. This property should not be changed.\n * @type Boolean\n * @default\n */\n interactive: true,\n\n /**\n * Indicates whether group selection should be enabled\n * @type Boolean\n * @default\n */\n selection: true,\n\n /**\n * Indicates which key or keys enable multiple click selection\n * Pass value as a string or array of strings\n * values: 'altKey', 'shiftKey', 'ctrlKey'.\n * If `null` or empty or containing any other string that is not a modifier key\n * feature is disabled.\n * @since 1.6.2\n * @type String|Array\n * @default\n */\n selectionKey: 'shiftKey',\n\n /**\n * Indicates which key enable alternative selection\n * in case of target overlapping with active object\n * values: 'altKey', 'shiftKey', 'ctrlKey'.\n * For a series of reason that come from the general expectations on how\n * things should work, this feature works only for preserveObjectStacking true.\n * If `null` or 'none' or any other string that is not a modifier key\n * feature is disabled.\n * @since 1.6.5\n * @type null|String\n * @default\n */\n altSelectionKey: null,\n\n /**\n * Color of selection\n * @type String\n * @default\n */\n selectionColor: 'rgba(100, 100, 255, 0.3)', // blue\n\n /**\n * Default dash array pattern\n * If not empty the selection border is dashed\n * @type Array\n */\n selectionDashArray: [],\n\n /**\n * Color of the border of selection (usually slightly darker than color of selection itself)\n * @type String\n * @default\n */\n selectionBorderColor: 'rgba(255, 255, 255, 0.3)',\n\n /**\n * Width of a line used in object/group selection\n * @type Number\n * @default\n */\n selectionLineWidth: 1,\n\n /**\n * Select only shapes that are fully contained in the dragged selection rectangle.\n * @type Boolean\n * @default\n */\n selectionFullyContained: false,\n\n /**\n * Default cursor value used when hovering over an object on canvas\n * @type String\n * @default\n */\n hoverCursor: 'move',\n\n /**\n * Default cursor value used when moving an object on canvas\n * @type String\n * @default\n */\n moveCursor: 'move',\n\n /**\n * Default cursor value used for the entire canvas\n * @type String\n * @default\n */\n defaultCursor: 'default',\n\n /**\n * Cursor value used during free drawing\n * @type String\n * @default\n */\n freeDrawingCursor: 'crosshair',\n\n /**\n * Cursor value used for disabled elements ( corners with disabled action )\n * @type String\n * @since 2.0.0\n * @default\n */\n notAllowedCursor: 'not-allowed',\n\n /**\n * Default element class that's given to wrapper (div) element of canvas\n * @type String\n * @default\n */\n containerClass: 'canvas-container',\n\n /**\n * When true, object detection happens on per-pixel basis rather than on per-bounding-box\n * @type Boolean\n * @default\n */\n perPixelTargetFind: false,\n\n /**\n * Number of pixels around target pixel to tolerate (consider active) during object detection\n * @type Number\n * @default\n */\n targetFindTolerance: 0,\n\n /**\n * When true, target detection is skipped. Target detection will return always undefined.\n * click selection won't work anymore, events will fire with no targets.\n * if something is selected before setting it to true, it will be deselected at the first click.\n * area selection will still work. check the `selection` property too.\n * if you deactivate both, you should look into staticCanvas.\n * @type Boolean\n * @default\n */\n skipTargetFind: false,\n\n /**\n * When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing.\n * After mousedown, mousemove creates a shape,\n * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas.\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-4#free_drawing}\n * @type Boolean\n * @default\n */\n isDrawingMode: false,\n\n /**\n * Indicates whether objects should remain in current stack position when selected.\n * When false objects are brought to top and rendered as part of the selection group\n * @type Boolean\n * @default\n */\n preserveObjectStacking: false,\n\n /**\n * Indicates the angle that an object will lock to while rotating.\n * @type Number\n * @since 1.6.7\n * @default\n */\n snapAngle: 0,\n\n /**\n * Indicates the distance from the snapAngle the rotation will lock to the snapAngle.\n * When `null`, the snapThreshold will default to the snapAngle.\n * @type null|Number\n * @since 1.6.7\n * @default\n */\n snapThreshold: null,\n\n /**\n * Indicates if the right click on canvas can output the context menu or not\n * @type Boolean\n * @since 1.6.5\n * @default\n */\n stopContextMenu: false,\n\n /**\n * Indicates if the canvas can fire right click events\n * @type Boolean\n * @since 1.6.5\n * @default\n */\n fireRightClick: false,\n\n /**\n * Indicates if the canvas can fire middle click events\n * @type Boolean\n * @since 1.7.8\n * @default\n */\n fireMiddleClick: false,\n\n /**\n * Keep track of the subTargets for Mouse Events\n * @type fabric.Object[]\n */\n targets: [],\n\n /**\n * When the option is enabled, PointerEvent is used instead of MouseEvent.\n * @type Boolean\n * @default\n */\n enablePointerEvents: false,\n\n /**\n * Keep track of the hovered target\n * @type fabric.Object\n * @private\n */\n _hoveredTarget: null,\n\n /**\n * hold the list of nested targets hovered\n * @type fabric.Object[]\n * @private\n */\n _hoveredTargets: [],\n\n /**\n * @private\n */\n _initInteractive: function() {\n this._currentTransform = null;\n this._groupSelector = null;\n this._initWrapperElement();\n this._createUpperCanvas();\n this._initEventListeners();\n\n this._initRetinaScaling();\n\n this.freeDrawingBrush = fabric.PencilBrush && new fabric.PencilBrush(this);\n\n this.calcOffset();\n },\n\n /**\n * Divides objects in two groups, one to render immediately\n * and one to render as activeGroup.\n * @return {Array} objects to render immediately and pushes the other in the activeGroup.\n */\n _chooseObjectsToRender: function() {\n var activeObjects = this.getActiveObjects(),\n object, objsToRender, activeGroupObjects;\n\n if (activeObjects.length > 0 && !this.preserveObjectStacking) {\n objsToRender = [];\n activeGroupObjects = [];\n for (var i = 0, length = this._objects.length; i < length; i++) {\n object = this._objects[i];\n if (activeObjects.indexOf(object) === -1 ) {\n objsToRender.push(object);\n }\n else {\n activeGroupObjects.push(object);\n }\n }\n if (activeObjects.length > 1) {\n this._activeObject._objects = activeGroupObjects;\n }\n objsToRender.push.apply(objsToRender, activeGroupObjects);\n }\n else {\n objsToRender = this._objects;\n }\n return objsToRender;\n },\n\n /**\n * Renders both the top canvas and the secondary container canvas.\n * @return {fabric.Canvas} instance\n * @chainable\n */\n renderAll: function () {\n if (this.contextTopDirty && !this._groupSelector && !this.isDrawingMode) {\n this.clearContext(this.contextTop);\n this.contextTopDirty = false;\n }\n if (this.hasLostContext) {\n this.renderTopLayer(this.contextTop);\n this.hasLostContext = false;\n }\n var canvasToDrawOn = this.contextContainer;\n this.renderCanvas(canvasToDrawOn, this._chooseObjectsToRender());\n return this;\n },\n\n renderTopLayer: function(ctx) {\n ctx.save();\n if (this.isDrawingMode && this._isCurrentlyDrawing) {\n this.freeDrawingBrush && this.freeDrawingBrush._render();\n this.contextTopDirty = true;\n }\n // we render the top context - last object\n if (this.selection && this._groupSelector) {\n this._drawSelection(ctx);\n this.contextTopDirty = true;\n }\n ctx.restore();\n },\n\n /**\n * Method to render only the top canvas.\n * Also used to render the group selection box.\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n renderTop: function () {\n var ctx = this.contextTop;\n this.clearContext(ctx);\n this.renderTopLayer(ctx);\n this.fire('after:render');\n return this;\n },\n\n /**\n * @private\n */\n _normalizePointer: function (object, pointer) {\n var m = object.calcTransformMatrix(),\n invertedM = fabric.util.invertTransform(m),\n vptPointer = this.restorePointerVpt(pointer);\n return fabric.util.transformPoint(vptPointer, invertedM);\n },\n\n /**\n * Returns true if object is transparent at a certain location\n * @param {fabric.Object} target Object to check\n * @param {Number} x Left coordinate\n * @param {Number} y Top coordinate\n * @return {Boolean}\n */\n isTargetTransparent: function (target, x, y) {\n // in case the target is the activeObject, we cannot execute this optimization\n // because we need to draw controls too.\n if (target.shouldCache() && target._cacheCanvas && target !== this._activeObject) {\n var normalizedPointer = this._normalizePointer(target, {x: x, y: y}),\n targetRelativeX = Math.max(target.cacheTranslationX + (normalizedPointer.x * target.zoomX), 0),\n targetRelativeY = Math.max(target.cacheTranslationY + (normalizedPointer.y * target.zoomY), 0);\n\n var isTransparent = fabric.util.isTransparent(\n target._cacheContext, Math.round(targetRelativeX), Math.round(targetRelativeY), this.targetFindTolerance);\n\n return isTransparent;\n }\n\n var ctx = this.contextCache,\n originalColor = target.selectionBackgroundColor, v = this.viewportTransform;\n\n target.selectionBackgroundColor = '';\n\n this.clearContext(ctx);\n\n ctx.save();\n ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);\n target.render(ctx);\n ctx.restore();\n\n target.selectionBackgroundColor = originalColor;\n\n var isTransparent = fabric.util.isTransparent(\n ctx, x, y, this.targetFindTolerance);\n\n return isTransparent;\n },\n\n /**\n * takes an event and determines if selection key has been pressed\n * @private\n * @param {Event} e Event object\n */\n _isSelectionKeyPressed: function(e) {\n var selectionKeyPressed = false;\n\n if (Array.isArray(this.selectionKey)) {\n selectionKeyPressed = !!this.selectionKey.find(function(key) { return e[key] === true; });\n }\n else {\n selectionKeyPressed = e[this.selectionKey];\n }\n\n return selectionKeyPressed;\n },\n\n /**\n * @private\n * @param {Event} e Event object\n * @param {fabric.Object} target\n */\n _shouldClearSelection: function (e, target) {\n var activeObjects = this.getActiveObjects(),\n activeObject = this._activeObject;\n\n return (\n !target\n ||\n (target &&\n activeObject &&\n activeObjects.length > 1 &&\n activeObjects.indexOf(target) === -1 &&\n activeObject !== target &&\n !this._isSelectionKeyPressed(e))\n ||\n (target && !target.evented)\n ||\n (target &&\n !target.selectable &&\n activeObject &&\n activeObject !== target)\n );\n },\n\n /**\n * centeredScaling from object can't override centeredScaling from canvas.\n * this should be fixed, since object setting should take precedence over canvas.\n * also this should be something that will be migrated in the control properties.\n * as ability to define the origin of the transformation that the control provide.\n * @private\n * @param {fabric.Object} target\n * @param {String} action\n * @param {Boolean} altKey\n */\n _shouldCenterTransform: function (target, action, altKey) {\n if (!target) {\n return;\n }\n\n var centerTransform;\n\n if (action === 'scale' || action === 'scaleX' || action === 'scaleY' || action === 'resizing') {\n centerTransform = this.centeredScaling || target.centeredScaling;\n }\n else if (action === 'rotate') {\n centerTransform = this.centeredRotation || target.centeredRotation;\n }\n\n return centerTransform ? !altKey : altKey;\n },\n\n /**\n * should disappear before release 4.0\n * @private\n */\n _getOriginFromCorner: function(target, corner) {\n var origin = {\n x: target.originX,\n y: target.originY\n };\n\n if (corner === 'ml' || corner === 'tl' || corner === 'bl') {\n origin.x = 'right';\n }\n else if (corner === 'mr' || corner === 'tr' || corner === 'br') {\n origin.x = 'left';\n }\n\n if (corner === 'tl' || corner === 'mt' || corner === 'tr') {\n origin.y = 'bottom';\n }\n else if (corner === 'bl' || corner === 'mb' || corner === 'br') {\n origin.y = 'top';\n }\n return origin;\n },\n\n /**\n * @private\n * @param {Boolean} alreadySelected true if target is already selected\n * @param {String} corner a string representing the corner ml, mr, tl ...\n * @param {Event} e Event object\n * @param {fabric.Object} [target] inserted back to help overriding. Unused\n */\n _getActionFromCorner: function(alreadySelected, corner, e, target) {\n if (!corner || !alreadySelected) {\n return 'drag';\n }\n var control = target.controls[corner];\n return control.getActionName(e, control, target);\n },\n\n /**\n * @private\n * @param {Event} e Event object\n * @param {fabric.Object} target\n */\n _setupCurrentTransform: function (e, target, alreadySelected) {\n if (!target) {\n return;\n }\n\n var pointer = this.getPointer(e), corner = target.__corner,\n control = target.controls[corner],\n actionHandler = (alreadySelected && corner) ?\n control.getActionHandler(e, target, control) : fabric.controlsUtils.dragHandler,\n action = this._getActionFromCorner(alreadySelected, corner, e, target),\n origin = this._getOriginFromCorner(target, corner),\n altKey = e[this.centeredKey],\n transform = {\n target: target,\n action: action,\n actionHandler: actionHandler,\n corner: corner,\n scaleX: target.scaleX,\n scaleY: target.scaleY,\n skewX: target.skewX,\n skewY: target.skewY,\n // used by transation\n offsetX: pointer.x - target.left,\n offsetY: pointer.y - target.top,\n originX: origin.x,\n originY: origin.y,\n ex: pointer.x,\n ey: pointer.y,\n lastX: pointer.x,\n lastY: pointer.y,\n // unsure they are useful anymore.\n // left: target.left,\n // top: target.top,\n theta: degreesToRadians(target.angle),\n // end of unsure\n width: target.width * target.scaleX,\n shiftKey: e.shiftKey,\n altKey: altKey,\n original: fabric.util.saveObjectTransform(target),\n };\n\n if (this._shouldCenterTransform(target, action, altKey)) {\n transform.originX = 'center';\n transform.originY = 'center';\n }\n transform.original.originX = origin.x;\n transform.original.originY = origin.y;\n this._currentTransform = transform;\n this._beforeTransform(e);\n },\n\n /**\n * Set the cursor type of the canvas element\n * @param {String} value Cursor type of the canvas element.\n * @see http://www.w3.org/TR/css3-ui/#cursor\n */\n setCursor: function (value) {\n this.upperCanvasEl.style.cursor = value;\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx to draw the selection on\n */\n _drawSelection: function (ctx) {\n var selector = this._groupSelector,\n viewportStart = new fabric.Point(selector.ex, selector.ey),\n start = fabric.util.transformPoint(viewportStart, this.viewportTransform),\n viewportExtent = new fabric.Point(selector.ex + selector.left, selector.ey + selector.top),\n extent = fabric.util.transformPoint(viewportExtent, this.viewportTransform),\n minX = Math.min(start.x, extent.x),\n minY = Math.min(start.y, extent.y),\n maxX = Math.max(start.x, extent.x),\n maxY = Math.max(start.y, extent.y),\n strokeOffset = this.selectionLineWidth / 2;\n\n if (this.selectionColor) {\n ctx.fillStyle = this.selectionColor;\n ctx.fillRect(minX, minY, maxX - minX, maxY - minY);\n }\n\n if (!this.selectionLineWidth || !this.selectionBorderColor) {\n return;\n }\n ctx.lineWidth = this.selectionLineWidth;\n ctx.strokeStyle = this.selectionBorderColor;\n\n minX += strokeOffset;\n minY += strokeOffset;\n maxX -= strokeOffset;\n maxY -= strokeOffset;\n // selection border\n fabric.Object.prototype._setLineDash.call(this, ctx, this.selectionDashArray);\n ctx.strokeRect(minX, minY, maxX - minX, maxY - minY);\n },\n\n /**\n * Method that determines what object we are clicking on\n * the skipGroup parameter is for internal use, is needed for shift+click action\n * 11/09/2018 TODO: would be cool if findTarget could discern between being a full target\n * or the outside part of the corner.\n * @param {Event} e mouse event\n * @param {Boolean} skipGroup when true, activeGroup is skipped and only objects are traversed through\n * @return {fabric.Object} the target found\n */\n findTarget: function (e, skipGroup) {\n if (this.skipTargetFind) {\n return;\n }\n\n var ignoreZoom = true,\n pointer = this.getPointer(e, ignoreZoom),\n activeObject = this._activeObject,\n aObjects = this.getActiveObjects(),\n activeTarget, activeTargetSubs,\n isTouch = isTouchEvent(e),\n shouldLookForActive = (aObjects.length > 1 && !skipGroup) || aObjects.length === 1;\n\n // first check current group (if one exists)\n // active group does not check sub targets like normal groups.\n // if active group just exits.\n this.targets = [];\n\n // if we hit the corner of an activeObject, let's return that.\n if (shouldLookForActive && activeObject._findTargetCorner(pointer, isTouch)) {\n return activeObject;\n }\n if (aObjects.length > 1 && !skipGroup && activeObject === this._searchPossibleTargets([activeObject], pointer)) {\n return activeObject;\n }\n if (aObjects.length === 1 &&\n activeObject === this._searchPossibleTargets([activeObject], pointer)) {\n if (!this.preserveObjectStacking) {\n return activeObject;\n }\n else {\n activeTarget = activeObject;\n activeTargetSubs = this.targets;\n this.targets = [];\n }\n }\n var target = this._searchPossibleTargets(this._objects, pointer);\n if (e[this.altSelectionKey] && target && activeTarget && target !== activeTarget) {\n target = activeTarget;\n this.targets = activeTargetSubs;\n }\n return target;\n },\n\n /**\n * Checks point is inside the object.\n * @param {Object} [pointer] x,y object of point coordinates we want to check.\n * @param {fabric.Object} obj Object to test against\n * @param {Object} [globalPointer] x,y object of point coordinates relative to canvas used to search per pixel target.\n * @return {Boolean} true if point is contained within an area of given object\n * @private\n */\n _checkTarget: function(pointer, obj, globalPointer) {\n if (obj &&\n obj.visible &&\n obj.evented &&\n // http://www.geog.ubc.ca/courses/klink/gis.notes/ncgia/u32.html\n // http://idav.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html\n obj.containsPoint(pointer)\n ) {\n if ((this.perPixelTargetFind || obj.perPixelTargetFind) && !obj.isEditing) {\n var isTransparent = this.isTargetTransparent(obj, globalPointer.x, globalPointer.y);\n if (!isTransparent) {\n return true;\n }\n }\n else {\n return true;\n }\n }\n },\n\n /**\n * Function used to search inside objects an object that contains pointer in bounding box or that contains pointerOnCanvas when painted\n * @param {Array} [objects] objects array to look into\n * @param {Object} [pointer] x,y object of point coordinates we want to check.\n * @return {fabric.Object} object that contains pointer\n * @private\n */\n _searchPossibleTargets: function(objects, pointer) {\n // Cache all targets where their bounding box contains point.\n var target, i = objects.length, subTarget;\n // Do not check for currently grouped objects, since we check the parent group itself.\n // until we call this function specifically to search inside the activeGroup\n while (i--) {\n var objToCheck = objects[i];\n var pointerToUse = objToCheck.group ?\n this._normalizePointer(objToCheck.group, pointer) : pointer;\n if (this._checkTarget(pointerToUse, objToCheck, pointer)) {\n target = objects[i];\n if (target.subTargetCheck && target instanceof fabric.Group) {\n subTarget = this._searchPossibleTargets(target._objects, pointer);\n subTarget && this.targets.push(subTarget);\n }\n break;\n }\n }\n return target;\n },\n\n /**\n * Returns pointer coordinates without the effect of the viewport\n * @param {Object} pointer with \"x\" and \"y\" number values\n * @return {Object} object with \"x\" and \"y\" number values\n */\n restorePointerVpt: function(pointer) {\n return fabric.util.transformPoint(\n pointer,\n fabric.util.invertTransform(this.viewportTransform)\n );\n },\n\n /**\n * Returns pointer coordinates relative to canvas.\n * Can return coordinates with or without viewportTransform.\n * ignoreZoom false gives back coordinates that represent\n * the point clicked on canvas element.\n * ignoreZoom true gives back coordinates after being processed\n * by the viewportTransform ( sort of coordinates of what is displayed\n * on the canvas where you are clicking.\n * ignoreZoom true = HTMLElement coordinates relative to top,left\n * ignoreZoom false, default = fabric space coordinates, the same used for shape position\n * To interact with your shapes top and left you want to use ignoreZoom true\n * most of the time, while ignoreZoom false will give you coordinates\n * compatible with the object.oCoords system.\n * of the time.\n * @param {Event} e\n * @param {Boolean} ignoreZoom\n * @return {Object} object with \"x\" and \"y\" number values\n */\n getPointer: function (e, ignoreZoom) {\n // return cached values if we are in the event processing chain\n if (this._absolutePointer && !ignoreZoom) {\n return this._absolutePointer;\n }\n if (this._pointer && ignoreZoom) {\n return this._pointer;\n }\n\n var pointer = getPointer(e),\n upperCanvasEl = this.upperCanvasEl,\n bounds = upperCanvasEl.getBoundingClientRect(),\n boundsWidth = bounds.width || 0,\n boundsHeight = bounds.height || 0,\n cssScale;\n\n if (!boundsWidth || !boundsHeight ) {\n if ('top' in bounds && 'bottom' in bounds) {\n boundsHeight = Math.abs( bounds.top - bounds.bottom );\n }\n if ('right' in bounds && 'left' in bounds) {\n boundsWidth = Math.abs( bounds.right - bounds.left );\n }\n }\n\n this.calcOffset();\n pointer.x = pointer.x - this._offset.left;\n pointer.y = pointer.y - this._offset.top;\n if (!ignoreZoom) {\n pointer = this.restorePointerVpt(pointer);\n }\n\n var retinaScaling = this.getRetinaScaling();\n if (retinaScaling !== 1) {\n pointer.x /= retinaScaling;\n pointer.y /= retinaScaling;\n }\n\n if (boundsWidth === 0 || boundsHeight === 0) {\n // If bounds are not available (i.e. not visible), do not apply scale.\n cssScale = { width: 1, height: 1 };\n }\n else {\n cssScale = {\n width: upperCanvasEl.width / boundsWidth,\n height: upperCanvasEl.height / boundsHeight\n };\n }\n\n return {\n x: pointer.x * cssScale.width,\n y: pointer.y * cssScale.height\n };\n },\n\n /**\n * @private\n * @throws {CANVAS_INIT_ERROR} If canvas can not be initialized\n */\n _createUpperCanvas: function () {\n var lowerCanvasClass = this.lowerCanvasEl.className.replace(/\\s*lower-canvas\\s*/, ''),\n lowerCanvasEl = this.lowerCanvasEl, upperCanvasEl = this.upperCanvasEl;\n\n // there is no need to create a new upperCanvas element if we have already one.\n if (upperCanvasEl) {\n upperCanvasEl.className = '';\n }\n else {\n upperCanvasEl = this._createCanvasElement();\n this.upperCanvasEl = upperCanvasEl;\n }\n fabric.util.addClass(upperCanvasEl, 'upper-canvas ' + lowerCanvasClass);\n\n this.wrapperEl.appendChild(upperCanvasEl);\n\n this._copyCanvasStyle(lowerCanvasEl, upperCanvasEl);\n this._applyCanvasStyle(upperCanvasEl);\n this.contextTop = upperCanvasEl.getContext('2d');\n },\n\n /**\n * Returns context of top canvas where interactions are drawn\n * @returns {CanvasRenderingContext2D}\n */\n getTopContext: function () {\n return this.contextTop;\n },\n\n /**\n * @private\n */\n _createCacheCanvas: function () {\n this.cacheCanvasEl = this._createCanvasElement();\n this.cacheCanvasEl.setAttribute('width', this.width);\n this.cacheCanvasEl.setAttribute('height', this.height);\n this.contextCache = this.cacheCanvasEl.getContext('2d');\n },\n\n /**\n * @private\n */\n _initWrapperElement: function () {\n this.wrapperEl = fabric.util.wrapElement(this.lowerCanvasEl, 'div', {\n 'class': this.containerClass\n });\n fabric.util.setStyle(this.wrapperEl, {\n width: this.width + 'px',\n height: this.height + 'px',\n position: 'relative'\n });\n fabric.util.makeElementUnselectable(this.wrapperEl);\n },\n\n /**\n * @private\n * @param {HTMLElement} element canvas element to apply styles on\n */\n _applyCanvasStyle: function (element) {\n var width = this.width || element.width,\n height = this.height || element.height;\n\n fabric.util.setStyle(element, {\n position: 'absolute',\n width: width + 'px',\n height: height + 'px',\n left: 0,\n top: 0,\n 'touch-action': this.allowTouchScrolling ? 'manipulation' : 'none',\n '-ms-touch-action': this.allowTouchScrolling ? 'manipulation' : 'none'\n });\n element.width = width;\n element.height = height;\n fabric.util.makeElementUnselectable(element);\n },\n\n /**\n * Copy the entire inline style from one element (fromEl) to another (toEl)\n * @private\n * @param {Element} fromEl Element style is copied from\n * @param {Element} toEl Element copied style is applied to\n */\n _copyCanvasStyle: function (fromEl, toEl) {\n toEl.style.cssText = fromEl.style.cssText;\n },\n\n /**\n * Returns context of canvas where object selection is drawn\n * @return {CanvasRenderingContext2D}\n */\n getSelectionContext: function() {\n return this.contextTop;\n },\n\n /**\n * Returns <canvas> element on which object selection is drawn\n * @return {HTMLCanvasElement}\n */\n getSelectionElement: function () {\n return this.upperCanvasEl;\n },\n\n /**\n * Returns currently active object\n * @return {fabric.Object} active object\n */\n getActiveObject: function () {\n return this._activeObject;\n },\n\n /**\n * Returns an array with the current selected objects\n * @return {fabric.Object} active object\n */\n getActiveObjects: function () {\n var active = this._activeObject;\n if (active) {\n if (active.type === 'activeSelection' && active._objects) {\n return active._objects.slice(0);\n }\n else {\n return [active];\n }\n }\n return [];\n },\n\n /**\n * @private\n * @param {fabric.Object} obj Object that was removed\n */\n _onObjectRemoved: function(obj) {\n // removing active object should fire \"selection:cleared\" events\n if (obj === this._activeObject) {\n this.fire('before:selection:cleared', { target: obj });\n this._discardActiveObject();\n this.fire('selection:cleared', { target: obj });\n obj.fire('deselected');\n }\n if (obj === this._hoveredTarget){\n this._hoveredTarget = null;\n this._hoveredTargets = [];\n }\n this.callSuper('_onObjectRemoved', obj);\n },\n\n /**\n * @private\n * Compares the old activeObject with the current one and fires correct events\n * @param {fabric.Object} obj old activeObject\n */\n _fireSelectionEvents: function(oldObjects, e) {\n var somethingChanged = false, objects = this.getActiveObjects(),\n added = [], removed = [];\n oldObjects.forEach(function(oldObject) {\n if (objects.indexOf(oldObject) === -1) {\n somethingChanged = true;\n oldObject.fire('deselected', {\n e: e,\n target: oldObject\n });\n removed.push(oldObject);\n }\n });\n objects.forEach(function(object) {\n if (oldObjects.indexOf(object) === -1) {\n somethingChanged = true;\n object.fire('selected', {\n e: e,\n target: object\n });\n added.push(object);\n }\n });\n if (oldObjects.length > 0 && objects.length > 0) {\n somethingChanged && this.fire('selection:updated', {\n e: e,\n selected: added,\n deselected: removed,\n });\n }\n else if (objects.length > 0) {\n this.fire('selection:created', {\n e: e,\n selected: added,\n });\n }\n else if (oldObjects.length > 0) {\n this.fire('selection:cleared', {\n e: e,\n deselected: removed,\n });\n }\n },\n\n /**\n * Sets given object as the only active object on canvas\n * @param {fabric.Object} object Object to set as an active one\n * @param {Event} [e] Event (passed along when firing \"object:selected\")\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n setActiveObject: function (object, e) {\n var currentActives = this.getActiveObjects();\n this._setActiveObject(object, e);\n this._fireSelectionEvents(currentActives, e);\n return this;\n },\n\n /**\n * This is a private method for now.\n * This is supposed to be equivalent to setActiveObject but without firing\n * any event. There is commitment to have this stay this way.\n * This is the functional part of setActiveObject.\n * @private\n * @param {Object} object to set as active\n * @param {Event} [e] Event (passed along when firing \"object:selected\")\n * @return {Boolean} true if the selection happened\n */\n _setActiveObject: function(object, e) {\n if (this._activeObject === object) {\n return false;\n }\n if (!this._discardActiveObject(e, object)) {\n return false;\n }\n if (object.onSelect({ e: e })) {\n return false;\n }\n this._activeObject = object;\n return true;\n },\n\n /**\n * This is a private method for now.\n * This is supposed to be equivalent to discardActiveObject but without firing\n * any events. There is commitment to have this stay this way.\n * This is the functional part of discardActiveObject.\n * @param {Event} [e] Event (passed along when firing \"object:deselected\")\n * @param {Object} object to set as active\n * @return {Boolean} true if the selection happened\n * @private\n */\n _discardActiveObject: function(e, object) {\n var obj = this._activeObject;\n if (obj) {\n // onDeselect return TRUE to cancel selection;\n if (obj.onDeselect({ e: e, object: object })) {\n return false;\n }\n this._activeObject = null;\n }\n return true;\n },\n\n /**\n * Discards currently active object and fire events. If the function is called by fabric\n * as a consequence of a mouse event, the event is passed as a parameter and\n * sent to the fire function for the custom events. When used as a method the\n * e param does not have any application.\n * @param {event} e\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n discardActiveObject: function (e) {\n var currentActives = this.getActiveObjects(), activeObject = this.getActiveObject();\n if (currentActives.length) {\n this.fire('before:selection:cleared', { target: activeObject, e: e });\n }\n this._discardActiveObject(e);\n this._fireSelectionEvents(currentActives, e);\n return this;\n },\n\n /**\n * Clears a canvas element and removes all event listeners\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n dispose: function () {\n var wrapper = this.wrapperEl;\n this.removeListeners();\n wrapper.removeChild(this.upperCanvasEl);\n wrapper.removeChild(this.lowerCanvasEl);\n this.contextCache = null;\n this.contextTop = null;\n ['upperCanvasEl', 'cacheCanvasEl'].forEach((function(element) {\n fabric.util.cleanUpJsdomNode(this[element]);\n this[element] = undefined;\n }).bind(this));\n if (wrapper.parentNode) {\n wrapper.parentNode.replaceChild(this.lowerCanvasEl, this.wrapperEl);\n }\n delete this.wrapperEl;\n fabric.StaticCanvas.prototype.dispose.call(this);\n return this;\n },\n\n /**\n * Clears all contexts (background, main, top) of an instance\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n clear: function () {\n // this.discardActiveGroup();\n this.discardActiveObject();\n this.clearContext(this.contextTop);\n return this.callSuper('clear');\n },\n\n /**\n * Draws objects' controls (borders/controls)\n * @param {CanvasRenderingContext2D} ctx Context to render controls on\n */\n drawControls: function(ctx) {\n var activeObject = this._activeObject;\n\n if (activeObject) {\n activeObject._renderControls(ctx);\n }\n },\n\n /**\n * @private\n */\n _toObject: function(instance, methodName, propertiesToInclude) {\n //If the object is part of the current selection group, it should\n //be transformed appropriately\n //i.e. it should be serialised as it would appear if the selection group\n //were to be destroyed.\n var originalProperties = this._realizeGroupTransformOnObject(instance),\n object = this.callSuper('_toObject', instance, methodName, propertiesToInclude);\n //Undo the damage we did by changing all of its properties\n this._unwindGroupTransformOnObject(instance, originalProperties);\n return object;\n },\n\n /**\n * Realises an object's group transformation on it\n * @private\n * @param {fabric.Object} [instance] the object to transform (gets mutated)\n * @returns the original values of instance which were changed\n */\n _realizeGroupTransformOnObject: function(instance) {\n if (instance.group && instance.group.type === 'activeSelection' && this._activeObject === instance.group) {\n var layoutProps = ['angle', 'flipX', 'flipY', 'left', 'scaleX', 'scaleY', 'skewX', 'skewY', 'top'];\n //Copy all the positionally relevant properties across now\n var originalValues = {};\n layoutProps.forEach(function(prop) {\n originalValues[prop] = instance[prop];\n });\n fabric.util.addTransformToObject(instance, this._activeObject.calcOwnMatrix());\n return originalValues;\n }\n else {\n return null;\n }\n },\n\n /**\n * Restores the changed properties of instance\n * @private\n * @param {fabric.Object} [instance] the object to un-transform (gets mutated)\n * @param {Object} [originalValues] the original values of instance, as returned by _realizeGroupTransformOnObject\n */\n _unwindGroupTransformOnObject: function(instance, originalValues) {\n if (originalValues) {\n instance.set(originalValues);\n }\n },\n\n /**\n * @private\n */\n _setSVGObject: function(markup, instance, reviver) {\n //If the object is in a selection group, simulate what would happen to that\n //object when the group is deselected\n var originalProperties = this._realizeGroupTransformOnObject(instance);\n this.callSuper('_setSVGObject', markup, instance, reviver);\n this._unwindGroupTransformOnObject(instance, originalProperties);\n },\n\n setViewportTransform: function (vpt) {\n if (this.renderOnAddRemove && this._activeObject && this._activeObject.isEditing) {\n this._activeObject.clearContextTop();\n }\n fabric.StaticCanvas.prototype.setViewportTransform.call(this, vpt);\n }\n });\n\n // copying static properties manually to work around Opera's bug,\n // where \"prototype\" property is enumerable and overrides existing prototype\n for (var prop in fabric.StaticCanvas) {\n if (prop !== 'prototype') {\n fabric.Canvas[prop] = fabric.StaticCanvas[prop];\n }\n }\n})();\n\n\n(function() {\n\n var addListener = fabric.util.addListener,\n removeListener = fabric.util.removeListener,\n RIGHT_CLICK = 3, MIDDLE_CLICK = 2, LEFT_CLICK = 1,\n addEventOptions = { passive: false };\n\n function checkClick(e, value) {\n return e.button && (e.button === value - 1);\n }\n\n fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {\n\n /**\n * Contains the id of the touch event that owns the fabric transform\n * @type Number\n * @private\n */\n mainTouchId: null,\n\n /**\n * Adds mouse listeners to canvas\n * @private\n */\n _initEventListeners: function () {\n // in case we initialized the class twice. This should not happen normally\n // but in some kind of applications where the canvas element may be changed\n // this is a workaround to having double listeners.\n this.removeListeners();\n this._bindEvents();\n this.addOrRemove(addListener, 'add');\n },\n\n /**\n * return an event prefix pointer or mouse.\n * @private\n */\n _getEventPrefix: function () {\n return this.enablePointerEvents ? 'pointer' : 'mouse';\n },\n\n addOrRemove: function(functor, eventjsFunctor) {\n var canvasElement = this.upperCanvasEl,\n eventTypePrefix = this._getEventPrefix();\n functor(fabric.window, 'resize', this._onResize);\n functor(canvasElement, eventTypePrefix + 'down', this._onMouseDown);\n functor(canvasElement, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);\n functor(canvasElement, eventTypePrefix + 'out', this._onMouseOut);\n functor(canvasElement, eventTypePrefix + 'enter', this._onMouseEnter);\n functor(canvasElement, 'wheel', this._onMouseWheel);\n functor(canvasElement, 'contextmenu', this._onContextMenu);\n functor(canvasElement, 'dblclick', this._onDoubleClick);\n functor(canvasElement, 'dragover', this._onDragOver);\n functor(canvasElement, 'dragenter', this._onDragEnter);\n functor(canvasElement, 'dragleave', this._onDragLeave);\n functor(canvasElement, 'drop', this._onDrop);\n if (!this.enablePointerEvents) {\n functor(canvasElement, 'touchstart', this._onTouchStart, addEventOptions);\n }\n if (typeof eventjs !== 'undefined' && eventjsFunctor in eventjs) {\n eventjs[eventjsFunctor](canvasElement, 'gesture', this._onGesture);\n eventjs[eventjsFunctor](canvasElement, 'drag', this._onDrag);\n eventjs[eventjsFunctor](canvasElement, 'orientation', this._onOrientationChange);\n eventjs[eventjsFunctor](canvasElement, 'shake', this._onShake);\n eventjs[eventjsFunctor](canvasElement, 'longpress', this._onLongPress);\n }\n },\n\n /**\n * Removes all event listeners\n */\n removeListeners: function() {\n this.addOrRemove(removeListener, 'remove');\n // if you dispose on a mouseDown, before mouse up, you need to clean document to...\n var eventTypePrefix = this._getEventPrefix();\n removeListener(fabric.document, eventTypePrefix + 'up', this._onMouseUp);\n removeListener(fabric.document, 'touchend', this._onTouchEnd, addEventOptions);\n removeListener(fabric.document, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);\n removeListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);\n },\n\n /**\n * @private\n */\n _bindEvents: function() {\n if (this.eventsBound) {\n // for any reason we pass here twice we do not want to bind events twice.\n return;\n }\n this._onMouseDown = this._onMouseDown.bind(this);\n this._onTouchStart = this._onTouchStart.bind(this);\n this._onMouseMove = this._onMouseMove.bind(this);\n this._onMouseUp = this._onMouseUp.bind(this);\n this._onTouchEnd = this._onTouchEnd.bind(this);\n this._onResize = this._onResize.bind(this);\n this._onGesture = this._onGesture.bind(this);\n this._onDrag = this._onDrag.bind(this);\n this._onShake = this._onShake.bind(this);\n this._onLongPress = this._onLongPress.bind(this);\n this._onOrientationChange = this._onOrientationChange.bind(this);\n this._onMouseWheel = this._onMouseWheel.bind(this);\n this._onMouseOut = this._onMouseOut.bind(this);\n this._onMouseEnter = this._onMouseEnter.bind(this);\n this._onContextMenu = this._onContextMenu.bind(this);\n this._onDoubleClick = this._onDoubleClick.bind(this);\n this._onDragOver = this._onDragOver.bind(this);\n this._onDragEnter = this._simpleEventHandler.bind(this, 'dragenter');\n this._onDragLeave = this._simpleEventHandler.bind(this, 'dragleave');\n this._onDrop = this._onDrop.bind(this);\n this.eventsBound = true;\n },\n\n /**\n * @private\n * @param {Event} [e] Event object fired on Event.js gesture\n * @param {Event} [self] Inner Event object\n */\n _onGesture: function(e, self) {\n this.__onTransformGesture && this.__onTransformGesture(e, self);\n },\n\n /**\n * @private\n * @param {Event} [e] Event object fired on Event.js drag\n * @param {Event} [self] Inner Event object\n */\n _onDrag: function(e, self) {\n this.__onDrag && this.__onDrag(e, self);\n },\n\n /**\n * @private\n * @param {Event} [e] Event object fired on wheel event\n */\n _onMouseWheel: function(e) {\n this.__onMouseWheel(e);\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousedown\n */\n _onMouseOut: function(e) {\n var target = this._hoveredTarget;\n this.fire('mouse:out', { target: target, e: e });\n this._hoveredTarget = null;\n target && target.fire('mouseout', { e: e });\n\n var _this = this;\n this._hoveredTargets.forEach(function(_target){\n _this.fire('mouse:out', { target: target, e: e });\n _target && target.fire('mouseout', { e: e });\n });\n this._hoveredTargets = [];\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mouseenter\n */\n _onMouseEnter: function(e) {\n // This find target and consequent 'mouse:over' is used to\n // clear old instances on hovered target.\n // calling findTarget has the side effect of killing target.__corner.\n // as a short term fix we are not firing this if we are currently transforming.\n // as a long term fix we need to separate the action of finding a target with the\n // side effects we added to it.\n if (!this._currentTransform && !this.findTarget(e)) {\n this.fire('mouse:over', { target: null, e: e });\n this._hoveredTarget = null;\n this._hoveredTargets = [];\n }\n },\n\n /**\n * @private\n * @param {Event} [e] Event object fired on Event.js orientation change\n * @param {Event} [self] Inner Event object\n */\n _onOrientationChange: function(e, self) {\n this.__onOrientationChange && this.__onOrientationChange(e, self);\n },\n\n /**\n * @private\n * @param {Event} [e] Event object fired on Event.js shake\n * @param {Event} [self] Inner Event object\n */\n _onShake: function(e, self) {\n this.__onShake && this.__onShake(e, self);\n },\n\n /**\n * @private\n * @param {Event} [e] Event object fired on Event.js shake\n * @param {Event} [self] Inner Event object\n */\n _onLongPress: function(e, self) {\n this.__onLongPress && this.__onLongPress(e, self);\n },\n\n /**\n * prevent default to allow drop event to be fired\n * @private\n * @param {Event} [e] Event object fired on Event.js shake\n */\n _onDragOver: function(e) {\n e.preventDefault();\n var target = this._simpleEventHandler('dragover', e);\n this._fireEnterLeaveEvents(target, e);\n },\n\n /**\n * `drop:before` is a an event that allow you to schedule logic\n * before the `drop` event. Prefer `drop` event always, but if you need\n * to run some drop-disabling logic on an event, since there is no way\n * to handle event handlers ordering, use `drop:before`\n * @param {Event} e\n */\n _onDrop: function (e) {\n this._simpleEventHandler('drop:before', e);\n return this._simpleEventHandler('drop', e);\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousedown\n */\n _onContextMenu: function (e) {\n if (this.stopContextMenu) {\n e.stopPropagation();\n e.preventDefault();\n }\n return false;\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousedown\n */\n _onDoubleClick: function (e) {\n this._cacheTransformEventData(e);\n this._handleEvent(e, 'dblclick');\n this._resetTransformEventData(e);\n },\n\n /**\n * Return a the id of an event.\n * returns either the pointerId or the identifier or 0 for the mouse event\n * @private\n * @param {Event} evt Event object\n */\n getPointerId: function(evt) {\n var changedTouches = evt.changedTouches;\n\n if (changedTouches) {\n return changedTouches[0] && changedTouches[0].identifier;\n }\n\n if (this.enablePointerEvents) {\n return evt.pointerId;\n }\n\n return -1;\n },\n\n /**\n * Determines if an event has the id of the event that is considered main\n * @private\n * @param {evt} event Event object\n */\n _isMainEvent: function(evt) {\n if (evt.isPrimary === true) {\n return true;\n }\n if (evt.isPrimary === false) {\n return false;\n }\n if (evt.type === 'touchend' && evt.touches.length === 0) {\n return true;\n }\n if (evt.changedTouches) {\n return evt.changedTouches[0].identifier === this.mainTouchId;\n }\n return true;\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousedown\n */\n _onTouchStart: function(e) {\n e.preventDefault();\n if (this.mainTouchId === null) {\n this.mainTouchId = this.getPointerId(e);\n }\n this.__onMouseDown(e);\n this._resetTransformEventData();\n var canvasElement = this.upperCanvasEl,\n eventTypePrefix = this._getEventPrefix();\n addListener(fabric.document, 'touchend', this._onTouchEnd, addEventOptions);\n addListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);\n // Unbind mousedown to prevent double triggers from touch devices\n removeListener(canvasElement, eventTypePrefix + 'down', this._onMouseDown);\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousedown\n */\n _onMouseDown: function (e) {\n this.__onMouseDown(e);\n this._resetTransformEventData();\n var canvasElement = this.upperCanvasEl,\n eventTypePrefix = this._getEventPrefix();\n removeListener(canvasElement, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);\n addListener(fabric.document, eventTypePrefix + 'up', this._onMouseUp);\n addListener(fabric.document, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousedown\n */\n _onTouchEnd: function(e) {\n if (e.touches.length > 0) {\n // if there are still touches stop here\n return;\n }\n this.__onMouseUp(e);\n this._resetTransformEventData();\n this.mainTouchId = null;\n var eventTypePrefix = this._getEventPrefix();\n removeListener(fabric.document, 'touchend', this._onTouchEnd, addEventOptions);\n removeListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);\n var _this = this;\n if (this._willAddMouseDown) {\n clearTimeout(this._willAddMouseDown);\n }\n this._willAddMouseDown = setTimeout(function() {\n // Wait 400ms before rebinding mousedown to prevent double triggers\n // from touch devices\n addListener(_this.upperCanvasEl, eventTypePrefix + 'down', _this._onMouseDown);\n _this._willAddMouseDown = 0;\n }, 400);\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mouseup\n */\n _onMouseUp: function (e) {\n this.__onMouseUp(e);\n this._resetTransformEventData();\n var canvasElement = this.upperCanvasEl,\n eventTypePrefix = this._getEventPrefix();\n if (this._isMainEvent(e)) {\n removeListener(fabric.document, eventTypePrefix + 'up', this._onMouseUp);\n removeListener(fabric.document, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);\n addListener(canvasElement, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);\n }\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousemove\n */\n _onMouseMove: function (e) {\n !this.allowTouchScrolling && e.preventDefault && e.preventDefault();\n this.__onMouseMove(e);\n },\n\n /**\n * @private\n */\n _onResize: function () {\n this.calcOffset();\n },\n\n /**\n * Decides whether the canvas should be redrawn in mouseup and mousedown events.\n * @private\n * @param {Object} target\n */\n _shouldRender: function(target) {\n var activeObject = this._activeObject;\n\n if (\n !!activeObject !== !!target ||\n (activeObject && target && (activeObject !== target))\n ) {\n // this covers: switch of target, from target to no target, selection of target\n // multiSelection with key and mouse\n return true;\n }\n else if (activeObject && activeObject.isEditing) {\n // if we mouse up/down over a editing textbox a cursor change,\n // there is no need to re render\n return false;\n }\n return false;\n },\n\n /**\n * Method that defines the actions when mouse is released on canvas.\n * The method resets the currentTransform parameters, store the image corner\n * position in the image object and render the canvas on top.\n * @private\n * @param {Event} e Event object fired on mouseup\n */\n __onMouseUp: function (e) {\n var target, transform = this._currentTransform,\n groupSelector = this._groupSelector, shouldRender = false,\n isClick = (!groupSelector || (groupSelector.left === 0 && groupSelector.top === 0));\n this._cacheTransformEventData(e);\n target = this._target;\n this._handleEvent(e, 'up:before');\n // if right/middle click just fire events and return\n // target undefined will make the _handleEvent search the target\n if (checkClick(e, RIGHT_CLICK)) {\n if (this.fireRightClick) {\n this._handleEvent(e, 'up', RIGHT_CLICK, isClick);\n }\n return;\n }\n\n if (checkClick(e, MIDDLE_CLICK)) {\n if (this.fireMiddleClick) {\n this._handleEvent(e, 'up', MIDDLE_CLICK, isClick);\n }\n this._resetTransformEventData();\n return;\n }\n\n if (this.isDrawingMode && this._isCurrentlyDrawing) {\n this._onMouseUpInDrawingMode(e);\n return;\n }\n\n if (!this._isMainEvent(e)) {\n return;\n }\n if (transform) {\n this._finalizeCurrentTransform(e);\n shouldRender = transform.actionPerformed;\n }\n if (!isClick) {\n var targetWasActive = target === this._activeObject;\n this._maybeGroupObjects(e);\n if (!shouldRender) {\n shouldRender = (\n this._shouldRender(target) ||\n (!targetWasActive && target === this._activeObject)\n );\n }\n }\n var corner, pointer;\n if (target) {\n corner = target._findTargetCorner(\n this.getPointer(e, true),\n fabric.util.isTouchEvent(e)\n );\n if (target.selectable && target !== this._activeObject && target.activeOn === 'up') {\n this.setActiveObject(target, e);\n shouldRender = true;\n }\n else {\n var control = target.controls[corner],\n mouseUpHandler = control && control.getMouseUpHandler(e, target, control);\n if (mouseUpHandler) {\n pointer = this.getPointer(e);\n mouseUpHandler(e, transform, pointer.x, pointer.y);\n }\n }\n target.isMoving = false;\n }\n // if we are ending up a transform on a different control or a new object\n // fire the original mouse up from the corner that started the transform\n if (transform && (transform.target !== target || transform.corner !== corner)) {\n var originalControl = transform.target && transform.target.controls[transform.corner],\n originalMouseUpHandler = originalControl && originalControl.getMouseUpHandler(e, target, control);\n pointer = pointer || this.getPointer(e);\n originalMouseUpHandler && originalMouseUpHandler(e, transform, pointer.x, pointer.y);\n }\n this._setCursorFromEvent(e, target);\n this._handleEvent(e, 'up', LEFT_CLICK, isClick);\n this._groupSelector = null;\n this._currentTransform = null;\n // reset the target information about which corner is selected\n target && (target.__corner = 0);\n if (shouldRender) {\n this.requestRenderAll();\n }\n else if (!isClick) {\n this.renderTop();\n }\n },\n\n /**\n * @private\n * Handle event firing for target and subtargets\n * @param {Event} e event from mouse\n * @param {String} eventType event to fire (up, down or move)\n * @return {Fabric.Object} target return the the target found, for internal reasons.\n */\n _simpleEventHandler: function(eventType, e) {\n var target = this.findTarget(e),\n targets = this.targets,\n options = {\n e: e,\n target: target,\n subTargets: targets,\n };\n this.fire(eventType, options);\n target && target.fire(eventType, options);\n if (!targets) {\n return target;\n }\n for (var i = 0; i < targets.length; i++) {\n targets[i].fire(eventType, options);\n }\n return target;\n },\n\n /**\n * @private\n * Handle event firing for target and subtargets\n * @param {Event} e event from mouse\n * @param {String} eventType event to fire (up, down or move)\n * @param {fabric.Object} targetObj receiving event\n * @param {Number} [button] button used in the event 1 = left, 2 = middle, 3 = right\n * @param {Boolean} isClick for left button only, indicates that the mouse up happened without move.\n */\n _handleEvent: function(e, eventType, button, isClick) {\n var target = this._target,\n targets = this.targets || [],\n options = {\n e: e,\n target: target,\n subTargets: targets,\n button: button || LEFT_CLICK,\n isClick: isClick || false,\n pointer: this._pointer,\n absolutePointer: this._absolutePointer,\n transform: this._currentTransform\n };\n if (eventType === 'up') {\n options.currentTarget = this.findTarget(e);\n options.currentSubTargets = this.targets;\n }\n this.fire('mouse:' + eventType, options);\n target && target.fire('mouse' + eventType, options);\n for (var i = 0; i < targets.length; i++) {\n targets[i].fire('mouse' + eventType, options);\n }\n },\n\n /**\n * @private\n * @param {Event} e send the mouse event that generate the finalize down, so it can be used in the event\n */\n _finalizeCurrentTransform: function(e) {\n\n var transform = this._currentTransform,\n target = transform.target,\n options = {\n e: e,\n target: target,\n transform: transform,\n action: transform.action,\n };\n\n if (target._scaling) {\n target._scaling = false;\n }\n\n target.setCoords();\n\n if (transform.actionPerformed || (this.stateful && target.hasStateChanged())) {\n this._fire('modified', options);\n }\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousedown\n */\n _onMouseDownInDrawingMode: function(e) {\n this._isCurrentlyDrawing = true;\n if (this.getActiveObject()) {\n this.discardActiveObject(e).requestRenderAll();\n }\n var pointer = this.getPointer(e);\n this.freeDrawingBrush.onMouseDown(pointer, { e: e, pointer: pointer });\n this._handleEvent(e, 'down');\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mousemove\n */\n _onMouseMoveInDrawingMode: function(e) {\n if (this._isCurrentlyDrawing) {\n var pointer = this.getPointer(e);\n this.freeDrawingBrush.onMouseMove(pointer, { e: e, pointer: pointer });\n }\n this.setCursor(this.freeDrawingCursor);\n this._handleEvent(e, 'move');\n },\n\n /**\n * @private\n * @param {Event} e Event object fired on mouseup\n */\n _onMouseUpInDrawingMode: function(e) {\n var pointer = this.getPointer(e);\n this._isCurrentlyDrawing = this.freeDrawingBrush.onMouseUp({ e: e, pointer: pointer });\n this._handleEvent(e, 'up');\n },\n\n /**\n * Method that defines the actions when mouse is clicked on canvas.\n * The method inits the currentTransform parameters and renders all the\n * canvas so the current image can be placed on the top canvas and the rest\n * in on the container one.\n * @private\n * @param {Event} e Event object fired on mousedown\n */\n __onMouseDown: function (e) {\n this._cacheTransformEventData(e);\n this._handleEvent(e, 'down:before');\n var target = this._target;\n // if right click just fire events\n if (checkClick(e, RIGHT_CLICK)) {\n if (this.fireRightClick) {\n this._handleEvent(e, 'down', RIGHT_CLICK);\n }\n return;\n }\n\n if (checkClick(e, MIDDLE_CLICK)) {\n if (this.fireMiddleClick) {\n this._handleEvent(e, 'down', MIDDLE_CLICK);\n }\n return;\n }\n\n if (this.isDrawingMode) {\n this._onMouseDownInDrawingMode(e);\n return;\n }\n\n if (!this._isMainEvent(e)) {\n return;\n }\n\n // ignore if some object is being transformed at this moment\n if (this._currentTransform) {\n return;\n }\n\n var pointer = this._pointer;\n // save pointer for check in __onMouseUp event\n this._previousPointer = pointer;\n var shouldRender = this._shouldRender(target),\n shouldGroup = this._shouldGroup(e, target);\n if (this._shouldClearSelection(e, target)) {\n this.discardActiveObject(e);\n }\n else if (shouldGroup) {\n this._handleGrouping(e, target);\n target = this._activeObject;\n }\n\n if (this.selection && (!target ||\n (!target.selectable && !target.isEditing && target !== this._activeObject))) {\n this._groupSelector = {\n ex: this._absolutePointer.x,\n ey: this._absolutePointer.y,\n top: 0,\n left: 0\n };\n }\n\n if (target) {\n var alreadySelected = target === this._activeObject;\n if (target.selectable && target.activeOn === 'down') {\n this.setActiveObject(target, e);\n }\n var corner = target._findTargetCorner(\n this.getPointer(e, true),\n fabric.util.isTouchEvent(e)\n );\n target.__corner = corner;\n if (target === this._activeObject && (corner || !shouldGroup)) {\n this._setupCurrentTransform(e, target, alreadySelected);\n var control = target.controls[corner],\n pointer = this.getPointer(e),\n mouseDownHandler = control && control.getMouseDownHandler(e, target, control);\n if (mouseDownHandler) {\n mouseDownHandler(e, this._currentTransform, pointer.x, pointer.y);\n }\n }\n }\n this._handleEvent(e, 'down');\n // we must renderAll so that we update the visuals\n (shouldRender || shouldGroup) && this.requestRenderAll();\n },\n\n /**\n * reset cache form common information needed during event processing\n * @private\n */\n _resetTransformEventData: function() {\n this._target = null;\n this._pointer = null;\n this._absolutePointer = null;\n },\n\n /**\n * Cache common information needed during event processing\n * @private\n * @param {Event} e Event object fired on event\n */\n _cacheTransformEventData: function(e) {\n // reset in order to avoid stale caching\n this._resetTransformEventData();\n this._pointer = this.getPointer(e, true);\n this._absolutePointer = this.restorePointerVpt(this._pointer);\n this._target = this._currentTransform ? this._currentTransform.target : this.findTarget(e) || null;\n },\n\n /**\n * @private\n */\n _beforeTransform: function(e) {\n var t = this._currentTransform;\n this.stateful && t.target.saveState();\n this.fire('before:transform', {\n e: e,\n transform: t,\n });\n },\n\n /**\n * Method that defines the actions when mouse is hovering the canvas.\n * The currentTransform parameter will define whether the user is rotating/scaling/translating\n * an image or neither of them (only hovering). A group selection is also possible and would cancel\n * all any other type of action.\n * In case of an image transformation only the top canvas will be rendered.\n * @private\n * @param {Event} e Event object fired on mousemove\n */\n __onMouseMove: function (e) {\n this._handleEvent(e, 'move:before');\n this._cacheTransformEventData(e);\n var target, pointer;\n\n if (this.isDrawingMode) {\n this._onMouseMoveInDrawingMode(e);\n return;\n }\n\n if (!this._isMainEvent(e)) {\n return;\n }\n\n var groupSelector = this._groupSelector;\n\n // We initially clicked in an empty area, so we draw a box for multiple selection\n if (groupSelector) {\n pointer = this._absolutePointer;\n\n groupSelector.left = pointer.x - groupSelector.ex;\n groupSelector.top = pointer.y - groupSelector.ey;\n\n this.renderTop();\n }\n else if (!this._currentTransform) {\n target = this.findTarget(e) || null;\n this._setCursorFromEvent(e, target);\n this._fireOverOutEvents(target, e);\n }\n else {\n this._transformObject(e);\n }\n this._handleEvent(e, 'move');\n this._resetTransformEventData();\n },\n\n /**\n * Manage the mouseout, mouseover events for the fabric object on the canvas\n * @param {Fabric.Object} target the target where the target from the mousemove event\n * @param {Event} e Event object fired on mousemove\n * @private\n */\n _fireOverOutEvents: function(target, e) {\n var _hoveredTarget = this._hoveredTarget,\n _hoveredTargets = this._hoveredTargets, targets = this.targets,\n length = Math.max(_hoveredTargets.length, targets.length);\n\n this.fireSyntheticInOutEvents(target, e, {\n oldTarget: _hoveredTarget,\n evtOut: 'mouseout',\n canvasEvtOut: 'mouse:out',\n evtIn: 'mouseover',\n canvasEvtIn: 'mouse:over',\n });\n for (var i = 0; i < length; i++){\n this.fireSyntheticInOutEvents(targets[i], e, {\n oldTarget: _hoveredTargets[i],\n evtOut: 'mouseout',\n evtIn: 'mouseover',\n });\n }\n this._hoveredTarget = target;\n this._hoveredTargets = this.targets.concat();\n },\n\n /**\n * Manage the dragEnter, dragLeave events for the fabric objects on the canvas\n * @param {Fabric.Object} target the target where the target from the onDrag event\n * @param {Event} e Event object fired on ondrag\n * @private\n */\n _fireEnterLeaveEvents: function(target, e) {\n var _draggedoverTarget = this._draggedoverTarget,\n _hoveredTargets = this._hoveredTargets, targets = this.targets,\n length = Math.max(_hoveredTargets.length, targets.length);\n\n this.fireSyntheticInOutEvents(target, e, {\n oldTarget: _draggedoverTarget,\n evtOut: 'dragleave',\n evtIn: 'dragenter',\n });\n for (var i = 0; i < length; i++) {\n this.fireSyntheticInOutEvents(targets[i], e, {\n oldTarget: _hoveredTargets[i],\n evtOut: 'dragleave',\n evtIn: 'dragenter',\n });\n }\n this._draggedoverTarget = target;\n },\n\n /**\n * Manage the synthetic in/out events for the fabric objects on the canvas\n * @param {Fabric.Object} target the target where the target from the supported events\n * @param {Event} e Event object fired\n * @param {Object} config configuration for the function to work\n * @param {String} config.targetName property on the canvas where the old target is stored\n * @param {String} [config.canvasEvtOut] name of the event to fire at canvas level for out\n * @param {String} config.evtOut name of the event to fire for out\n * @param {String} [config.canvasEvtIn] name of the event to fire at canvas level for in\n * @param {String} config.evtIn name of the event to fire for in\n * @private\n */\n fireSyntheticInOutEvents: function(target, e, config) {\n var inOpt, outOpt, oldTarget = config.oldTarget, outFires, inFires,\n targetChanged = oldTarget !== target, canvasEvtIn = config.canvasEvtIn, canvasEvtOut = config.canvasEvtOut;\n if (targetChanged) {\n inOpt = { e: e, target: target, previousTarget: oldTarget };\n outOpt = { e: e, target: oldTarget, nextTarget: target };\n }\n inFires = target && targetChanged;\n outFires = oldTarget && targetChanged;\n if (outFires) {\n canvasEvtOut && this.fire(canvasEvtOut, outOpt);\n oldTarget.fire(config.evtOut, outOpt);\n }\n if (inFires) {\n canvasEvtIn && this.fire(canvasEvtIn, inOpt);\n target.fire(config.evtIn, inOpt);\n }\n },\n\n /**\n * Method that defines actions when an Event Mouse Wheel\n * @param {Event} e Event object fired on mouseup\n */\n __onMouseWheel: function(e) {\n this._cacheTransformEventData(e);\n this._handleEvent(e, 'wheel');\n this._resetTransformEventData();\n },\n\n /**\n * @private\n * @param {Event} e Event fired on mousemove\n */\n _transformObject: function(e) {\n var pointer = this.getPointer(e),\n transform = this._currentTransform;\n\n transform.reset = false;\n transform.shiftKey = e.shiftKey;\n transform.altKey = e[this.centeredKey];\n\n this._performTransformAction(e, transform, pointer);\n transform.actionPerformed && this.requestRenderAll();\n },\n\n /**\n * @private\n */\n _performTransformAction: function(e, transform, pointer) {\n var x = pointer.x,\n y = pointer.y,\n action = transform.action,\n actionPerformed = false,\n actionHandler = transform.actionHandler;\n // this object could be created from the function in the control handlers\n\n\n if (actionHandler) {\n actionPerformed = actionHandler(e, transform, x, y);\n }\n if (action === 'drag' && actionPerformed) {\n transform.target.isMoving = true;\n this.setCursor(transform.target.moveCursor || this.moveCursor);\n }\n transform.actionPerformed = transform.actionPerformed || actionPerformed;\n },\n\n /**\n * @private\n */\n _fire: fabric.controlsUtils.fireEvent,\n\n /**\n * Sets the cursor depending on where the canvas is being hovered.\n * Note: very buggy in Opera\n * @param {Event} e Event object\n * @param {Object} target Object that the mouse is hovering, if so.\n */\n _setCursorFromEvent: function (e, target) {\n if (!target) {\n this.setCursor(this.defaultCursor);\n return false;\n }\n var hoverCursor = target.hoverCursor || this.hoverCursor,\n activeSelection = this._activeObject && this._activeObject.type === 'activeSelection' ?\n this._activeObject : null,\n // only show proper corner when group selection is not active\n corner = (!activeSelection || !activeSelection.contains(target))\n // here we call findTargetCorner always with undefined for the touch parameter.\n // we assume that if you are using a cursor you do not need to interact with\n // the bigger touch area.\n && target._findTargetCorner(this.getPointer(e, true));\n\n if (!corner) {\n if (target.subTargetCheck){\n // hoverCursor should come from top-most subTarget,\n // so we walk the array backwards\n this.targets.concat().reverse().map(function(_target){\n hoverCursor = _target.hoverCursor || hoverCursor;\n });\n }\n this.setCursor(hoverCursor);\n }\n else {\n this.setCursor(this.getCornerCursor(corner, target, e));\n }\n },\n\n /**\n * @private\n */\n getCornerCursor: function(corner, target, e) {\n var control = target.controls[corner];\n return control.cursorStyleHandler(e, control, target);\n }\n });\n})();\n\n\n(function() {\n\n var min = Math.min,\n max = Math.max;\n\n fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {\n\n /**\n * @private\n * @param {Event} e Event object\n * @param {fabric.Object} target\n * @return {Boolean}\n */\n _shouldGroup: function(e, target) {\n var activeObject = this._activeObject;\n return activeObject && this._isSelectionKeyPressed(e) && target && target.selectable && this.selection &&\n (activeObject !== target || activeObject.type === 'activeSelection') && !target.onSelect({ e: e });\n },\n\n /**\n * @private\n * @param {Event} e Event object\n * @param {fabric.Object} target\n */\n _handleGrouping: function (e, target) {\n var activeObject = this._activeObject;\n // avoid multi select when shift click on a corner\n if (activeObject.__corner) {\n return;\n }\n if (target === activeObject) {\n // if it's a group, find target again, using activeGroup objects\n target = this.findTarget(e, true);\n // if even object is not found or we are on activeObjectCorner, bail out\n if (!target || !target.selectable) {\n return;\n }\n }\n if (activeObject && activeObject.type === 'activeSelection') {\n this._updateActiveSelection(target, e);\n }\n else {\n this._createActiveSelection(target, e);\n }\n },\n\n /**\n * @private\n */\n _updateActiveSelection: function(target, e) {\n var activeSelection = this._activeObject,\n currentActiveObjects = activeSelection._objects.slice(0);\n if (activeSelection.contains(target)) {\n activeSelection.removeWithUpdate(target);\n this._hoveredTarget = target;\n this._hoveredTargets = this.targets.concat();\n if (activeSelection.size() === 1) {\n // activate last remaining object\n this._setActiveObject(activeSelection.item(0), e);\n }\n }\n else {\n activeSelection.addWithUpdate(target);\n this._hoveredTarget = activeSelection;\n this._hoveredTargets = this.targets.concat();\n }\n this._fireSelectionEvents(currentActiveObjects, e);\n },\n\n /**\n * @private\n */\n _createActiveSelection: function(target, e) {\n var currentActives = this.getActiveObjects(), group = this._createGroup(target);\n this._hoveredTarget = group;\n // ISSUE 4115: should we consider subTargets here?\n // this._hoveredTargets = [];\n // this._hoveredTargets = this.targets.concat();\n this._setActiveObject(group, e);\n this._fireSelectionEvents(currentActives, e);\n },\n\n /**\n * @private\n * @param {Object} target\n */\n _createGroup: function(target) {\n var objects = this._objects,\n isActiveLower = objects.indexOf(this._activeObject) < objects.indexOf(target),\n groupObjects = isActiveLower\n ? [this._activeObject, target]\n : [target, this._activeObject];\n this._activeObject.isEditing && this._activeObject.exitEditing();\n return new fabric.ActiveSelection(groupObjects, {\n canvas: this\n });\n },\n\n /**\n * @private\n * @param {Event} e mouse event\n */\n _groupSelectedObjects: function (e) {\n\n var group = this._collectObjects(e),\n aGroup;\n\n // do not create group for 1 element only\n if (group.length === 1) {\n this.setActiveObject(group[0], e);\n }\n else if (group.length > 1) {\n aGroup = new fabric.ActiveSelection(group.reverse(), {\n canvas: this\n });\n this.setActiveObject(aGroup, e);\n }\n },\n\n /**\n * @private\n */\n _collectObjects: function(e) {\n var group = [],\n currentObject,\n x1 = this._groupSelector.ex,\n y1 = this._groupSelector.ey,\n x2 = x1 + this._groupSelector.left,\n y2 = y1 + this._groupSelector.top,\n selectionX1Y1 = new fabric.Point(min(x1, x2), min(y1, y2)),\n selectionX2Y2 = new fabric.Point(max(x1, x2), max(y1, y2)),\n allowIntersect = !this.selectionFullyContained,\n isClick = x1 === x2 && y1 === y2;\n // we iterate reverse order to collect top first in case of click.\n for (var i = this._objects.length; i--; ) {\n currentObject = this._objects[i];\n\n if (!currentObject || !currentObject.selectable || !currentObject.visible) {\n continue;\n }\n\n if ((allowIntersect && currentObject.intersectsWithRect(selectionX1Y1, selectionX2Y2, true)) ||\n currentObject.isContainedWithinRect(selectionX1Y1, selectionX2Y2, true) ||\n (allowIntersect && currentObject.containsPoint(selectionX1Y1, null, true)) ||\n (allowIntersect && currentObject.containsPoint(selectionX2Y2, null, true))\n ) {\n group.push(currentObject);\n // only add one object if it's a click\n if (isClick) {\n break;\n }\n }\n }\n\n if (group.length > 1) {\n group = group.filter(function(object) {\n return !object.onSelect({ e: e });\n });\n }\n\n return group;\n },\n\n /**\n * @private\n */\n _maybeGroupObjects: function(e) {\n if (this.selection && this._groupSelector) {\n this._groupSelectedObjects(e);\n }\n this.setCursor(this.defaultCursor);\n // clear selection and current transformation\n this._groupSelector = null;\n }\n });\n\n})();\n\n\n(function () {\n fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {\n\n /**\n * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately\n * @param {Object} [options] Options object\n * @param {String} [options.format=png] The format of the output image. Either \"jpeg\" or \"png\"\n * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.\n * @param {Number} [options.multiplier=1] Multiplier to scale by, to have consistent\n * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14\n * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14\n * @param {Number} [options.width] Cropping width. Introduced in v1.2.14\n * @param {Number} [options.height] Cropping height. Introduced in v1.2.14\n * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 2.0.0\n * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format\n * @see {@link http://jsfiddle.net/fabricjs/NfZVb/|jsFiddle demo}\n * @example Generate jpeg dataURL with lower quality\n * var dataURL = canvas.toDataURL({\n * format: 'jpeg',\n * quality: 0.8\n * });\n * @example Generate cropped png dataURL (clipping of canvas)\n * var dataURL = canvas.toDataURL({\n * format: 'png',\n * left: 100,\n * top: 100,\n * width: 200,\n * height: 200\n * });\n * @example Generate double scaled png dataURL\n * var dataURL = canvas.toDataURL({\n * format: 'png',\n * multiplier: 2\n * });\n */\n toDataURL: function (options) {\n options || (options = { });\n\n var format = options.format || 'png',\n quality = options.quality || 1,\n multiplier = (options.multiplier || 1) * (options.enableRetinaScaling ? this.getRetinaScaling() : 1),\n canvasEl = this.toCanvasElement(multiplier, options);\n return fabric.util.toDataURL(canvasEl, format, quality);\n },\n\n /**\n * Create a new HTMLCanvas element painted with the current canvas content.\n * No need to resize the actual one or repaint it.\n * Will transfer object ownership to a new canvas, paint it, and set everything back.\n * This is an intermediary step used to get to a dataUrl but also it is useful to\n * create quick image copies of a canvas without passing for the dataUrl string\n * @param {Number} [multiplier] a zoom factor.\n * @param {Object} [cropping] Cropping informations\n * @param {Number} [cropping.left] Cropping left offset.\n * @param {Number} [cropping.top] Cropping top offset.\n * @param {Number} [cropping.width] Cropping width.\n * @param {Number} [cropping.height] Cropping height.\n */\n toCanvasElement: function(multiplier, cropping) {\n multiplier = multiplier || 1;\n cropping = cropping || { };\n var scaledWidth = (cropping.width || this.width) * multiplier,\n scaledHeight = (cropping.height || this.height) * multiplier,\n zoom = this.getZoom(),\n originalWidth = this.width,\n originalHeight = this.height,\n newZoom = zoom * multiplier,\n vp = this.viewportTransform,\n translateX = (vp[4] - (cropping.left || 0)) * multiplier,\n translateY = (vp[5] - (cropping.top || 0)) * multiplier,\n originalInteractive = this.interactive,\n newVp = [newZoom, 0, 0, newZoom, translateX, translateY],\n originalRetina = this.enableRetinaScaling,\n canvasEl = fabric.util.createCanvasElement(),\n originalContextTop = this.contextTop;\n canvasEl.width = scaledWidth;\n canvasEl.height = scaledHeight;\n this.contextTop = null;\n this.enableRetinaScaling = false;\n this.interactive = false;\n this.viewportTransform = newVp;\n this.width = scaledWidth;\n this.height = scaledHeight;\n this.calcViewportBoundaries();\n this.renderCanvas(canvasEl.getContext('2d'), this._objects);\n this.viewportTransform = vp;\n this.width = originalWidth;\n this.height = originalHeight;\n this.calcViewportBoundaries();\n this.interactive = originalInteractive;\n this.enableRetinaScaling = originalRetina;\n this.contextTop = originalContextTop;\n return canvasEl;\n },\n });\n\n})();\n\n\nfabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {\n /**\n * Populates canvas with data from the specified JSON.\n * JSON format must conform to the one of {@link fabric.Canvas#toJSON}\n * @param {String|Object} json JSON string or object\n * @param {Function} callback Callback, invoked when json is parsed\n * and corresponding objects (e.g: {@link fabric.Image})\n * are initialized\n * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created.\n * @return {fabric.Canvas} instance\n * @chainable\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#deserialization}\n * @see {@link http://jsfiddle.net/fabricjs/fmgXt/|jsFiddle demo}\n * @example loadFromJSON\n * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));\n * @example loadFromJSON with reviver\n * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {\n * // `o` = json object\n * // `object` = fabric.Object instance\n * // ... do some stuff ...\n * });\n */\n loadFromJSON: function (json, callback, reviver) {\n if (!json) {\n return;\n }\n\n // serialize if it wasn't already\n var serialized = (typeof json === 'string')\n ? JSON.parse(json)\n : fabric.util.object.clone(json);\n\n var _this = this,\n clipPath = serialized.clipPath,\n renderOnAddRemove = this.renderOnAddRemove;\n\n this.renderOnAddRemove = false;\n\n delete serialized.clipPath;\n\n this._enlivenObjects(serialized.objects, function (enlivenedObjects) {\n _this.clear();\n _this._setBgOverlay(serialized, function () {\n if (clipPath) {\n _this._enlivenObjects([clipPath], function (enlivenedCanvasClip) {\n _this.clipPath = enlivenedCanvasClip[0];\n _this.__setupCanvas.call(_this, serialized, enlivenedObjects, renderOnAddRemove, callback);\n });\n }\n else {\n _this.__setupCanvas.call(_this, serialized, enlivenedObjects, renderOnAddRemove, callback);\n }\n });\n }, reviver);\n return this;\n },\n\n /**\n * @private\n * @param {Object} serialized Object with background and overlay information\n * @param {Array} restored canvas objects\n * @param {Function} cached renderOnAddRemove callback\n * @param {Function} callback Invoked after all background and overlay images/patterns loaded\n */\n __setupCanvas: function(serialized, enlivenedObjects, renderOnAddRemove, callback) {\n var _this = this;\n enlivenedObjects.forEach(function(obj, index) {\n // we splice the array just in case some custom classes restored from JSON\n // will add more object to canvas at canvas init.\n _this.insertAt(obj, index);\n });\n this.renderOnAddRemove = renderOnAddRemove;\n // remove parts i cannot set as options\n delete serialized.objects;\n delete serialized.backgroundImage;\n delete serialized.overlayImage;\n delete serialized.background;\n delete serialized.overlay;\n // this._initOptions does too many things to just\n // call it. Normally loading an Object from JSON\n // create the Object instance. Here the Canvas is\n // already an instance and we are just loading things over it\n this._setOptions(serialized);\n this.renderAll();\n callback && callback();\n },\n\n /**\n * @private\n * @param {Object} serialized Object with background and overlay information\n * @param {Function} callback Invoked after all background and overlay images/patterns loaded\n */\n _setBgOverlay: function(serialized, callback) {\n var loaded = {\n backgroundColor: false,\n overlayColor: false,\n backgroundImage: false,\n overlayImage: false\n };\n\n if (!serialized.backgroundImage && !serialized.overlayImage && !serialized.background && !serialized.overlay) {\n callback && callback();\n return;\n }\n\n var cbIfLoaded = function () {\n if (loaded.backgroundImage && loaded.overlayImage && loaded.backgroundColor && loaded.overlayColor) {\n callback && callback();\n }\n };\n\n this.__setBgOverlay('backgroundImage', serialized.backgroundImage, loaded, cbIfLoaded);\n this.__setBgOverlay('overlayImage', serialized.overlayImage, loaded, cbIfLoaded);\n this.__setBgOverlay('backgroundColor', serialized.background, loaded, cbIfLoaded);\n this.__setBgOverlay('overlayColor', serialized.overlay, loaded, cbIfLoaded);\n },\n\n /**\n * @private\n * @param {String} property Property to set (backgroundImage, overlayImage, backgroundColor, overlayColor)\n * @param {(Object|String)} value Value to set\n * @param {Object} loaded Set loaded property to true if property is set\n * @param {Object} callback Callback function to invoke after property is set\n */\n __setBgOverlay: function(property, value, loaded, callback) {\n var _this = this;\n\n if (!value) {\n loaded[property] = true;\n callback && callback();\n return;\n }\n\n if (property === 'backgroundImage' || property === 'overlayImage') {\n fabric.util.enlivenObjects([value], function(enlivedObject){\n _this[property] = enlivedObject[0];\n loaded[property] = true;\n callback && callback();\n });\n }\n else {\n this['set' + fabric.util.string.capitalize(property, true)](value, function() {\n loaded[property] = true;\n callback && callback();\n });\n }\n },\n\n /**\n * @private\n * @param {Array} objects\n * @param {Function} callback\n * @param {Function} [reviver]\n */\n _enlivenObjects: function (objects, callback, reviver) {\n if (!objects || objects.length === 0) {\n callback && callback([]);\n return;\n }\n\n fabric.util.enlivenObjects(objects, function(enlivenedObjects) {\n callback && callback(enlivenedObjects);\n }, null, reviver);\n },\n\n /**\n * @private\n * @param {String} format\n * @param {Function} callback\n */\n _toDataURL: function (format, callback) {\n this.clone(function (clone) {\n callback(clone.toDataURL(format));\n });\n },\n\n /**\n * @private\n * @param {String} format\n * @param {Number} multiplier\n * @param {Function} callback\n */\n _toDataURLWithMultiplier: function (format, multiplier, callback) {\n this.clone(function (clone) {\n callback(clone.toDataURLWithMultiplier(format, multiplier));\n });\n },\n\n /**\n * Clones canvas instance\n * @param {Object} [callback] Receives cloned instance as a first argument\n * @param {Array} [properties] Array of properties to include in the cloned canvas and children\n */\n clone: function (callback, properties) {\n var data = JSON.stringify(this.toJSON(properties));\n this.cloneWithoutData(function(clone) {\n clone.loadFromJSON(data, function() {\n callback && callback(clone);\n });\n });\n },\n\n /**\n * Clones canvas instance without cloning existing data.\n * This essentially copies canvas dimensions, clipping properties, etc.\n * but leaves data empty (so that you can populate it with your own)\n * @param {Object} [callback] Receives cloned instance as a first argument\n */\n cloneWithoutData: function(callback) {\n var el = fabric.util.createCanvasElement();\n\n el.width = this.width;\n el.height = this.height;\n\n var clone = new fabric.Canvas(el);\n if (this.backgroundImage) {\n clone.setBackgroundImage(this.backgroundImage.src, function() {\n clone.renderAll();\n callback && callback(clone);\n });\n clone.backgroundImageOpacity = this.backgroundImageOpacity;\n clone.backgroundImageStretch = this.backgroundImageStretch;\n }\n else {\n callback && callback(clone);\n }\n }\n});\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n extend = fabric.util.object.extend,\n clone = fabric.util.object.clone,\n toFixed = fabric.util.toFixed,\n capitalize = fabric.util.string.capitalize,\n degreesToRadians = fabric.util.degreesToRadians,\n objectCaching = !fabric.isLikelyNode,\n ALIASING_LIMIT = 2;\n\n if (fabric.Object) {\n return;\n }\n\n /**\n * Root object class from which all 2d shape classes inherit from\n * @class fabric.Object\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#objects}\n * @see {@link fabric.Object#initialize} for constructor definition\n *\n * @fires added\n * @fires removed\n *\n * @fires selected\n * @fires deselected\n * @fires modified\n * @fires modified\n * @fires moved\n * @fires scaled\n * @fires rotated\n * @fires skewed\n *\n * @fires rotating\n * @fires scaling\n * @fires moving\n * @fires skewing\n *\n * @fires mousedown\n * @fires mouseup\n * @fires mouseover\n * @fires mouseout\n * @fires mousewheel\n * @fires mousedblclick\n *\n * @fires dragover\n * @fires dragenter\n * @fires dragleave\n * @fires drop\n */\n fabric.Object = fabric.util.createClass(fabric.CommonMethods, /** @lends fabric.Object.prototype */ {\n\n /**\n * Type of an object (rect, circle, path, etc.).\n * Note that this property is meant to be read-only and not meant to be modified.\n * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly.\n * @type String\n * @default\n */\n type: 'object',\n\n /**\n * Horizontal origin of transformation of an object (one of \"left\", \"right\", \"center\")\n * See http://jsfiddle.net/1ow02gea/244/ on how originX/originY affect objects in groups\n * @type String\n * @default\n */\n originX: 'left',\n\n /**\n * Vertical origin of transformation of an object (one of \"top\", \"bottom\", \"center\")\n * See http://jsfiddle.net/1ow02gea/244/ on how originX/originY affect objects in groups\n * @type String\n * @default\n */\n originY: 'top',\n\n /**\n * Top position of an object. Note that by default it's relative to object top. You can change this by setting originY={top/center/bottom}\n * @type Number\n * @default\n */\n top: 0,\n\n /**\n * Left position of an object. Note that by default it's relative to object left. You can change this by setting originX={left/center/right}\n * @type Number\n * @default\n */\n left: 0,\n\n /**\n * Object width\n * @type Number\n * @default\n */\n width: 0,\n\n /**\n * Object height\n * @type Number\n * @default\n */\n height: 0,\n\n /**\n * Object scale factor (horizontal)\n * @type Number\n * @default\n */\n scaleX: 1,\n\n /**\n * Object scale factor (vertical)\n * @type Number\n * @default\n */\n scaleY: 1,\n\n /**\n * When true, an object is rendered as flipped horizontally\n * @type Boolean\n * @default\n */\n flipX: false,\n\n /**\n * When true, an object is rendered as flipped vertically\n * @type Boolean\n * @default\n */\n flipY: false,\n\n /**\n * Opacity of an object\n * @type Number\n * @default\n */\n opacity: 1,\n\n /**\n * Angle of rotation of an object (in degrees)\n * @type Number\n * @default\n */\n angle: 0,\n\n /**\n * Angle of skew on x axes of an object (in degrees)\n * @type Number\n * @default\n */\n skewX: 0,\n\n /**\n * Angle of skew on y axes of an object (in degrees)\n * @type Number\n * @default\n */\n skewY: 0,\n\n /**\n * Size of object's controlling corners (in pixels)\n * @type Number\n * @default\n */\n cornerSize: 13,\n\n /**\n * Size of object's controlling corners when touch interaction is detected\n * @type Number\n * @default\n */\n touchCornerSize: 24,\n\n /**\n * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill)\n * @type Boolean\n * @default\n */\n transparentCorners: true,\n\n /**\n * Default cursor value used when hovering over this object on canvas\n * @type String\n * @default\n */\n hoverCursor: null,\n\n /**\n * Default cursor value used when moving this object on canvas\n * @type String\n * @default\n */\n moveCursor: null,\n\n /**\n * Padding between object and its controlling borders (in pixels)\n * @type Number\n * @default\n */\n padding: 0,\n\n /**\n * Color of controlling borders of an object (when it's active)\n * @type String\n * @default\n */\n borderColor: 'rgb(178,204,255)',\n\n /**\n * Array specifying dash pattern of an object's borders (hasBorder must be true)\n * @since 1.6.2\n * @type Array\n */\n borderDashArray: null,\n\n /**\n * Color of controlling corners of an object (when it's active)\n * @type String\n * @default\n */\n cornerColor: 'rgb(178,204,255)',\n\n /**\n * Color of controlling corners of an object (when it's active and transparentCorners false)\n * @since 1.6.2\n * @type String\n * @default\n */\n cornerStrokeColor: null,\n\n /**\n * Specify style of control, 'rect' or 'circle'\n * @since 1.6.2\n * @type String\n */\n cornerStyle: 'rect',\n\n /**\n * Array specifying dash pattern of an object's control (hasBorder must be true)\n * @since 1.6.2\n * @type Array\n */\n cornerDashArray: null,\n\n /**\n * When true, this object will use center point as the origin of transformation\n * when being scaled via the controls.\n * Backwards incompatibility note: This property replaces \"centerTransform\" (Boolean).\n * @since 1.3.4\n * @type Boolean\n * @default\n */\n centeredScaling: false,\n\n /**\n * When true, this object will use center point as the origin of transformation\n * when being rotated via the controls.\n * Backwards incompatibility note: This property replaces \"centerTransform\" (Boolean).\n * @since 1.3.4\n * @type Boolean\n * @default\n */\n centeredRotation: true,\n\n /**\n * Color of object's fill\n * takes css colors https://www.w3.org/TR/css-color-3/\n * @type String\n * @default\n */\n fill: 'rgb(0,0,0)',\n\n /**\n * Fill rule used to fill an object\n * accepted values are nonzero, evenodd\n * Backwards incompatibility note: This property was used for setting globalCompositeOperation until v1.4.12 (use `fabric.Object#globalCompositeOperation` instead)\n * @type String\n * @default\n */\n fillRule: 'nonzero',\n\n /**\n * Composite rule used for canvas globalCompositeOperation\n * @type String\n * @default\n */\n globalCompositeOperation: 'source-over',\n\n /**\n * Background color of an object.\n * takes css colors https://www.w3.org/TR/css-color-3/\n * @type String\n * @default\n */\n backgroundColor: '',\n\n /**\n * Selection Background color of an object. colored layer behind the object when it is active.\n * does not mix good with globalCompositeOperation methods.\n * @type String\n * @default\n */\n selectionBackgroundColor: '',\n\n /**\n * When defined, an object is rendered via stroke and this property specifies its color\n * takes css colors https://www.w3.org/TR/css-color-3/\n * @type String\n * @default\n */\n stroke: null,\n\n /**\n * Width of a stroke used to render this object\n * @type Number\n * @default\n */\n strokeWidth: 1,\n\n /**\n * Array specifying dash pattern of an object's stroke (stroke must be defined)\n * @type Array\n */\n strokeDashArray: null,\n\n /**\n * Line offset of an object's stroke\n * @type Number\n * @default\n */\n strokeDashOffset: 0,\n\n /**\n * Line endings style of an object's stroke (one of \"butt\", \"round\", \"square\")\n * @type String\n * @default\n */\n strokeLineCap: 'butt',\n\n /**\n * Corner style of an object's stroke (one of \"bevel\", \"round\", \"miter\")\n * @type String\n * @default\n */\n strokeLineJoin: 'miter',\n\n /**\n * Maximum miter length (used for strokeLineJoin = \"miter\") of an object's stroke\n * @type Number\n * @default\n */\n strokeMiterLimit: 4,\n\n /**\n * Shadow object representing shadow of this shape\n * @type fabric.Shadow\n * @default\n */\n shadow: null,\n\n /**\n * Opacity of object's controlling borders when object is active and moving\n * @type Number\n * @default\n */\n borderOpacityWhenMoving: 0.4,\n\n /**\n * Scale factor of object's controlling borders\n * bigger number will make a thicker border\n * border is 1, so this is basically a border thickness\n * since there is no way to change the border itself.\n * @type Number\n * @default\n */\n borderScaleFactor: 1,\n\n /**\n * Minimum allowed scale value of an object\n * @type Number\n * @default\n */\n minScaleLimit: 0,\n\n /**\n * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection).\n * But events still fire on it.\n * @type Boolean\n * @default\n */\n selectable: true,\n\n /**\n * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4\n * @type Boolean\n * @default\n */\n evented: true,\n\n /**\n * When set to `false`, an object is not rendered on canvas\n * @type Boolean\n * @default\n */\n visible: true,\n\n /**\n * When set to `false`, object's controls are not displayed and can not be used to manipulate object\n * @type Boolean\n * @default\n */\n hasControls: true,\n\n /**\n * When set to `false`, object's controlling borders are not rendered\n * @type Boolean\n * @default\n */\n hasBorders: true,\n\n /**\n * When set to `true`, objects are \"found\" on canvas on per-pixel basis rather than according to bounding box\n * @type Boolean\n * @default\n */\n perPixelTargetFind: false,\n\n /**\n * When `false`, default object's values are not included in its serialization\n * @type Boolean\n * @default\n */\n includeDefaultValues: true,\n\n /**\n * When `true`, object horizontal movement is locked\n * @type Boolean\n * @default\n */\n lockMovementX: false,\n\n /**\n * When `true`, object vertical movement is locked\n * @type Boolean\n * @default\n */\n lockMovementY: false,\n\n /**\n * When `true`, object rotation is locked\n * @type Boolean\n * @default\n */\n lockRotation: false,\n\n /**\n * When `true`, object horizontal scaling is locked\n * @type Boolean\n * @default\n */\n lockScalingX: false,\n\n /**\n * When `true`, object vertical scaling is locked\n * @type Boolean\n * @default\n */\n lockScalingY: false,\n\n /**\n * When `true`, object horizontal skewing is locked\n * @type Boolean\n * @default\n */\n lockSkewingX: false,\n\n /**\n * When `true`, object vertical skewing is locked\n * @type Boolean\n * @default\n */\n lockSkewingY: false,\n\n /**\n * When `true`, object cannot be flipped by scaling into negative values\n * @type Boolean\n * @default\n */\n lockScalingFlip: false,\n\n /**\n * When `true`, object is not exported in OBJECT/JSON\n * @since 1.6.3\n * @type Boolean\n * @default\n */\n excludeFromExport: false,\n\n /**\n * When `true`, object is cached on an additional canvas.\n * When `false`, object is not cached unless necessary ( clipPath )\n * default to true\n * @since 1.7.0\n * @type Boolean\n * @default true\n */\n objectCaching: objectCaching,\n\n /**\n * When `true`, object properties are checked for cache invalidation. In some particular\n * situation you may want this to be disabled ( spray brush, very big, groups)\n * or if your application does not allow you to modify properties for groups child you want\n * to disable it for groups.\n * default to false\n * since 1.7.0\n * @type Boolean\n * @default false\n */\n statefullCache: false,\n\n /**\n * When `true`, cache does not get updated during scaling. The picture will get blocky if scaled\n * too much and will be redrawn with correct details at the end of scaling.\n * this setting is performance and application dependant.\n * default to true\n * since 1.7.0\n * @type Boolean\n * @default true\n */\n noScaleCache: true,\n\n /**\n * When `false`, the stoke width will scale with the object.\n * When `true`, the stroke will always match the exact pixel size entered for stroke width.\n * this Property does not work on Text classes or drawing call that uses strokeText,fillText methods\n * default to false\n * @since 2.6.0\n * @type Boolean\n * @default false\n * @type Boolean\n * @default false\n */\n strokeUniform: false,\n\n /**\n * When set to `true`, object's cache will be rerendered next render call.\n * since 1.7.0\n * @type Boolean\n * @default true\n */\n dirty: true,\n\n /**\n * keeps the value of the last hovered corner during mouse move.\n * 0 is no corner, or 'mt', 'ml', 'mtr' etc..\n * It should be private, but there is no harm in using it as\n * a read-only property.\n * @type number|string|any\n * @default 0\n */\n __corner: 0,\n\n /**\n * Determines if the fill or the stroke is drawn first (one of \"fill\" or \"stroke\")\n * @type String\n * @default\n */\n paintFirst: 'fill',\n\n /**\n * When 'down', object is set to active on mousedown/touchstart\n * When 'up', object is set to active on mouseup/touchend\n * Experimental. Let's see if this breaks anything before supporting officially\n * @private\n * since 4.4.0\n * @type String\n * @default 'down'\n */\n activeOn: 'down',\n\n /**\n * List of properties to consider when checking if state\n * of an object is changed (fabric.Object#hasStateChanged)\n * as well as for history (undo/redo) purposes\n * @type Array\n */\n stateProperties: (\n 'top left width height scaleX scaleY flipX flipY originX originY transformMatrix ' +\n 'stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit ' +\n 'angle opacity fill globalCompositeOperation shadow visible backgroundColor ' +\n 'skewX skewY fillRule paintFirst clipPath strokeUniform'\n ).split(' '),\n\n /**\n * List of properties to consider when checking if cache needs refresh\n * Those properties are checked by statefullCache ON ( or lazy mode if we want ) or from single\n * calls to Object.set(key, value). If the key is in this list, the object is marked as dirty\n * and refreshed at the next render\n * @type Array\n */\n cacheProperties: (\n 'fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform' +\n ' strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath'\n ).split(' '),\n\n /**\n * List of properties to consider for animating colors.\n * @type Array\n */\n colorProperties: (\n 'fill stroke backgroundColor'\n ).split(' '),\n\n /**\n * a fabricObject that, without stroke define a clipping area with their shape. filled in black\n * the clipPath object gets used when the object has rendered, and the context is placed in the center\n * of the object cacheCanvas.\n * If you want 0,0 of a clipPath to align with an object center, use clipPath.originX/Y to 'center'\n * @type fabric.Object\n */\n clipPath: undefined,\n\n /**\n * Meaningful ONLY when the object is used as clipPath.\n * if true, the clipPath will make the object clip to the outside of the clipPath\n * since 2.4.0\n * @type boolean\n * @default false\n */\n inverted: false,\n\n /**\n * Meaningful ONLY when the object is used as clipPath.\n * if true, the clipPath will have its top and left relative to canvas, and will\n * not be influenced by the object transform. This will make the clipPath relative\n * to the canvas, but clipping just a particular object.\n * WARNING this is beta, this feature may change or be renamed.\n * since 2.4.0\n * @type boolean\n * @default false\n */\n absolutePositioned: false,\n\n /**\n * Constructor\n * @param {Object} [options] Options object\n */\n initialize: function(options) {\n if (options) {\n this.setOptions(options);\n }\n },\n\n /**\n * Create a the canvas used to keep the cached copy of the object\n * @private\n */\n _createCacheCanvas: function() {\n this._cacheProperties = {};\n this._cacheCanvas = fabric.util.createCanvasElement();\n this._cacheContext = this._cacheCanvas.getContext('2d');\n this._updateCacheCanvas();\n // if canvas gets created, is empty, so dirty.\n this.dirty = true;\n },\n\n /**\n * Limit the cache dimensions so that X * Y do not cross fabric.perfLimitSizeTotal\n * and each side do not cross fabric.cacheSideLimit\n * those numbers are configurable so that you can get as much detail as you want\n * making bargain with performances.\n * @param {Object} dims\n * @param {Object} dims.width width of canvas\n * @param {Object} dims.height height of canvas\n * @param {Object} dims.zoomX zoomX zoom value to unscale the canvas before drawing cache\n * @param {Object} dims.zoomY zoomY zoom value to unscale the canvas before drawing cache\n * @return {Object}.width width of canvas\n * @return {Object}.height height of canvas\n * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache\n * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache\n */\n _limitCacheSize: function(dims) {\n var perfLimitSizeTotal = fabric.perfLimitSizeTotal,\n width = dims.width, height = dims.height,\n max = fabric.maxCacheSideLimit, min = fabric.minCacheSideLimit;\n if (width <= max && height <= max && width * height <= perfLimitSizeTotal) {\n if (width < min) {\n dims.width = min;\n }\n if (height < min) {\n dims.height = min;\n }\n return dims;\n }\n var ar = width / height, limitedDims = fabric.util.limitDimsByArea(ar, perfLimitSizeTotal),\n capValue = fabric.util.capValue,\n x = capValue(min, limitedDims.x, max),\n y = capValue(min, limitedDims.y, max);\n if (width > x) {\n dims.zoomX /= width / x;\n dims.width = x;\n dims.capped = true;\n }\n if (height > y) {\n dims.zoomY /= height / y;\n dims.height = y;\n dims.capped = true;\n }\n return dims;\n },\n\n /**\n * Return the dimension and the zoom level needed to create a cache canvas\n * big enough to host the object to be cached.\n * @private\n * @return {Object}.x width of object to be cached\n * @return {Object}.y height of object to be cached\n * @return {Object}.width width of canvas\n * @return {Object}.height height of canvas\n * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache\n * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache\n */\n _getCacheCanvasDimensions: function() {\n var objectScale = this.getTotalObjectScaling(),\n // caculate dimensions without skewing\n dim = this._getTransformedDimensions(0, 0),\n neededX = dim.x * objectScale.scaleX / this.scaleX,\n neededY = dim.y * objectScale.scaleY / this.scaleY;\n return {\n // for sure this ALIASING_LIMIT is slightly creating problem\n // in situation in which the cache canvas gets an upper limit\n // also objectScale contains already scaleX and scaleY\n width: neededX + ALIASING_LIMIT,\n height: neededY + ALIASING_LIMIT,\n zoomX: objectScale.scaleX,\n zoomY: objectScale.scaleY,\n x: neededX,\n y: neededY\n };\n },\n\n /**\n * Update width and height of the canvas for cache\n * returns true or false if canvas needed resize.\n * @private\n * @return {Boolean} true if the canvas has been resized\n */\n _updateCacheCanvas: function() {\n var targetCanvas = this.canvas;\n if (this.noScaleCache && targetCanvas && targetCanvas._currentTransform) {\n var target = targetCanvas._currentTransform.target,\n action = targetCanvas._currentTransform.action;\n if (this === target && action.slice && action.slice(0, 5) === 'scale') {\n return false;\n }\n }\n var canvas = this._cacheCanvas,\n dims = this._limitCacheSize(this._getCacheCanvasDimensions()),\n minCacheSize = fabric.minCacheSideLimit,\n width = dims.width, height = dims.height, drawingWidth, drawingHeight,\n zoomX = dims.zoomX, zoomY = dims.zoomY,\n dimensionsChanged = width !== this.cacheWidth || height !== this.cacheHeight,\n zoomChanged = this.zoomX !== zoomX || this.zoomY !== zoomY,\n shouldRedraw = dimensionsChanged || zoomChanged,\n additionalWidth = 0, additionalHeight = 0, shouldResizeCanvas = false;\n if (dimensionsChanged) {\n var canvasWidth = this._cacheCanvas.width,\n canvasHeight = this._cacheCanvas.height,\n sizeGrowing = width > canvasWidth || height > canvasHeight,\n sizeShrinking = (width < canvasWidth * 0.9 || height < canvasHeight * 0.9) &&\n canvasWidth > minCacheSize && canvasHeight > minCacheSize;\n shouldResizeCanvas = sizeGrowing || sizeShrinking;\n if (sizeGrowing && !dims.capped && (width > minCacheSize || height > minCacheSize)) {\n additionalWidth = width * 0.1;\n additionalHeight = height * 0.1;\n }\n }\n if (this instanceof fabric.Text && this.path) {\n shouldRedraw = true;\n shouldResizeCanvas = true;\n additionalWidth += this.getHeightOfLine(0) * this.zoomX;\n additionalHeight += this.getHeightOfLine(0) * this.zoomY;\n }\n if (shouldRedraw) {\n if (shouldResizeCanvas) {\n canvas.width = Math.ceil(width + additionalWidth);\n canvas.height = Math.ceil(height + additionalHeight);\n }\n else {\n this._cacheContext.setTransform(1, 0, 0, 1, 0, 0);\n this._cacheContext.clearRect(0, 0, canvas.width, canvas.height);\n }\n drawingWidth = dims.x / 2;\n drawingHeight = dims.y / 2;\n this.cacheTranslationX = Math.round(canvas.width / 2 - drawingWidth) + drawingWidth;\n this.cacheTranslationY = Math.round(canvas.height / 2 - drawingHeight) + drawingHeight;\n this.cacheWidth = width;\n this.cacheHeight = height;\n this._cacheContext.translate(this.cacheTranslationX, this.cacheTranslationY);\n this._cacheContext.scale(zoomX, zoomY);\n this.zoomX = zoomX;\n this.zoomY = zoomY;\n return true;\n }\n return false;\n },\n\n /**\n * Sets object's properties from options\n * @param {Object} [options] Options object\n */\n setOptions: function(options) {\n this._setOptions(options);\n this._initGradient(options.fill, 'fill');\n this._initGradient(options.stroke, 'stroke');\n this._initPattern(options.fill, 'fill');\n this._initPattern(options.stroke, 'stroke');\n },\n\n /**\n * Transforms context when rendering an object\n * @param {CanvasRenderingContext2D} ctx Context\n */\n transform: function(ctx) {\n var needFullTransform = (this.group && !this.group._transformDone) ||\n (this.group && this.canvas && ctx === this.canvas.contextTop);\n var m = this.calcTransformMatrix(!needFullTransform);\n ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);\n },\n\n /**\n * Returns an object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} Object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,\n\n object = {\n type: this.type,\n version: fabric.version,\n originX: this.originX,\n originY: this.originY,\n left: toFixed(this.left, NUM_FRACTION_DIGITS),\n top: toFixed(this.top, NUM_FRACTION_DIGITS),\n width: toFixed(this.width, NUM_FRACTION_DIGITS),\n height: toFixed(this.height, NUM_FRACTION_DIGITS),\n fill: (this.fill && this.fill.toObject) ? this.fill.toObject() : this.fill,\n stroke: (this.stroke && this.stroke.toObject) ? this.stroke.toObject() : this.stroke,\n strokeWidth: toFixed(this.strokeWidth, NUM_FRACTION_DIGITS),\n strokeDashArray: this.strokeDashArray ? this.strokeDashArray.concat() : this.strokeDashArray,\n strokeLineCap: this.strokeLineCap,\n strokeDashOffset: this.strokeDashOffset,\n strokeLineJoin: this.strokeLineJoin,\n strokeUniform: this.strokeUniform,\n strokeMiterLimit: toFixed(this.strokeMiterLimit, NUM_FRACTION_DIGITS),\n scaleX: toFixed(this.scaleX, NUM_FRACTION_DIGITS),\n scaleY: toFixed(this.scaleY, NUM_FRACTION_DIGITS),\n angle: toFixed(this.angle, NUM_FRACTION_DIGITS),\n flipX: this.flipX,\n flipY: this.flipY,\n opacity: toFixed(this.opacity, NUM_FRACTION_DIGITS),\n shadow: (this.shadow && this.shadow.toObject) ? this.shadow.toObject() : this.shadow,\n visible: this.visible,\n backgroundColor: this.backgroundColor,\n fillRule: this.fillRule,\n paintFirst: this.paintFirst,\n globalCompositeOperation: this.globalCompositeOperation,\n skewX: toFixed(this.skewX, NUM_FRACTION_DIGITS),\n skewY: toFixed(this.skewY, NUM_FRACTION_DIGITS),\n };\n\n if (this.clipPath && !this.clipPath.excludeFromExport) {\n object.clipPath = this.clipPath.toObject(propertiesToInclude);\n object.clipPath.inverted = this.clipPath.inverted;\n object.clipPath.absolutePositioned = this.clipPath.absolutePositioned;\n }\n\n fabric.util.populateWithProperties(this, object, propertiesToInclude);\n if (!this.includeDefaultValues) {\n object = this._removeDefaultValues(object);\n }\n\n return object;\n },\n\n /**\n * Returns (dataless) object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} Object representation of an instance\n */\n toDatalessObject: function(propertiesToInclude) {\n // will be overwritten by subclasses\n return this.toObject(propertiesToInclude);\n },\n\n /**\n * @private\n * @param {Object} object\n */\n _removeDefaultValues: function(object) {\n var prototype = fabric.util.getKlass(object.type).prototype,\n stateProperties = prototype.stateProperties;\n stateProperties.forEach(function(prop) {\n if (prop === 'left' || prop === 'top') {\n return;\n }\n if (object[prop] === prototype[prop]) {\n delete object[prop];\n }\n // basically a check for [] === []\n if (Array.isArray(object[prop]) && Array.isArray(prototype[prop])\n && object[prop].length === 0 && prototype[prop].length === 0) {\n delete object[prop];\n }\n });\n\n return object;\n },\n\n /**\n * Returns a string representation of an instance\n * @return {String}\n */\n toString: function() {\n return '#';\n },\n\n /**\n * Return the object scale factor counting also the group scaling\n * @return {Object} object with scaleX and scaleY properties\n */\n getObjectScaling: function() {\n // if the object is a top level one, on the canvas, we go for simple aritmetic\n // otherwise the complex method with angles will return approximations and decimals\n // and will likely kill the cache when not needed\n // https://github.com/fabricjs/fabric.js/issues/7157\n if (!this.group) {\n return {\n scaleX: this.scaleX,\n scaleY: this.scaleY,\n };\n }\n // if we are inside a group total zoom calculation is complex, we defer to generic matrices\n var options = fabric.util.qrDecompose(this.calcTransformMatrix());\n return { scaleX: Math.abs(options.scaleX), scaleY: Math.abs(options.scaleY) };\n },\n\n /**\n * Return the object scale factor counting also the group scaling, zoom and retina\n * @return {Object} object with scaleX and scaleY properties\n */\n getTotalObjectScaling: function() {\n var scale = this.getObjectScaling(), scaleX = scale.scaleX, scaleY = scale.scaleY;\n if (this.canvas) {\n var zoom = this.canvas.getZoom();\n var retina = this.canvas.getRetinaScaling();\n scaleX *= zoom * retina;\n scaleY *= zoom * retina;\n }\n return { scaleX: scaleX, scaleY: scaleY };\n },\n\n /**\n * Return the object opacity counting also the group property\n * @return {Number}\n */\n getObjectOpacity: function() {\n var opacity = this.opacity;\n if (this.group) {\n opacity *= this.group.getObjectOpacity();\n }\n return opacity;\n },\n\n /**\n * @private\n * @param {String} key\n * @param {*} value\n * @return {fabric.Object} thisArg\n */\n _set: function(key, value) {\n var shouldConstrainValue = (key === 'scaleX' || key === 'scaleY'),\n isChanged = this[key] !== value, groupNeedsUpdate = false;\n\n if (shouldConstrainValue) {\n value = this._constrainScale(value);\n }\n if (key === 'scaleX' && value < 0) {\n this.flipX = !this.flipX;\n value *= -1;\n }\n else if (key === 'scaleY' && value < 0) {\n this.flipY = !this.flipY;\n value *= -1;\n }\n else if (key === 'shadow' && value && !(value instanceof fabric.Shadow)) {\n value = new fabric.Shadow(value);\n }\n else if (key === 'dirty' && this.group) {\n this.group.set('dirty', value);\n }\n\n this[key] = value;\n\n if (isChanged) {\n groupNeedsUpdate = this.group && this.group.isOnACache();\n if (this.cacheProperties.indexOf(key) > -1) {\n this.dirty = true;\n groupNeedsUpdate && this.group.set('dirty', true);\n }\n else if (groupNeedsUpdate && this.stateProperties.indexOf(key) > -1) {\n this.group.set('dirty', true);\n }\n }\n return this;\n },\n\n /**\n * This callback function is called by the parent group of an object every\n * time a non-delegated property changes on the group. It is passed the key\n * and value as parameters. Not adding in this function's signature to avoid\n * Travis build error about unused variables.\n */\n setOnGroup: function() {\n // implemented by sub-classes, as needed.\n },\n\n /**\n * Retrieves viewportTransform from Object's canvas if possible\n * @method getViewportTransform\n * @memberOf fabric.Object.prototype\n * @return {Array}\n */\n getViewportTransform: function() {\n if (this.canvas && this.canvas.viewportTransform) {\n return this.canvas.viewportTransform;\n }\n return fabric.iMatrix.concat();\n },\n\n /*\n * @private\n * return if the object would be visible in rendering\n * @memberOf fabric.Object.prototype\n * @return {Boolean}\n */\n isNotVisible: function() {\n return this.opacity === 0 ||\n (!this.width && !this.height && this.strokeWidth === 0) ||\n !this.visible;\n },\n\n /**\n * Renders an object on a specified context\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n render: function(ctx) {\n // do not render if width/height are zeros or object is not visible\n if (this.isNotVisible()) {\n return;\n }\n if (this.canvas && this.canvas.skipOffscreen && !this.group && !this.isOnScreen()) {\n return;\n }\n ctx.save();\n this._setupCompositeOperation(ctx);\n this.drawSelectionBackground(ctx);\n this.transform(ctx);\n this._setOpacity(ctx);\n this._setShadow(ctx, this);\n if (this.shouldCache()) {\n this.renderCache();\n this.drawCacheOnCanvas(ctx);\n }\n else {\n this._removeCacheCanvas();\n this.dirty = false;\n this.drawObject(ctx);\n if (this.objectCaching && this.statefullCache) {\n this.saveState({ propertySet: 'cacheProperties' });\n }\n }\n ctx.restore();\n },\n\n renderCache: function(options) {\n options = options || {};\n if (!this._cacheCanvas || !this._cacheContext) {\n this._createCacheCanvas();\n }\n if (this.isCacheDirty()) {\n this.statefullCache && this.saveState({ propertySet: 'cacheProperties' });\n this.drawObject(this._cacheContext, options.forClipping);\n this.dirty = false;\n }\n },\n\n /**\n * Remove cacheCanvas and its dimensions from the objects\n */\n _removeCacheCanvas: function() {\n this._cacheCanvas = null;\n this._cacheContext = null;\n this.cacheWidth = 0;\n this.cacheHeight = 0;\n },\n\n /**\n * return true if the object will draw a stroke\n * Does not consider text styles. This is just a shortcut used at rendering time\n * We want it to be an approximation and be fast.\n * wrote to avoid extra caching, it has to return true when stroke happens,\n * can guess when it will not happen at 100% chance, does not matter if it misses\n * some use case where the stroke is invisible.\n * @since 3.0.0\n * @returns Boolean\n */\n hasStroke: function() {\n return this.stroke && this.stroke !== 'transparent' && this.strokeWidth !== 0;\n },\n\n /**\n * return true if the object will draw a fill\n * Does not consider text styles. This is just a shortcut used at rendering time\n * We want it to be an approximation and be fast.\n * wrote to avoid extra caching, it has to return true when fill happens,\n * can guess when it will not happen at 100% chance, does not matter if it misses\n * some use case where the fill is invisible.\n * @since 3.0.0\n * @returns Boolean\n */\n hasFill: function() {\n return this.fill && this.fill !== 'transparent';\n },\n\n /**\n * When set to `true`, force the object to have its own cache, even if it is inside a group\n * it may be needed when your object behave in a particular way on the cache and always needs\n * its own isolated canvas to render correctly.\n * Created to be overridden\n * since 1.7.12\n * @returns Boolean\n */\n needsItsOwnCache: function() {\n if (this.paintFirst === 'stroke' &&\n this.hasFill() && this.hasStroke() && typeof this.shadow === 'object') {\n return true;\n }\n if (this.clipPath) {\n return true;\n }\n return false;\n },\n\n /**\n * Decide if the object should cache or not. Create its own cache level\n * objectCaching is a global flag, wins over everything\n * needsItsOwnCache should be used when the object drawing method requires\n * a cache step. None of the fabric classes requires it.\n * Generally you do not cache objects in groups because the group outside is cached.\n * Read as: cache if is needed, or if the feature is enabled but we are not already caching.\n * @return {Boolean}\n */\n shouldCache: function() {\n this.ownCaching = this.needsItsOwnCache() || (\n this.objectCaching &&\n (!this.group || !this.group.isOnACache())\n );\n return this.ownCaching;\n },\n\n /**\n * Check if this object or a child object will cast a shadow\n * used by Group.shouldCache to know if child has a shadow recursively\n * @return {Boolean}\n */\n willDrawShadow: function() {\n return !!this.shadow && (this.shadow.offsetX !== 0 || this.shadow.offsetY !== 0);\n },\n\n /**\n * Execute the drawing operation for an object clipPath\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {fabric.Object} clipPath\n */\n drawClipPathOnCache: function(ctx, clipPath) {\n ctx.save();\n // DEBUG: uncomment this line, comment the following\n // ctx.globalAlpha = 0.4\n if (clipPath.inverted) {\n ctx.globalCompositeOperation = 'destination-out';\n }\n else {\n ctx.globalCompositeOperation = 'destination-in';\n }\n //ctx.scale(1 / 2, 1 / 2);\n if (clipPath.absolutePositioned) {\n var m = fabric.util.invertTransform(this.calcTransformMatrix());\n ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);\n }\n clipPath.transform(ctx);\n ctx.scale(1 / clipPath.zoomX, 1 / clipPath.zoomY);\n ctx.drawImage(clipPath._cacheCanvas, -clipPath.cacheTranslationX, -clipPath.cacheTranslationY);\n ctx.restore();\n },\n\n /**\n * Execute the drawing operation for an object on a specified context\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n drawObject: function(ctx, forClipping) {\n var originalFill = this.fill, originalStroke = this.stroke;\n if (forClipping) {\n this.fill = 'black';\n this.stroke = '';\n this._setClippingProperties(ctx);\n }\n else {\n this._renderBackground(ctx);\n }\n this._render(ctx);\n this._drawClipPath(ctx, this.clipPath);\n this.fill = originalFill;\n this.stroke = originalStroke;\n },\n\n /**\n * Prepare clipPath state and cache and draw it on instance's cache\n * @param {CanvasRenderingContext2D} ctx\n * @param {fabric.Object} clipPath\n */\n _drawClipPath: function (ctx, clipPath) {\n if (!clipPath) { return; }\n // needed to setup a couple of variables\n // path canvas gets overridden with this one.\n // TODO find a better solution?\n clipPath.canvas = this.canvas;\n clipPath.shouldCache();\n clipPath._transformDone = true;\n clipPath.renderCache({ forClipping: true });\n this.drawClipPathOnCache(ctx, clipPath);\n },\n\n /**\n * Paint the cached copy of the object on the target context.\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n drawCacheOnCanvas: function(ctx) {\n ctx.scale(1 / this.zoomX, 1 / this.zoomY);\n ctx.drawImage(this._cacheCanvas, -this.cacheTranslationX, -this.cacheTranslationY);\n },\n\n /**\n * Check if cache is dirty\n * @param {Boolean} skipCanvas skip canvas checks because this object is painted\n * on parent canvas.\n */\n isCacheDirty: function(skipCanvas) {\n if (this.isNotVisible()) {\n return false;\n }\n if (this._cacheCanvas && this._cacheContext && !skipCanvas && this._updateCacheCanvas()) {\n // in this case the context is already cleared.\n return true;\n }\n else {\n if (this.dirty ||\n (this.clipPath && this.clipPath.absolutePositioned) ||\n (this.statefullCache && this.hasStateChanged('cacheProperties'))\n ) {\n if (this._cacheCanvas && this._cacheContext && !skipCanvas) {\n var width = this.cacheWidth / this.zoomX;\n var height = this.cacheHeight / this.zoomY;\n this._cacheContext.clearRect(-width / 2, -height / 2, width, height);\n }\n return true;\n }\n }\n return false;\n },\n\n /**\n * Draws a background for the object big as its untransformed dimensions\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderBackground: function(ctx) {\n if (!this.backgroundColor) {\n return;\n }\n var dim = this._getNonTransformedDimensions();\n ctx.fillStyle = this.backgroundColor;\n\n ctx.fillRect(\n -dim.x / 2,\n -dim.y / 2,\n dim.x,\n dim.y\n );\n // if there is background color no other shadows\n // should be casted\n this._removeShadow(ctx);\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _setOpacity: function(ctx) {\n if (this.group && !this.group._transformDone) {\n ctx.globalAlpha = this.getObjectOpacity();\n }\n else {\n ctx.globalAlpha *= this.opacity;\n }\n },\n\n _setStrokeStyles: function(ctx, decl) {\n var stroke = decl.stroke;\n if (stroke) {\n ctx.lineWidth = decl.strokeWidth;\n ctx.lineCap = decl.strokeLineCap;\n ctx.lineDashOffset = decl.strokeDashOffset;\n ctx.lineJoin = decl.strokeLineJoin;\n ctx.miterLimit = decl.strokeMiterLimit;\n if (stroke.toLive) {\n if (stroke.gradientUnits === 'percentage' || stroke.gradientTransform || stroke.patternTransform) {\n // need to transform gradient in a pattern.\n // this is a slow process. If you are hitting this codepath, and the object\n // is not using caching, you should consider switching it on.\n // we need a canvas as big as the current object caching canvas.\n this._applyPatternForTransformedGradient(ctx, stroke);\n }\n else {\n // is a simple gradient or pattern\n ctx.strokeStyle = stroke.toLive(ctx, this);\n this._applyPatternGradientTransform(ctx, stroke);\n }\n }\n else {\n // is a color\n ctx.strokeStyle = decl.stroke;\n }\n }\n },\n\n _setFillStyles: function(ctx, decl) {\n var fill = decl.fill;\n if (fill) {\n if (fill.toLive) {\n ctx.fillStyle = fill.toLive(ctx, this);\n this._applyPatternGradientTransform(ctx, decl.fill);\n }\n else {\n ctx.fillStyle = fill;\n }\n }\n },\n\n _setClippingProperties: function(ctx) {\n ctx.globalAlpha = 1;\n ctx.strokeStyle = 'transparent';\n ctx.fillStyle = '#000000';\n },\n\n /**\n * @private\n * Sets line dash\n * @param {CanvasRenderingContext2D} ctx Context to set the dash line on\n * @param {Array} dashArray array representing dashes\n */\n _setLineDash: function(ctx, dashArray) {\n if (!dashArray || dashArray.length === 0) {\n return;\n }\n // Spec requires the concatenation of two copies the dash list when the number of elements is odd\n if (1 & dashArray.length) {\n dashArray.push.apply(dashArray, dashArray);\n }\n ctx.setLineDash(dashArray);\n },\n\n /**\n * Renders controls and borders for the object\n * the context here is not transformed\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {Object} [styleOverride] properties to override the object style\n */\n _renderControls: function(ctx, styleOverride) {\n var vpt = this.getViewportTransform(),\n matrix = this.calcTransformMatrix(),\n options, drawBorders, drawControls;\n styleOverride = styleOverride || { };\n drawBorders = typeof styleOverride.hasBorders !== 'undefined' ? styleOverride.hasBorders : this.hasBorders;\n drawControls = typeof styleOverride.hasControls !== 'undefined' ? styleOverride.hasControls : this.hasControls;\n matrix = fabric.util.multiplyTransformMatrices(vpt, matrix);\n options = fabric.util.qrDecompose(matrix);\n ctx.save();\n ctx.translate(options.translateX, options.translateY);\n ctx.lineWidth = 1 * this.borderScaleFactor;\n if (!this.group) {\n ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;\n }\n if (this.flipX) {\n options.angle -= 180;\n }\n ctx.rotate(degreesToRadians(this.group ? options.angle : this.angle));\n if (styleOverride.forActiveSelection || this.group) {\n drawBorders && this.drawBordersInGroup(ctx, options, styleOverride);\n }\n else {\n drawBorders && this.drawBorders(ctx, styleOverride);\n }\n drawControls && this.drawControls(ctx, styleOverride);\n ctx.restore();\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _setShadow: function(ctx) {\n if (!this.shadow) {\n return;\n }\n\n var shadow = this.shadow, canvas = this.canvas, scaling,\n multX = (canvas && canvas.viewportTransform[0]) || 1,\n multY = (canvas && canvas.viewportTransform[3]) || 1;\n if (shadow.nonScaling) {\n scaling = { scaleX: 1, scaleY: 1 };\n }\n else {\n scaling = this.getObjectScaling();\n }\n if (canvas && canvas._isRetinaScaling()) {\n multX *= fabric.devicePixelRatio;\n multY *= fabric.devicePixelRatio;\n }\n ctx.shadowColor = shadow.color;\n ctx.shadowBlur = shadow.blur * fabric.browserShadowBlurConstant *\n (multX + multY) * (scaling.scaleX + scaling.scaleY) / 4;\n ctx.shadowOffsetX = shadow.offsetX * multX * scaling.scaleX;\n ctx.shadowOffsetY = shadow.offsetY * multY * scaling.scaleY;\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _removeShadow: function(ctx) {\n if (!this.shadow) {\n return;\n }\n\n ctx.shadowColor = '';\n ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {Object} filler fabric.Pattern or fabric.Gradient\n * @return {Object} offset.offsetX offset for text rendering\n * @return {Object} offset.offsetY offset for text rendering\n */\n _applyPatternGradientTransform: function(ctx, filler) {\n if (!filler || !filler.toLive) {\n return { offsetX: 0, offsetY: 0 };\n }\n var t = filler.gradientTransform || filler.patternTransform;\n var offsetX = -this.width / 2 + filler.offsetX || 0,\n offsetY = -this.height / 2 + filler.offsetY || 0;\n\n if (filler.gradientUnits === 'percentage') {\n ctx.transform(this.width, 0, 0, this.height, offsetX, offsetY);\n }\n else {\n ctx.transform(1, 0, 0, 1, offsetX, offsetY);\n }\n if (t) {\n ctx.transform(t[0], t[1], t[2], t[3], t[4], t[5]);\n }\n return { offsetX: offsetX, offsetY: offsetY };\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderPaintInOrder: function(ctx) {\n if (this.paintFirst === 'stroke') {\n this._renderStroke(ctx);\n this._renderFill(ctx);\n }\n else {\n this._renderFill(ctx);\n this._renderStroke(ctx);\n }\n },\n\n /**\n * @private\n * function that actually render something on the context.\n * empty here to allow Obects to work on tests to benchmark fabric functionalites\n * not related to rendering\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(/* ctx */) {\n\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderFill: function(ctx) {\n if (!this.fill) {\n return;\n }\n\n ctx.save();\n this._setFillStyles(ctx, this);\n if (this.fillRule === 'evenodd') {\n ctx.fill('evenodd');\n }\n else {\n ctx.fill();\n }\n ctx.restore();\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderStroke: function(ctx) {\n if (!this.stroke || this.strokeWidth === 0) {\n return;\n }\n\n if (this.shadow && !this.shadow.affectStroke) {\n this._removeShadow(ctx);\n }\n\n ctx.save();\n if (this.strokeUniform && this.group) {\n var scaling = this.getObjectScaling();\n ctx.scale(1 / scaling.scaleX, 1 / scaling.scaleY);\n }\n else if (this.strokeUniform) {\n ctx.scale(1 / this.scaleX, 1 / this.scaleY);\n }\n this._setLineDash(ctx, this.strokeDashArray);\n this._setStrokeStyles(ctx, this);\n ctx.stroke();\n ctx.restore();\n },\n\n /**\n * This function try to patch the missing gradientTransform on canvas gradients.\n * transforming a context to transform the gradient, is going to transform the stroke too.\n * we want to transform the gradient but not the stroke operation, so we create\n * a transformed gradient on a pattern and then we use the pattern instead of the gradient.\n * this method has drwabacks: is slow, is in low resolution, needs a patch for when the size\n * is limited.\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {fabric.Gradient} filler a fabric gradient instance\n */\n _applyPatternForTransformedGradient: function(ctx, filler) {\n var dims = this._limitCacheSize(this._getCacheCanvasDimensions()),\n pCanvas = fabric.util.createCanvasElement(), pCtx, retinaScaling = this.canvas.getRetinaScaling(),\n width = dims.x / this.scaleX / retinaScaling, height = dims.y / this.scaleY / retinaScaling;\n pCanvas.width = width;\n pCanvas.height = height;\n pCtx = pCanvas.getContext('2d');\n pCtx.beginPath(); pCtx.moveTo(0, 0); pCtx.lineTo(width, 0); pCtx.lineTo(width, height);\n pCtx.lineTo(0, height); pCtx.closePath();\n pCtx.translate(width / 2, height / 2);\n pCtx.scale(\n dims.zoomX / this.scaleX / retinaScaling,\n dims.zoomY / this.scaleY / retinaScaling\n );\n this._applyPatternGradientTransform(pCtx, filler);\n pCtx.fillStyle = filler.toLive(ctx);\n pCtx.fill();\n ctx.translate(-this.width / 2 - this.strokeWidth / 2, -this.height / 2 - this.strokeWidth / 2);\n ctx.scale(\n retinaScaling * this.scaleX / dims.zoomX,\n retinaScaling * this.scaleY / dims.zoomY\n );\n ctx.strokeStyle = pCtx.createPattern(pCanvas, 'no-repeat');\n },\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates\n * @private\n * @return {Object} center point from element coordinates\n */\n _findCenterFromElement: function() {\n return { x: this.left + this.width / 2, y: this.top + this.height / 2 };\n },\n\n /**\n * This function is an helper for svg import. it decompose the transformMatrix\n * and assign properties to object.\n * untransformed coordinates\n * @private\n * @chainable\n */\n _assignTransformMatrixProps: function() {\n if (this.transformMatrix) {\n var options = fabric.util.qrDecompose(this.transformMatrix);\n this.flipX = false;\n this.flipY = false;\n this.set('scaleX', options.scaleX);\n this.set('scaleY', options.scaleY);\n this.angle = options.angle;\n this.skewX = options.skewX;\n this.skewY = 0;\n }\n },\n\n /**\n * This function is an helper for svg import. it removes the transform matrix\n * and set to object properties that fabricjs can handle\n * @private\n * @param {Object} preserveAspectRatioOptions\n * @return {thisArg}\n */\n _removeTransformMatrix: function(preserveAspectRatioOptions) {\n var center = this._findCenterFromElement();\n if (this.transformMatrix) {\n this._assignTransformMatrixProps();\n center = fabric.util.transformPoint(center, this.transformMatrix);\n }\n this.transformMatrix = null;\n if (preserveAspectRatioOptions) {\n this.scaleX *= preserveAspectRatioOptions.scaleX;\n this.scaleY *= preserveAspectRatioOptions.scaleY;\n this.cropX = preserveAspectRatioOptions.cropX;\n this.cropY = preserveAspectRatioOptions.cropY;\n center.x += preserveAspectRatioOptions.offsetLeft;\n center.y += preserveAspectRatioOptions.offsetTop;\n this.width = preserveAspectRatioOptions.width;\n this.height = preserveAspectRatioOptions.height;\n }\n this.setPositionByOrigin(center, 'center', 'center');\n },\n\n /**\n * Clones an instance, using a callback method will work for every object.\n * @param {Function} callback Callback is invoked with a clone as a first argument\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n */\n clone: function(callback, propertiesToInclude) {\n var objectForm = this.toObject(propertiesToInclude);\n if (this.constructor.fromObject) {\n this.constructor.fromObject(objectForm, callback);\n }\n else {\n fabric.Object._fromObject('Object', objectForm, callback);\n }\n },\n\n /**\n * Creates an instance of fabric.Image out of an object\n * makes use of toCanvasElement.\n * Once this method was based on toDataUrl and loadImage, so it also had a quality\n * and format option. toCanvasElement is faster and produce no loss of quality.\n * If you need to get a real Jpeg or Png from an object, using toDataURL is the right way to do it.\n * toCanvasElement and then toBlob from the obtained canvas is also a good option.\n * This method is sync now, but still support the callback because we did not want to break.\n * When fabricJS 5.0 will be planned, this will probably be changed to not have a callback.\n * @param {Function} callback callback, invoked with an instance as a first argument\n * @param {Object} [options] for clone as image, passed to toDataURL\n * @param {Number} [options.multiplier=1] Multiplier to scale by\n * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14\n * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14\n * @param {Number} [options.width] Cropping width. Introduced in v1.2.14\n * @param {Number} [options.height] Cropping height. Introduced in v1.2.14\n * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 1.6.4\n * @param {Boolean} [options.withoutTransform] Remove current object transform ( no scale , no angle, no flip, no skew ). Introduced in 2.3.4\n * @param {Boolean} [options.withoutShadow] Remove current object shadow. Introduced in 2.4.2\n * @return {fabric.Object} thisArg\n */\n cloneAsImage: function(callback, options) {\n var canvasEl = this.toCanvasElement(options);\n if (callback) {\n callback(new fabric.Image(canvasEl));\n }\n return this;\n },\n\n /**\n * Converts an object into a HTMLCanvas element\n * @param {Object} options Options object\n * @param {Number} [options.multiplier=1] Multiplier to scale by\n * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14\n * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14\n * @param {Number} [options.width] Cropping width. Introduced in v1.2.14\n * @param {Number} [options.height] Cropping height. Introduced in v1.2.14\n * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 1.6.4\n * @param {Boolean} [options.withoutTransform] Remove current object transform ( no scale , no angle, no flip, no skew ). Introduced in 2.3.4\n * @param {Boolean} [options.withoutShadow] Remove current object shadow. Introduced in 2.4.2\n * @return {HTMLCanvasElement} Returns DOM element with the fabric.Object\n */\n toCanvasElement: function(options) {\n options || (options = { });\n\n var utils = fabric.util, origParams = utils.saveObjectTransform(this),\n originalGroup = this.group,\n originalShadow = this.shadow, abs = Math.abs,\n multiplier = (options.multiplier || 1) * (options.enableRetinaScaling ? fabric.devicePixelRatio : 1);\n delete this.group;\n if (options.withoutTransform) {\n utils.resetObjectTransform(this);\n }\n if (options.withoutShadow) {\n this.shadow = null;\n }\n\n var el = fabric.util.createCanvasElement(),\n // skip canvas zoom and calculate with setCoords now.\n boundingRect = this.getBoundingRect(true, true),\n shadow = this.shadow, scaling,\n shadowOffset = { x: 0, y: 0 }, shadowBlur,\n width, height;\n\n if (shadow) {\n shadowBlur = shadow.blur;\n if (shadow.nonScaling) {\n scaling = { scaleX: 1, scaleY: 1 };\n }\n else {\n scaling = this.getObjectScaling();\n }\n // consider non scaling shadow.\n shadowOffset.x = 2 * Math.round(abs(shadow.offsetX) + shadowBlur) * (abs(scaling.scaleX));\n shadowOffset.y = 2 * Math.round(abs(shadow.offsetY) + shadowBlur) * (abs(scaling.scaleY));\n }\n width = boundingRect.width + shadowOffset.x;\n height = boundingRect.height + shadowOffset.y;\n // if the current width/height is not an integer\n // we need to make it so.\n el.width = Math.ceil(width);\n el.height = Math.ceil(height);\n var canvas = new fabric.StaticCanvas(el, {\n enableRetinaScaling: false,\n renderOnAddRemove: false,\n skipOffscreen: false,\n });\n if (options.format === 'jpeg') {\n canvas.backgroundColor = '#fff';\n }\n this.setPositionByOrigin(new fabric.Point(canvas.width / 2, canvas.height / 2), 'center', 'center');\n\n var originalCanvas = this.canvas;\n canvas.add(this);\n var canvasEl = canvas.toCanvasElement(multiplier || 1, options);\n this.shadow = originalShadow;\n this.set('canvas', originalCanvas);\n if (originalGroup) {\n this.group = originalGroup;\n }\n this.set(origParams).setCoords();\n // canvas.dispose will call image.dispose that will nullify the elements\n // since this canvas is a simple element for the process, we remove references\n // to objects in this way in order to avoid object trashing.\n canvas._objects = [];\n canvas.dispose();\n canvas = null;\n\n return canvasEl;\n },\n\n /**\n * Converts an object into a data-url-like string\n * @param {Object} options Options object\n * @param {String} [options.format=png] The format of the output image. Either \"jpeg\" or \"png\"\n * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.\n * @param {Number} [options.multiplier=1] Multiplier to scale by\n * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14\n * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14\n * @param {Number} [options.width] Cropping width. Introduced in v1.2.14\n * @param {Number} [options.height] Cropping height. Introduced in v1.2.14\n * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 1.6.4\n * @param {Boolean} [options.withoutTransform] Remove current object transform ( no scale , no angle, no flip, no skew ). Introduced in 2.3.4\n * @param {Boolean} [options.withoutShadow] Remove current object shadow. Introduced in 2.4.2\n * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format\n */\n toDataURL: function(options) {\n options || (options = { });\n return fabric.util.toDataURL(this.toCanvasElement(options), options.format || 'png', options.quality || 1);\n },\n\n /**\n * Returns true if specified type is identical to the type of an instance\n * @param {String} type Type to check against\n * @return {Boolean}\n */\n isType: function(type) {\n return arguments.length > 1 ? Array.from(arguments).includes(this.type) : this.type === type;\n },\n\n /**\n * Returns complexity of an instance\n * @return {Number} complexity of this instance (is 1 unless subclassed)\n */\n complexity: function() {\n return 1;\n },\n\n /**\n * Returns a JSON representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} JSON\n */\n toJSON: function(propertiesToInclude) {\n // delegate, not alias\n return this.toObject(propertiesToInclude);\n },\n\n /**\n * Sets \"angle\" of an instance with centered rotation\n * @param {Number} angle Angle value (in degrees)\n * @return {fabric.Object} thisArg\n * @chainable\n */\n rotate: function(angle) {\n var shouldCenterOrigin = (this.originX !== 'center' || this.originY !== 'center') && this.centeredRotation;\n\n if (shouldCenterOrigin) {\n this._setOriginToCenter();\n }\n\n this.set('angle', angle);\n\n if (shouldCenterOrigin) {\n this._resetOrigin();\n }\n\n return this;\n },\n\n /**\n * Centers object horizontally on canvas to which it was added last.\n * You might need to call `setCoords` on an object after centering, to update controls area.\n * @return {fabric.Object} thisArg\n * @chainable\n */\n centerH: function () {\n this.canvas && this.canvas.centerObjectH(this);\n return this;\n },\n\n /**\n * Centers object horizontally on current viewport of canvas to which it was added last.\n * You might need to call `setCoords` on an object after centering, to update controls area.\n * @return {fabric.Object} thisArg\n * @chainable\n */\n viewportCenterH: function () {\n this.canvas && this.canvas.viewportCenterObjectH(this);\n return this;\n },\n\n /**\n * Centers object vertically on canvas to which it was added last.\n * You might need to call `setCoords` on an object after centering, to update controls area.\n * @return {fabric.Object} thisArg\n * @chainable\n */\n centerV: function () {\n this.canvas && this.canvas.centerObjectV(this);\n return this;\n },\n\n /**\n * Centers object vertically on current viewport of canvas to which it was added last.\n * You might need to call `setCoords` on an object after centering, to update controls area.\n * @return {fabric.Object} thisArg\n * @chainable\n */\n viewportCenterV: function () {\n this.canvas && this.canvas.viewportCenterObjectV(this);\n return this;\n },\n\n /**\n * Centers object vertically and horizontally on canvas to which is was added last\n * You might need to call `setCoords` on an object after centering, to update controls area.\n * @return {fabric.Object} thisArg\n * @chainable\n */\n center: function () {\n this.canvas && this.canvas.centerObject(this);\n return this;\n },\n\n /**\n * Centers object on current viewport of canvas to which it was added last.\n * You might need to call `setCoords` on an object after centering, to update controls area.\n * @return {fabric.Object} thisArg\n * @chainable\n */\n viewportCenter: function () {\n this.canvas && this.canvas.viewportCenterObject(this);\n return this;\n },\n\n /**\n * Returns coordinates of a pointer relative to an object\n * @param {Event} e Event to operate upon\n * @param {Object} [pointer] Pointer to operate upon (instead of event)\n * @return {Object} Coordinates of a pointer (x, y)\n */\n getLocalPointer: function(e, pointer) {\n pointer = pointer || this.canvas.getPointer(e);\n var pClicked = new fabric.Point(pointer.x, pointer.y),\n objectLeftTop = this._getLeftTopCoords();\n if (this.angle) {\n pClicked = fabric.util.rotatePoint(\n pClicked, objectLeftTop, degreesToRadians(-this.angle));\n }\n return {\n x: pClicked.x - objectLeftTop.x,\n y: pClicked.y - objectLeftTop.y\n };\n },\n\n /**\n * Sets canvas globalCompositeOperation for specific object\n * custom composition operation for the particular object can be specified using globalCompositeOperation property\n * @param {CanvasRenderingContext2D} ctx Rendering canvas context\n */\n _setupCompositeOperation: function (ctx) {\n if (this.globalCompositeOperation) {\n ctx.globalCompositeOperation = this.globalCompositeOperation;\n }\n },\n\n /**\n * cancel instance's running animations\n * override if necessary to dispose artifacts such as `clipPath`\n */\n dispose: function () {\n if (fabric.runningAnimations) {\n fabric.runningAnimations.cancelByTarget(this);\n }\n }\n });\n\n fabric.util.createAccessors && fabric.util.createAccessors(fabric.Object);\n\n extend(fabric.Object.prototype, fabric.Observable);\n\n /**\n * Defines the number of fraction digits to use when serializing object values.\n * You can use it to increase/decrease precision of such values like left, top, scaleX, scaleY, etc.\n * @static\n * @memberOf fabric.Object\n * @constant\n * @type Number\n */\n fabric.Object.NUM_FRACTION_DIGITS = 2;\n\n /**\n * Defines which properties should be enlivened from the object passed to {@link fabric.Object._fromObject}\n * @static\n * @memberOf fabric.Object\n * @constant\n * @type string[]\n */\n fabric.Object.ENLIVEN_PROPS = ['clipPath'];\n\n fabric.Object._fromObject = function(className, object, callback, extraParam) {\n var klass = fabric[className];\n object = clone(object, true);\n fabric.util.enlivenPatterns([object.fill, object.stroke], function(patterns) {\n if (typeof patterns[0] !== 'undefined') {\n object.fill = patterns[0];\n }\n if (typeof patterns[1] !== 'undefined') {\n object.stroke = patterns[1];\n }\n fabric.util.enlivenObjectEnlivables(object, object, function () {\n var instance = extraParam ? new klass(object[extraParam], object) : new klass(object);\n callback && callback(instance);\n });\n });\n };\n\n /**\n * Unique id used internally when creating SVG elements\n * @static\n * @memberOf fabric.Object\n * @type Number\n */\n fabric.Object.__uid = 0;\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function() {\n\n var degreesToRadians = fabric.util.degreesToRadians,\n originXOffset = {\n left: -0.5,\n center: 0,\n right: 0.5\n },\n originYOffset = {\n top: -0.5,\n center: 0,\n bottom: 0.5\n };\n\n fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {\n\n /**\n * Translates the coordinates from a set of origin to another (based on the object's dimensions)\n * @param {fabric.Point} point The point which corresponds to the originX and originY params\n * @param {String} fromOriginX Horizontal origin: 'left', 'center' or 'right'\n * @param {String} fromOriginY Vertical origin: 'top', 'center' or 'bottom'\n * @param {String} toOriginX Horizontal origin: 'left', 'center' or 'right'\n * @param {String} toOriginY Vertical origin: 'top', 'center' or 'bottom'\n * @return {fabric.Point}\n */\n translateToGivenOrigin: function(point, fromOriginX, fromOriginY, toOriginX, toOriginY) {\n var x = point.x,\n y = point.y,\n offsetX, offsetY, dim;\n\n if (typeof fromOriginX === 'string') {\n fromOriginX = originXOffset[fromOriginX];\n }\n else {\n fromOriginX -= 0.5;\n }\n\n if (typeof toOriginX === 'string') {\n toOriginX = originXOffset[toOriginX];\n }\n else {\n toOriginX -= 0.5;\n }\n\n offsetX = toOriginX - fromOriginX;\n\n if (typeof fromOriginY === 'string') {\n fromOriginY = originYOffset[fromOriginY];\n }\n else {\n fromOriginY -= 0.5;\n }\n\n if (typeof toOriginY === 'string') {\n toOriginY = originYOffset[toOriginY];\n }\n else {\n toOriginY -= 0.5;\n }\n\n offsetY = toOriginY - fromOriginY;\n\n if (offsetX || offsetY) {\n dim = this._getTransformedDimensions();\n x = point.x + offsetX * dim.x;\n y = point.y + offsetY * dim.y;\n }\n\n return new fabric.Point(x, y);\n },\n\n /**\n * Translates the coordinates from origin to center coordinates (based on the object's dimensions)\n * @param {fabric.Point} point The point which corresponds to the originX and originY params\n * @param {String} originX Horizontal origin: 'left', 'center' or 'right'\n * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'\n * @return {fabric.Point}\n */\n translateToCenterPoint: function(point, originX, originY) {\n var p = this.translateToGivenOrigin(point, originX, originY, 'center', 'center');\n if (this.angle) {\n return fabric.util.rotatePoint(p, point, degreesToRadians(this.angle));\n }\n return p;\n },\n\n /**\n * Translates the coordinates from center to origin coordinates (based on the object's dimensions)\n * @param {fabric.Point} center The point which corresponds to center of the object\n * @param {String} originX Horizontal origin: 'left', 'center' or 'right'\n * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'\n * @return {fabric.Point}\n */\n translateToOriginPoint: function(center, originX, originY) {\n var p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);\n if (this.angle) {\n return fabric.util.rotatePoint(p, center, degreesToRadians(this.angle));\n }\n return p;\n },\n\n /**\n * Returns the real center coordinates of the object\n * @return {fabric.Point}\n */\n getCenterPoint: function() {\n var leftTop = new fabric.Point(this.left, this.top);\n return this.translateToCenterPoint(leftTop, this.originX, this.originY);\n },\n\n /**\n * Returns the coordinates of the object based on center coordinates\n * @param {fabric.Point} point The point which corresponds to the originX and originY params\n * @return {fabric.Point}\n */\n // getOriginPoint: function(center) {\n // return this.translateToOriginPoint(center, this.originX, this.originY);\n // },\n\n /**\n * Returns the coordinates of the object as if it has a different origin\n * @param {String} originX Horizontal origin: 'left', 'center' or 'right'\n * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'\n * @return {fabric.Point}\n */\n getPointByOrigin: function(originX, originY) {\n var center = this.getCenterPoint();\n return this.translateToOriginPoint(center, originX, originY);\n },\n\n /**\n * Returns the point in local coordinates\n * @param {fabric.Point} point The point relative to the global coordinate system\n * @param {String} originX Horizontal origin: 'left', 'center' or 'right'\n * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'\n * @return {fabric.Point}\n */\n toLocalPoint: function(point, originX, originY) {\n var center = this.getCenterPoint(),\n p, p2;\n\n if (typeof originX !== 'undefined' && typeof originY !== 'undefined' ) {\n p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);\n }\n else {\n p = new fabric.Point(this.left, this.top);\n }\n\n p2 = new fabric.Point(point.x, point.y);\n if (this.angle) {\n p2 = fabric.util.rotatePoint(p2, center, -degreesToRadians(this.angle));\n }\n return p2.subtractEquals(p);\n },\n\n /**\n * Returns the point in global coordinates\n * @param {fabric.Point} The point relative to the local coordinate system\n * @return {fabric.Point}\n */\n // toGlobalPoint: function(point) {\n // return fabric.util.rotatePoint(point, this.getCenterPoint(), degreesToRadians(this.angle)).addEquals(new fabric.Point(this.left, this.top));\n // },\n\n /**\n * Sets the position of the object taking into consideration the object's origin\n * @param {fabric.Point} pos The new position of the object\n * @param {String} originX Horizontal origin: 'left', 'center' or 'right'\n * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'\n * @return {void}\n */\n setPositionByOrigin: function(pos, originX, originY) {\n var center = this.translateToCenterPoint(pos, originX, originY),\n position = this.translateToOriginPoint(center, this.originX, this.originY);\n this.set('left', position.x);\n this.set('top', position.y);\n },\n\n /**\n * @param {String} to One of 'left', 'center', 'right'\n */\n adjustPosition: function(to) {\n var angle = degreesToRadians(this.angle),\n hypotFull = this.getScaledWidth(),\n xFull = fabric.util.cos(angle) * hypotFull,\n yFull = fabric.util.sin(angle) * hypotFull,\n offsetFrom, offsetTo;\n\n //TODO: this function does not consider mixed situation like top, center.\n if (typeof this.originX === 'string') {\n offsetFrom = originXOffset[this.originX];\n }\n else {\n offsetFrom = this.originX - 0.5;\n }\n if (typeof to === 'string') {\n offsetTo = originXOffset[to];\n }\n else {\n offsetTo = to - 0.5;\n }\n this.left += xFull * (offsetTo - offsetFrom);\n this.top += yFull * (offsetTo - offsetFrom);\n this.setCoords();\n this.originX = to;\n },\n\n /**\n * Sets the origin/position of the object to it's center point\n * @private\n * @return {void}\n */\n _setOriginToCenter: function() {\n this._originalOriginX = this.originX;\n this._originalOriginY = this.originY;\n\n var center = this.getCenterPoint();\n\n this.originX = 'center';\n this.originY = 'center';\n\n this.left = center.x;\n this.top = center.y;\n },\n\n /**\n * Resets the origin/position of the object to it's original origin\n * @private\n * @return {void}\n */\n _resetOrigin: function() {\n var originPoint = this.translateToOriginPoint(\n this.getCenterPoint(),\n this._originalOriginX,\n this._originalOriginY);\n\n this.originX = this._originalOriginX;\n this.originY = this._originalOriginY;\n\n this.left = originPoint.x;\n this.top = originPoint.y;\n\n this._originalOriginX = null;\n this._originalOriginY = null;\n },\n\n /**\n * @private\n */\n _getLeftTopCoords: function() {\n return this.translateToOriginPoint(this.getCenterPoint(), 'left', 'top');\n },\n });\n\n})();\n\n\n(function() {\n\n function arrayFromCoords(coords) {\n return [\n new fabric.Point(coords.tl.x, coords.tl.y),\n new fabric.Point(coords.tr.x, coords.tr.y),\n new fabric.Point(coords.br.x, coords.br.y),\n new fabric.Point(coords.bl.x, coords.bl.y)\n ];\n }\n\n var util = fabric.util,\n degreesToRadians = util.degreesToRadians,\n multiplyMatrices = util.multiplyTransformMatrices,\n transformPoint = util.transformPoint;\n\n util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {\n\n /**\n * Describe object's corner position in canvas element coordinates.\n * properties are depending on control keys and padding the main controls.\n * each property is an object with x, y and corner.\n * The `corner` property contains in a similar manner the 4 points of the\n * interactive area of the corner.\n * The coordinates depends from the controls positionHandler and are used\n * to draw and locate controls\n * @memberOf fabric.Object.prototype\n */\n oCoords: null,\n\n /**\n * Describe object's corner position in canvas object absolute coordinates\n * properties are tl,tr,bl,br and describe the four main corner.\n * each property is an object with x, y, instance of Fabric.Point.\n * The coordinates depends from this properties: width, height, scaleX, scaleY\n * skewX, skewY, angle, strokeWidth, top, left.\n * Those coordinates are useful to understand where an object is. They get updated\n * with oCoords but they do not need to be updated when zoom or panning change.\n * The coordinates get updated with @method setCoords.\n * You can calculate them without updating with @method calcACoords();\n * @memberOf fabric.Object.prototype\n */\n aCoords: null,\n\n /**\n * Describe object's corner position in canvas element coordinates.\n * includes padding. Used of object detection.\n * set and refreshed with setCoords.\n * @memberOf fabric.Object.prototype\n */\n lineCoords: null,\n\n /**\n * storage for object transform matrix\n */\n ownMatrixCache: null,\n\n /**\n * storage for object full transform matrix\n */\n matrixCache: null,\n\n /**\n * custom controls interface\n * controls are added by default_controls.js\n */\n controls: { },\n\n /**\n * return correct set of coordinates for intersection\n * this will return either aCoords or lineCoords.\n * @param {Boolean} absolute will return aCoords if true or lineCoords\n * @return {Object} {tl, tr, br, bl} points\n */\n _getCoords: function(absolute, calculate) {\n if (calculate) {\n return (absolute ? this.calcACoords() : this.calcLineCoords());\n }\n if (!this.aCoords || !this.lineCoords) {\n this.setCoords(true);\n }\n return (absolute ? this.aCoords : this.lineCoords);\n },\n\n /**\n * return correct set of coordinates for intersection\n * this will return either aCoords or lineCoords.\n * The coords are returned in an array.\n * @return {Array} [tl, tr, br, bl] of points\n */\n getCoords: function(absolute, calculate) {\n return arrayFromCoords(this._getCoords(absolute, calculate));\n },\n\n /**\n * Checks if object intersects with an area formed by 2 points\n * @param {Object} pointTL top-left point of area\n * @param {Object} pointBR bottom-right point of area\n * @param {Boolean} [absolute] use coordinates without viewportTransform\n * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords\n * @return {Boolean} true if object intersects with an area formed by 2 points\n */\n intersectsWithRect: function(pointTL, pointBR, absolute, calculate) {\n var coords = this.getCoords(absolute, calculate),\n intersection = fabric.Intersection.intersectPolygonRectangle(\n coords,\n pointTL,\n pointBR\n );\n return intersection.status === 'Intersection';\n },\n\n /**\n * Checks if object intersects with another object\n * @param {Object} other Object to test\n * @param {Boolean} [absolute] use coordinates without viewportTransform\n * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords\n * @return {Boolean} true if object intersects with another object\n */\n intersectsWithObject: function(other, absolute, calculate) {\n var intersection = fabric.Intersection.intersectPolygonPolygon(\n this.getCoords(absolute, calculate),\n other.getCoords(absolute, calculate)\n );\n\n return intersection.status === 'Intersection'\n || other.isContainedWithinObject(this, absolute, calculate)\n || this.isContainedWithinObject(other, absolute, calculate);\n },\n\n /**\n * Checks if object is fully contained within area of another object\n * @param {Object} other Object to test\n * @param {Boolean} [absolute] use coordinates without viewportTransform\n * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords\n * @return {Boolean} true if object is fully contained within area of another object\n */\n isContainedWithinObject: function(other, absolute, calculate) {\n var points = this.getCoords(absolute, calculate),\n otherCoords = absolute ? other.aCoords : other.lineCoords,\n i = 0, lines = other._getImageLines(otherCoords);\n for (; i < 4; i++) {\n if (!other.containsPoint(points[i], lines)) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Checks if object is fully contained within area formed by 2 points\n * @param {Object} pointTL top-left point of area\n * @param {Object} pointBR bottom-right point of area\n * @param {Boolean} [absolute] use coordinates without viewportTransform\n * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords\n * @return {Boolean} true if object is fully contained within area formed by 2 points\n */\n isContainedWithinRect: function(pointTL, pointBR, absolute, calculate) {\n var boundingRect = this.getBoundingRect(absolute, calculate);\n\n return (\n boundingRect.left >= pointTL.x &&\n boundingRect.left + boundingRect.width <= pointBR.x &&\n boundingRect.top >= pointTL.y &&\n boundingRect.top + boundingRect.height <= pointBR.y\n );\n },\n\n /**\n * Checks if point is inside the object\n * @param {fabric.Point} point Point to check against\n * @param {Object} [lines] object returned from @method _getImageLines\n * @param {Boolean} [absolute] use coordinates without viewportTransform\n * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords\n * @return {Boolean} true if point is inside the object\n */\n containsPoint: function(point, lines, absolute, calculate) {\n var coords = this._getCoords(absolute, calculate),\n lines = lines || this._getImageLines(coords),\n xPoints = this._findCrossPoints(point, lines);\n // if xPoints is odd then point is inside the object\n return (xPoints !== 0 && xPoints % 2 === 1);\n },\n\n /**\n * Checks if object is contained within the canvas with current viewportTransform\n * the check is done stopping at first point that appears on screen\n * @param {Boolean} [calculate] use coordinates of current position instead of .aCoords\n * @return {Boolean} true if object is fully or partially contained within canvas\n */\n isOnScreen: function(calculate) {\n if (!this.canvas) {\n return false;\n }\n var pointTL = this.canvas.vptCoords.tl, pointBR = this.canvas.vptCoords.br;\n var points = this.getCoords(true, calculate);\n // if some point is on screen, the object is on screen.\n if (points.some(function(point) {\n return point.x <= pointBR.x && point.x >= pointTL.x &&\n point.y <= pointBR.y && point.y >= pointTL.y;\n })) {\n return true;\n }\n // no points on screen, check intersection with absolute coordinates\n if (this.intersectsWithRect(pointTL, pointBR, true, calculate)) {\n return true;\n }\n return this._containsCenterOfCanvas(pointTL, pointBR, calculate);\n },\n\n /**\n * Checks if the object contains the midpoint between canvas extremities\n * Does not make sense outside the context of isOnScreen and isPartiallyOnScreen\n * @private\n * @param {Fabric.Point} pointTL Top Left point\n * @param {Fabric.Point} pointBR Top Right point\n * @param {Boolean} calculate use coordinates of current position instead of .oCoords\n * @return {Boolean} true if the object contains the point\n */\n _containsCenterOfCanvas: function(pointTL, pointBR, calculate) {\n // worst case scenario the object is so big that contains the screen\n var centerPoint = { x: (pointTL.x + pointBR.x) / 2, y: (pointTL.y + pointBR.y) / 2 };\n if (this.containsPoint(centerPoint, null, true, calculate)) {\n return true;\n }\n return false;\n },\n\n /**\n * Checks if object is partially contained within the canvas with current viewportTransform\n * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords\n * @return {Boolean} true if object is partially contained within canvas\n */\n isPartiallyOnScreen: function(calculate) {\n if (!this.canvas) {\n return false;\n }\n var pointTL = this.canvas.vptCoords.tl, pointBR = this.canvas.vptCoords.br;\n if (this.intersectsWithRect(pointTL, pointBR, true, calculate)) {\n return true;\n }\n var allPointsAreOutside = this.getCoords(true, calculate).every(function(point) {\n return (point.x >= pointBR.x || point.x <= pointTL.x) &&\n (point.y >= pointBR.y || point.y <= pointTL.y);\n });\n return allPointsAreOutside && this._containsCenterOfCanvas(pointTL, pointBR, calculate);\n },\n\n /**\n * Method that returns an object with the object edges in it, given the coordinates of the corners\n * @private\n * @param {Object} oCoords Coordinates of the object corners\n */\n _getImageLines: function(oCoords) {\n\n var lines = {\n topline: {\n o: oCoords.tl,\n d: oCoords.tr\n },\n rightline: {\n o: oCoords.tr,\n d: oCoords.br\n },\n bottomline: {\n o: oCoords.br,\n d: oCoords.bl\n },\n leftline: {\n o: oCoords.bl,\n d: oCoords.tl\n }\n };\n\n // // debugging\n // if (this.canvas.contextTop) {\n // this.canvas.contextTop.fillRect(lines.bottomline.d.x, lines.bottomline.d.y, 2, 2);\n // this.canvas.contextTop.fillRect(lines.bottomline.o.x, lines.bottomline.o.y, 2, 2);\n //\n // this.canvas.contextTop.fillRect(lines.leftline.d.x, lines.leftline.d.y, 2, 2);\n // this.canvas.contextTop.fillRect(lines.leftline.o.x, lines.leftline.o.y, 2, 2);\n //\n // this.canvas.contextTop.fillRect(lines.topline.d.x, lines.topline.d.y, 2, 2);\n // this.canvas.contextTop.fillRect(lines.topline.o.x, lines.topline.o.y, 2, 2);\n //\n // this.canvas.contextTop.fillRect(lines.rightline.d.x, lines.rightline.d.y, 2, 2);\n // this.canvas.contextTop.fillRect(lines.rightline.o.x, lines.rightline.o.y, 2, 2);\n // }\n\n return lines;\n },\n\n /**\n * Helper method to determine how many cross points are between the 4 object edges\n * and the horizontal line determined by a point on canvas\n * @private\n * @param {fabric.Point} point Point to check\n * @param {Object} lines Coordinates of the object being evaluated\n */\n // remove yi, not used but left code here just in case.\n _findCrossPoints: function(point, lines) {\n var b1, b2, a1, a2, xi, // yi,\n xcount = 0,\n iLine;\n\n for (var lineKey in lines) {\n iLine = lines[lineKey];\n // optimisation 1: line below point. no cross\n if ((iLine.o.y < point.y) && (iLine.d.y < point.y)) {\n continue;\n }\n // optimisation 2: line above point. no cross\n if ((iLine.o.y >= point.y) && (iLine.d.y >= point.y)) {\n continue;\n }\n // optimisation 3: vertical line case\n if ((iLine.o.x === iLine.d.x) && (iLine.o.x >= point.x)) {\n xi = iLine.o.x;\n // yi = point.y;\n }\n // calculate the intersection point\n else {\n b1 = 0;\n b2 = (iLine.d.y - iLine.o.y) / (iLine.d.x - iLine.o.x);\n a1 = point.y - b1 * point.x;\n a2 = iLine.o.y - b2 * iLine.o.x;\n\n xi = -(a1 - a2) / (b1 - b2);\n // yi = a1 + b1 * xi;\n }\n // dont count xi < point.x cases\n if (xi >= point.x) {\n xcount += 1;\n }\n // optimisation 4: specific for square images\n if (xcount === 2) {\n break;\n }\n }\n return xcount;\n },\n\n /**\n * Returns coordinates of object's bounding rectangle (left, top, width, height)\n * the box is intended as aligned to axis of canvas.\n * @param {Boolean} [absolute] use coordinates without viewportTransform\n * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords / .aCoords\n * @return {Object} Object with left, top, width, height properties\n */\n getBoundingRect: function(absolute, calculate) {\n var coords = this.getCoords(absolute, calculate);\n return util.makeBoundingBoxFromPoints(coords);\n },\n\n /**\n * Returns width of an object's bounding box counting transformations\n * before 2.0 it was named getWidth();\n * @return {Number} width value\n */\n getScaledWidth: function() {\n return this._getTransformedDimensions().x;\n },\n\n /**\n * Returns height of an object bounding box counting transformations\n * before 2.0 it was named getHeight();\n * @return {Number} height value\n */\n getScaledHeight: function() {\n return this._getTransformedDimensions().y;\n },\n\n /**\n * Makes sure the scale is valid and modifies it if necessary\n * @private\n * @param {Number} value\n * @return {Number}\n */\n _constrainScale: function(value) {\n if (Math.abs(value) < this.minScaleLimit) {\n if (value < 0) {\n return -this.minScaleLimit;\n }\n else {\n return this.minScaleLimit;\n }\n }\n else if (value === 0) {\n return 0.0001;\n }\n return value;\n },\n\n /**\n * Scales an object (equally by x and y)\n * @param {Number} value Scale factor\n * @return {fabric.Object} thisArg\n * @chainable\n */\n scale: function(value) {\n this._set('scaleX', value);\n this._set('scaleY', value);\n return this.setCoords();\n },\n\n /**\n * Scales an object to a given width, with respect to bounding box (scaling by x/y equally)\n * @param {Number} value New width value\n * @param {Boolean} absolute ignore viewport\n * @return {fabric.Object} thisArg\n * @chainable\n */\n scaleToWidth: function(value, absolute) {\n // adjust to bounding rect factor so that rotated shapes would fit as well\n var boundingRectFactor = this.getBoundingRect(absolute).width / this.getScaledWidth();\n return this.scale(value / this.width / boundingRectFactor);\n },\n\n /**\n * Scales an object to a given height, with respect to bounding box (scaling by x/y equally)\n * @param {Number} value New height value\n * @param {Boolean} absolute ignore viewport\n * @return {fabric.Object} thisArg\n * @chainable\n */\n scaleToHeight: function(value, absolute) {\n // adjust to bounding rect factor so that rotated shapes would fit as well\n var boundingRectFactor = this.getBoundingRect(absolute).height / this.getScaledHeight();\n return this.scale(value / this.height / boundingRectFactor);\n },\n\n calcLineCoords: function() {\n var vpt = this.getViewportTransform(),\n padding = this.padding, angle = degreesToRadians(this.angle),\n cos = util.cos(angle), sin = util.sin(angle),\n cosP = cos * padding, sinP = sin * padding, cosPSinP = cosP + sinP,\n cosPMinusSinP = cosP - sinP, aCoords = this.calcACoords();\n\n var lineCoords = {\n tl: transformPoint(aCoords.tl, vpt),\n tr: transformPoint(aCoords.tr, vpt),\n bl: transformPoint(aCoords.bl, vpt),\n br: transformPoint(aCoords.br, vpt),\n };\n\n if (padding) {\n lineCoords.tl.x -= cosPMinusSinP;\n lineCoords.tl.y -= cosPSinP;\n lineCoords.tr.x += cosPSinP;\n lineCoords.tr.y -= cosPMinusSinP;\n lineCoords.bl.x -= cosPSinP;\n lineCoords.bl.y += cosPMinusSinP;\n lineCoords.br.x += cosPMinusSinP;\n lineCoords.br.y += cosPSinP;\n }\n\n return lineCoords;\n },\n\n calcOCoords: function() {\n var rotateMatrix = this._calcRotateMatrix(),\n translateMatrix = this._calcTranslateMatrix(),\n vpt = this.getViewportTransform(),\n startMatrix = multiplyMatrices(vpt, translateMatrix),\n finalMatrix = multiplyMatrices(startMatrix, rotateMatrix),\n finalMatrix = multiplyMatrices(finalMatrix, [1 / vpt[0], 0, 0, 1 / vpt[3], 0, 0]),\n dim = this._calculateCurrentDimensions(),\n coords = {};\n this.forEachControl(function(control, key, fabricObject) {\n coords[key] = control.positionHandler(dim, finalMatrix, fabricObject);\n });\n\n // debug code\n // var canvas = this.canvas;\n // setTimeout(function() {\n // canvas.contextTop.clearRect(0, 0, 700, 700);\n // canvas.contextTop.fillStyle = 'green';\n // Object.keys(coords).forEach(function(key) {\n // var control = coords[key];\n // canvas.contextTop.fillRect(control.x, control.y, 3, 3);\n // });\n // }, 50);\n return coords;\n },\n\n calcACoords: function() {\n var rotateMatrix = this._calcRotateMatrix(),\n translateMatrix = this._calcTranslateMatrix(),\n finalMatrix = multiplyMatrices(translateMatrix, rotateMatrix),\n dim = this._getTransformedDimensions(),\n w = dim.x / 2, h = dim.y / 2;\n return {\n // corners\n tl: transformPoint({ x: -w, y: -h }, finalMatrix),\n tr: transformPoint({ x: w, y: -h }, finalMatrix),\n bl: transformPoint({ x: -w, y: h }, finalMatrix),\n br: transformPoint({ x: w, y: h }, finalMatrix)\n };\n },\n\n /**\n * Sets corner and controls position coordinates based on current angle, width and height, left and top.\n * oCoords are used to find the corners\n * aCoords are used to quickly find an object on the canvas\n * lineCoords are used to quickly find object during pointer events.\n * See {@link https://github.com/fabricjs/fabric.js/wiki/When-to-call-setCoords} and {@link http://fabricjs.com/fabric-gotchas}\n *\n * @param {Boolean} [skipCorners] skip calculation of oCoords.\n * @return {fabric.Object} thisArg\n * @chainable\n */\n setCoords: function(skipCorners) {\n this.aCoords = this.calcACoords();\n // in case we are in a group, for how the inner group target check works,\n // lineCoords are exactly aCoords. Since the vpt gets absorbed by the normalized pointer.\n this.lineCoords = this.group ? this.aCoords : this.calcLineCoords();\n if (skipCorners) {\n return this;\n }\n // set coordinates of the draggable boxes in the corners used to scale/rotate the image\n this.oCoords = this.calcOCoords();\n this._setCornerCoords && this._setCornerCoords();\n return this;\n },\n\n /**\n * calculate rotation matrix of an object\n * @return {Array} rotation matrix for the object\n */\n _calcRotateMatrix: function() {\n return util.calcRotateMatrix(this);\n },\n\n /**\n * calculate the translation matrix for an object transform\n * @return {Array} rotation matrix for the object\n */\n _calcTranslateMatrix: function() {\n var center = this.getCenterPoint();\n return [1, 0, 0, 1, center.x, center.y];\n },\n\n transformMatrixKey: function(skipGroup) {\n var sep = '_', prefix = '';\n if (!skipGroup && this.group) {\n prefix = this.group.transformMatrixKey(skipGroup) + sep;\n };\n return prefix + this.top + sep + this.left + sep + this.scaleX + sep + this.scaleY +\n sep + this.skewX + sep + this.skewY + sep + this.angle + sep + this.originX + sep + this.originY +\n sep + this.width + sep + this.height + sep + this.strokeWidth + this.flipX + this.flipY;\n },\n\n /**\n * calculate transform matrix that represents the current transformations from the\n * object's properties.\n * @param {Boolean} [skipGroup] return transform matrix for object not counting parent transformations\n * There are some situation in which this is useful to avoid the fake rotation.\n * @return {Array} transform matrix for the object\n */\n calcTransformMatrix: function(skipGroup) {\n var matrix = this.calcOwnMatrix();\n if (skipGroup || !this.group) {\n return matrix;\n }\n var key = this.transformMatrixKey(skipGroup), cache = this.matrixCache || (this.matrixCache = {});\n if (cache.key === key) {\n return cache.value;\n }\n if (this.group) {\n matrix = multiplyMatrices(this.group.calcTransformMatrix(false), matrix);\n }\n cache.key = key;\n cache.value = matrix;\n return matrix;\n },\n\n /**\n * calculate transform matrix that represents the current transformations from the\n * object's properties, this matrix does not include the group transformation\n * @return {Array} transform matrix for the object\n */\n calcOwnMatrix: function() {\n var key = this.transformMatrixKey(true), cache = this.ownMatrixCache || (this.ownMatrixCache = {});\n if (cache.key === key) {\n return cache.value;\n }\n var tMatrix = this._calcTranslateMatrix(),\n options = {\n angle: this.angle,\n translateX: tMatrix[4],\n translateY: tMatrix[5],\n scaleX: this.scaleX,\n scaleY: this.scaleY,\n skewX: this.skewX,\n skewY: this.skewY,\n flipX: this.flipX,\n flipY: this.flipY,\n };\n cache.key = key;\n cache.value = util.composeMatrix(options);\n return cache.value;\n },\n\n /*\n * Calculate object dimensions from its properties\n * @private\n * @return {Object} .x width dimension\n * @return {Object} .y height dimension\n */\n _getNonTransformedDimensions: function() {\n var strokeWidth = this.strokeWidth,\n w = this.width + strokeWidth,\n h = this.height + strokeWidth;\n return { x: w, y: h };\n },\n\n /*\n * Calculate object bounding box dimensions from its properties scale, skew.\n * @param {Number} skewX, a value to override current skewX\n * @param {Number} skewY, a value to override current skewY\n * @private\n * @return {Object} .x width dimension\n * @return {Object} .y height dimension\n */\n _getTransformedDimensions: function(skewX, skewY) {\n if (typeof skewX === 'undefined') {\n skewX = this.skewX;\n }\n if (typeof skewY === 'undefined') {\n skewY = this.skewY;\n }\n var dimensions, dimX, dimY,\n noSkew = skewX === 0 && skewY === 0;\n\n if (this.strokeUniform) {\n dimX = this.width;\n dimY = this.height;\n }\n else {\n dimensions = this._getNonTransformedDimensions();\n dimX = dimensions.x;\n dimY = dimensions.y;\n }\n if (noSkew) {\n return this._finalizeDimensions(dimX * this.scaleX, dimY * this.scaleY);\n }\n var bbox = util.sizeAfterTransform(dimX, dimY, {\n scaleX: this.scaleX,\n scaleY: this.scaleY,\n skewX: skewX,\n skewY: skewY,\n });\n return this._finalizeDimensions(bbox.x, bbox.y);\n },\n\n /*\n * Calculate object bounding box dimensions from its properties scale, skew.\n * @param Number width width of the bbox\n * @param Number height height of the bbox\n * @private\n * @return {Object} .x finalized width dimension\n * @return {Object} .y finalized height dimension\n */\n _finalizeDimensions: function(width, height) {\n return this.strokeUniform ?\n { x: width + this.strokeWidth, y: height + this.strokeWidth }\n :\n { x: width, y: height };\n },\n\n /*\n * Calculate object dimensions for controls box, including padding and canvas zoom.\n * and active selection\n * private\n */\n _calculateCurrentDimensions: function() {\n var vpt = this.getViewportTransform(),\n dim = this._getTransformedDimensions(),\n p = transformPoint(dim, vpt, true);\n return p.scalarAdd(2 * this.padding);\n },\n });\n})();\n\n\nfabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {\n\n /**\n * Moves an object to the bottom of the stack of drawn objects\n * @return {fabric.Object} thisArg\n * @chainable\n */\n sendToBack: function() {\n if (this.group) {\n fabric.StaticCanvas.prototype.sendToBack.call(this.group, this);\n }\n else if (this.canvas) {\n this.canvas.sendToBack(this);\n }\n return this;\n },\n\n /**\n * Moves an object to the top of the stack of drawn objects\n * @return {fabric.Object} thisArg\n * @chainable\n */\n bringToFront: function() {\n if (this.group) {\n fabric.StaticCanvas.prototype.bringToFront.call(this.group, this);\n }\n else if (this.canvas) {\n this.canvas.bringToFront(this);\n }\n return this;\n },\n\n /**\n * Moves an object down in stack of drawn objects\n * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object\n * @return {fabric.Object} thisArg\n * @chainable\n */\n sendBackwards: function(intersecting) {\n if (this.group) {\n fabric.StaticCanvas.prototype.sendBackwards.call(this.group, this, intersecting);\n }\n else if (this.canvas) {\n this.canvas.sendBackwards(this, intersecting);\n }\n return this;\n },\n\n /**\n * Moves an object up in stack of drawn objects\n * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object\n * @return {fabric.Object} thisArg\n * @chainable\n */\n bringForward: function(intersecting) {\n if (this.group) {\n fabric.StaticCanvas.prototype.bringForward.call(this.group, this, intersecting);\n }\n else if (this.canvas) {\n this.canvas.bringForward(this, intersecting);\n }\n return this;\n },\n\n /**\n * Moves an object to specified level in stack of drawn objects\n * @param {Number} index New position of object\n * @return {fabric.Object} thisArg\n * @chainable\n */\n moveTo: function(index) {\n if (this.group && this.group.type !== 'activeSelection') {\n fabric.StaticCanvas.prototype.moveTo.call(this.group, this, index);\n }\n else if (this.canvas) {\n this.canvas.moveTo(this, index);\n }\n return this;\n }\n});\n\n\n/* _TO_SVG_START_ */\n(function() {\n function getSvgColorString(prop, value) {\n if (!value) {\n return prop + ': none; ';\n }\n else if (value.toLive) {\n return prop + ': url(#SVGID_' + value.id + '); ';\n }\n else {\n var color = new fabric.Color(value),\n str = prop + ': ' + color.toRgb() + '; ',\n opacity = color.getAlpha();\n if (opacity !== 1) {\n //change the color in rgb + opacity\n str += prop + '-opacity: ' + opacity.toString() + '; ';\n }\n return str;\n }\n }\n\n var toFixed = fabric.util.toFixed;\n\n fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {\n /**\n * Returns styles-string for svg-export\n * @param {Boolean} skipShadow a boolean to skip shadow filter output\n * @return {String}\n */\n getSvgStyles: function(skipShadow) {\n\n var fillRule = this.fillRule ? this.fillRule : 'nonzero',\n strokeWidth = this.strokeWidth ? this.strokeWidth : '0',\n strokeDashArray = this.strokeDashArray ? this.strokeDashArray.join(' ') : 'none',\n strokeDashOffset = this.strokeDashOffset ? this.strokeDashOffset : '0',\n strokeLineCap = this.strokeLineCap ? this.strokeLineCap : 'butt',\n strokeLineJoin = this.strokeLineJoin ? this.strokeLineJoin : 'miter',\n strokeMiterLimit = this.strokeMiterLimit ? this.strokeMiterLimit : '4',\n opacity = typeof this.opacity !== 'undefined' ? this.opacity : '1',\n visibility = this.visible ? '' : ' visibility: hidden;',\n filter = skipShadow ? '' : this.getSvgFilter(),\n fill = getSvgColorString('fill', this.fill),\n stroke = getSvgColorString('stroke', this.stroke);\n\n return [\n stroke,\n 'stroke-width: ', strokeWidth, '; ',\n 'stroke-dasharray: ', strokeDashArray, '; ',\n 'stroke-linecap: ', strokeLineCap, '; ',\n 'stroke-dashoffset: ', strokeDashOffset, '; ',\n 'stroke-linejoin: ', strokeLineJoin, '; ',\n 'stroke-miterlimit: ', strokeMiterLimit, '; ',\n fill,\n 'fill-rule: ', fillRule, '; ',\n 'opacity: ', opacity, ';',\n filter,\n visibility\n ].join('');\n },\n\n /**\n * Returns styles-string for svg-export\n * @param {Object} style the object from which to retrieve style properties\n * @param {Boolean} useWhiteSpace a boolean to include an additional attribute in the style.\n * @return {String}\n */\n getSvgSpanStyles: function(style, useWhiteSpace) {\n var term = '; ';\n var fontFamily = style.fontFamily ?\n 'font-family: ' + (((style.fontFamily.indexOf('\\'') === -1 && style.fontFamily.indexOf('\"') === -1) ?\n '\\'' + style.fontFamily + '\\'' : style.fontFamily)) + term : '';\n var strokeWidth = style.strokeWidth ? 'stroke-width: ' + style.strokeWidth + term : '',\n fontFamily = fontFamily,\n fontSize = style.fontSize ? 'font-size: ' + style.fontSize + 'px' + term : '',\n fontStyle = style.fontStyle ? 'font-style: ' + style.fontStyle + term : '',\n fontWeight = style.fontWeight ? 'font-weight: ' + style.fontWeight + term : '',\n fill = style.fill ? getSvgColorString('fill', style.fill) : '',\n stroke = style.stroke ? getSvgColorString('stroke', style.stroke) : '',\n textDecoration = this.getSvgTextDecoration(style),\n deltaY = style.deltaY ? 'baseline-shift: ' + (-style.deltaY) + '; ' : '';\n if (textDecoration) {\n textDecoration = 'text-decoration: ' + textDecoration + term;\n }\n\n return [\n stroke,\n strokeWidth,\n fontFamily,\n fontSize,\n fontStyle,\n fontWeight,\n textDecoration,\n fill,\n deltaY,\n useWhiteSpace ? 'white-space: pre; ' : ''\n ].join('');\n },\n\n /**\n * Returns text-decoration property for svg-export\n * @param {Object} style the object from which to retrieve style properties\n * @return {String}\n */\n getSvgTextDecoration: function(style) {\n return ['overline', 'underline', 'line-through'].filter(function(decoration) {\n return style[decoration.replace('-', '')];\n }).join(' ');\n },\n\n /**\n * Returns filter for svg shadow\n * @return {String}\n */\n getSvgFilter: function() {\n return this.shadow ? 'filter: url(#SVGID_' + this.shadow.id + ');' : '';\n },\n\n /**\n * Returns id attribute for svg output\n * @return {String}\n */\n getSvgCommons: function() {\n return [\n this.id ? 'id=\"' + this.id + '\" ' : '',\n this.clipPath ? 'clip-path=\"url(#' + this.clipPath.clipPathId + ')\" ' : '',\n ].join('');\n },\n\n /**\n * Returns transform-string for svg-export\n * @param {Boolean} use the full transform or the single object one.\n * @return {String}\n */\n getSvgTransform: function(full, additionalTransform) {\n var transform = full ? this.calcTransformMatrix() : this.calcOwnMatrix(),\n svgTransform = 'transform=\"' + fabric.util.matrixToSVG(transform);\n return svgTransform +\n (additionalTransform || '') + '\" ';\n },\n\n _setSVGBg: function(textBgRects) {\n if (this.backgroundColor) {\n var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;\n textBgRects.push(\n '\\t\\t\\n');\n }\n },\n\n /**\n * Returns svg representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {String} svg representation of an instance\n */\n toSVG: function(reviver) {\n return this._createBaseSVGMarkup(this._toSVG(reviver), { reviver: reviver });\n },\n\n /**\n * Returns svg clipPath representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {String} svg representation of an instance\n */\n toClipPathSVG: function(reviver) {\n return '\\t' + this._createBaseClipPathSVGMarkup(this._toSVG(reviver), { reviver: reviver });\n },\n\n /**\n * @private\n */\n _createBaseClipPathSVGMarkup: function(objectMarkup, options) {\n options = options || {};\n var reviver = options.reviver,\n additionalTransform = options.additionalTransform || '',\n commonPieces = [\n this.getSvgTransform(true, additionalTransform),\n this.getSvgCommons(),\n ].join(''),\n // insert commons in the markup, style and svgCommons\n index = objectMarkup.indexOf('COMMON_PARTS');\n objectMarkup[index] = commonPieces;\n return reviver ? reviver(objectMarkup.join('')) : objectMarkup.join('');\n },\n\n /**\n * @private\n */\n _createBaseSVGMarkup: function(objectMarkup, options) {\n options = options || {};\n var noStyle = options.noStyle,\n reviver = options.reviver,\n styleInfo = noStyle ? '' : 'style=\"' + this.getSvgStyles() + '\" ',\n shadowInfo = options.withShadow ? 'style=\"' + this.getSvgFilter() + '\" ' : '',\n clipPath = this.clipPath,\n vectorEffect = this.strokeUniform ? 'vector-effect=\"non-scaling-stroke\" ' : '',\n absoluteClipPath = clipPath && clipPath.absolutePositioned,\n stroke = this.stroke, fill = this.fill, shadow = this.shadow,\n commonPieces, markup = [], clipPathMarkup,\n // insert commons in the markup, style and svgCommons\n index = objectMarkup.indexOf('COMMON_PARTS'),\n additionalTransform = options.additionalTransform;\n if (clipPath) {\n clipPath.clipPathId = 'CLIPPATH_' + fabric.Object.__uid++;\n clipPathMarkup = '\\n' +\n clipPath.toClipPathSVG(reviver) +\n '\\n';\n }\n if (absoluteClipPath) {\n markup.push(\n '\\n'\n );\n }\n markup.push(\n '\\n'\n );\n commonPieces = [\n styleInfo,\n vectorEffect,\n noStyle ? '' : this.addPaintOrder(), ' ',\n additionalTransform ? 'transform=\"' + additionalTransform + '\" ' : '',\n ].join('');\n objectMarkup[index] = commonPieces;\n if (fill && fill.toLive) {\n markup.push(fill.toSVG(this));\n }\n if (stroke && stroke.toLive) {\n markup.push(stroke.toSVG(this));\n }\n if (shadow) {\n markup.push(shadow.toSVG(this));\n }\n if (clipPath) {\n markup.push(clipPathMarkup);\n }\n markup.push(objectMarkup.join(''));\n markup.push('\\n');\n absoluteClipPath && markup.push('\\n');\n return reviver ? reviver(markup.join('')) : markup.join('');\n },\n\n addPaintOrder: function() {\n return this.paintFirst !== 'fill' ? ' paint-order=\"' + this.paintFirst + '\" ' : '';\n }\n });\n})();\n/* _TO_SVG_END_ */\n\n\n(function() {\n\n var extend = fabric.util.object.extend,\n originalSet = 'stateProperties';\n\n /*\n Depends on `stateProperties`\n */\n function saveProps(origin, destination, props) {\n var tmpObj = { }, deep = true;\n props.forEach(function(prop) {\n tmpObj[prop] = origin[prop];\n });\n\n extend(origin[destination], tmpObj, deep);\n }\n\n function _isEqual(origValue, currentValue, firstPass) {\n if (origValue === currentValue) {\n // if the objects are identical, return\n return true;\n }\n else if (Array.isArray(origValue)) {\n if (!Array.isArray(currentValue) || origValue.length !== currentValue.length) {\n return false;\n }\n for (var i = 0, len = origValue.length; i < len; i++) {\n if (!_isEqual(origValue[i], currentValue[i])) {\n return false;\n }\n }\n return true;\n }\n else if (origValue && typeof origValue === 'object') {\n var keys = Object.keys(origValue), key;\n if (!currentValue ||\n typeof currentValue !== 'object' ||\n (!firstPass && keys.length !== Object.keys(currentValue).length)\n ) {\n return false;\n }\n for (var i = 0, len = keys.length; i < len; i++) {\n key = keys[i];\n // since clipPath is in the statefull cache list and the clipPath objects\n // would be iterated as an object, this would lead to possible infinite recursion\n // we do not want to compare those.\n if (key === 'canvas' || key === 'group') {\n continue;\n }\n if (!_isEqual(origValue[key], currentValue[key])) {\n return false;\n }\n }\n return true;\n }\n }\n\n\n fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {\n\n /**\n * Returns true if object state (one of its state properties) was changed\n * @param {String} [propertySet] optional name for the set of property we want to save\n * @return {Boolean} true if instance' state has changed since `{@link fabric.Object#saveState}` was called\n */\n hasStateChanged: function(propertySet) {\n propertySet = propertySet || originalSet;\n var dashedPropertySet = '_' + propertySet;\n if (Object.keys(this[dashedPropertySet]).length < this[propertySet].length) {\n return true;\n }\n return !_isEqual(this[dashedPropertySet], this, true);\n },\n\n /**\n * Saves state of an object\n * @param {Object} [options] Object with additional `stateProperties` array to include when saving state\n * @return {fabric.Object} thisArg\n */\n saveState: function(options) {\n var propertySet = options && options.propertySet || originalSet,\n destination = '_' + propertySet;\n if (!this[destination]) {\n return this.setupState(options);\n }\n saveProps(this, destination, this[propertySet]);\n if (options && options.stateProperties) {\n saveProps(this, destination, options.stateProperties);\n }\n return this;\n },\n\n /**\n * Setups state of an object\n * @param {Object} [options] Object with additional `stateProperties` array to include when saving state\n * @return {fabric.Object} thisArg\n */\n setupState: function(options) {\n options = options || { };\n var propertySet = options.propertySet || originalSet;\n options.propertySet = propertySet;\n this['_' + propertySet] = { };\n this.saveState(options);\n return this;\n }\n });\n})();\n\n\n(function() {\n\n var degreesToRadians = fabric.util.degreesToRadians;\n\n fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {\n /**\n * Determines which corner has been clicked\n * @private\n * @param {Object} pointer The pointer indicating the mouse position\n * @return {String|Boolean} corner code (tl, tr, bl, br, etc.), or false if nothing is found\n */\n _findTargetCorner: function(pointer, forTouch) {\n // objects in group, anykind, are not self modificable,\n // must not return an hovered corner.\n if (!this.hasControls || this.group || (!this.canvas || this.canvas._activeObject !== this)) {\n return false;\n }\n\n var ex = pointer.x,\n ey = pointer.y,\n xPoints,\n lines, keys = Object.keys(this.oCoords),\n j = keys.length - 1, i;\n this.__corner = 0;\n\n // cycle in reverse order so we pick first the one on top\n for (; j >= 0; j--) {\n i = keys[j];\n if (!this.isControlVisible(i)) {\n continue;\n }\n\n lines = this._getImageLines(forTouch ? this.oCoords[i].touchCorner : this.oCoords[i].corner);\n // // debugging\n //\n // this.canvas.contextTop.fillRect(lines.bottomline.d.x, lines.bottomline.d.y, 2, 2);\n // this.canvas.contextTop.fillRect(lines.bottomline.o.x, lines.bottomline.o.y, 2, 2);\n //\n // this.canvas.contextTop.fillRect(lines.leftline.d.x, lines.leftline.d.y, 2, 2);\n // this.canvas.contextTop.fillRect(lines.leftline.o.x, lines.leftline.o.y, 2, 2);\n //\n // this.canvas.contextTop.fillRect(lines.topline.d.x, lines.topline.d.y, 2, 2);\n // this.canvas.contextTop.fillRect(lines.topline.o.x, lines.topline.o.y, 2, 2);\n //\n // this.canvas.contextTop.fillRect(lines.rightline.d.x, lines.rightline.d.y, 2, 2);\n // this.canvas.contextTop.fillRect(lines.rightline.o.x, lines.rightline.o.y, 2, 2);\n\n xPoints = this._findCrossPoints({ x: ex, y: ey }, lines);\n if (xPoints !== 0 && xPoints % 2 === 1) {\n this.__corner = i;\n return i;\n }\n }\n return false;\n },\n\n /**\n * Calls a function for each control. The function gets called,\n * with the control, the object that is calling the iterator and the control's key\n * @param {Function} fn function to iterate over the controls over\n */\n forEachControl: function(fn) {\n for (var i in this.controls) {\n fn(this.controls[i], i, this);\n };\n },\n\n /**\n * Sets the coordinates of the draggable boxes in the corners of\n * the image used to scale/rotate it.\n * note: if we would switch to ROUND corner area, all of this would disappear.\n * everything would resolve to a single point and a pythagorean theorem for the distance\n * @private\n */\n _setCornerCoords: function() {\n var coords = this.oCoords;\n\n for (var control in coords) {\n var controlObject = this.controls[control];\n coords[control].corner = controlObject.calcCornerCoords(\n this.angle, this.cornerSize, coords[control].x, coords[control].y, false);\n coords[control].touchCorner = controlObject.calcCornerCoords(\n this.angle, this.touchCornerSize, coords[control].x, coords[control].y, true);\n }\n },\n\n /**\n * Draws a colored layer behind the object, inside its selection borders.\n * Requires public options: padding, selectionBackgroundColor\n * this function is called when the context is transformed\n * has checks to be skipped when the object is on a staticCanvas\n * @param {CanvasRenderingContext2D} ctx Context to draw on\n * @return {fabric.Object} thisArg\n * @chainable\n */\n drawSelectionBackground: function(ctx) {\n if (!this.selectionBackgroundColor ||\n (this.canvas && !this.canvas.interactive) ||\n (this.canvas && this.canvas._activeObject !== this)\n ) {\n return this;\n }\n ctx.save();\n var center = this.getCenterPoint(), wh = this._calculateCurrentDimensions(),\n vpt = this.canvas.viewportTransform;\n ctx.translate(center.x, center.y);\n ctx.scale(1 / vpt[0], 1 / vpt[3]);\n ctx.rotate(degreesToRadians(this.angle));\n ctx.fillStyle = this.selectionBackgroundColor;\n ctx.fillRect(-wh.x / 2, -wh.y / 2, wh.x, wh.y);\n ctx.restore();\n return this;\n },\n\n /**\n * Draws borders of an object's bounding box.\n * Requires public properties: width, height\n * Requires public options: padding, borderColor\n * @param {CanvasRenderingContext2D} ctx Context to draw on\n * @param {Object} styleOverride object to override the object style\n * @return {fabric.Object} thisArg\n * @chainable\n */\n drawBorders: function(ctx, styleOverride) {\n styleOverride = styleOverride || {};\n var wh = this._calculateCurrentDimensions(),\n strokeWidth = this.borderScaleFactor,\n width = wh.x + strokeWidth,\n height = wh.y + strokeWidth,\n hasControls = typeof styleOverride.hasControls !== 'undefined' ?\n styleOverride.hasControls : this.hasControls,\n shouldStroke = false;\n\n ctx.save();\n ctx.strokeStyle = styleOverride.borderColor || this.borderColor;\n this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray);\n\n ctx.strokeRect(\n -width / 2,\n -height / 2,\n width,\n height\n );\n\n if (hasControls) {\n ctx.beginPath();\n this.forEachControl(function(control, key, fabricObject) {\n // in this moment, the ctx is centered on the object.\n // width and height of the above function are the size of the bbox.\n if (control.withConnection && control.getVisibility(fabricObject, key)) {\n // reset movement for each control\n shouldStroke = true;\n ctx.moveTo(control.x * width, control.y * height);\n ctx.lineTo(\n control.x * width + control.offsetX,\n control.y * height + control.offsetY\n );\n }\n });\n if (shouldStroke) {\n ctx.stroke();\n }\n }\n ctx.restore();\n return this;\n },\n\n /**\n * Draws borders of an object's bounding box when it is inside a group.\n * Requires public properties: width, height\n * Requires public options: padding, borderColor\n * @param {CanvasRenderingContext2D} ctx Context to draw on\n * @param {object} options object representing current object parameters\n * @param {Object} styleOverride object to override the object style\n * @return {fabric.Object} thisArg\n * @chainable\n */\n drawBordersInGroup: function(ctx, options, styleOverride) {\n styleOverride = styleOverride || {};\n var bbox = fabric.util.sizeAfterTransform(this.width, this.height, options),\n strokeWidth = this.strokeWidth,\n strokeUniform = this.strokeUniform,\n borderScaleFactor = this.borderScaleFactor,\n width =\n bbox.x + strokeWidth * (strokeUniform ? this.canvas.getZoom() : options.scaleX) + borderScaleFactor,\n height =\n bbox.y + strokeWidth * (strokeUniform ? this.canvas.getZoom() : options.scaleY) + borderScaleFactor;\n ctx.save();\n this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray);\n ctx.strokeStyle = styleOverride.borderColor || this.borderColor;\n ctx.strokeRect(\n -width / 2,\n -height / 2,\n width,\n height\n );\n\n ctx.restore();\n return this;\n },\n\n /**\n * Draws corners of an object's bounding box.\n * Requires public properties: width, height\n * Requires public options: cornerSize, padding\n * @param {CanvasRenderingContext2D} ctx Context to draw on\n * @param {Object} styleOverride object to override the object style\n * @return {fabric.Object} thisArg\n * @chainable\n */\n drawControls: function(ctx, styleOverride) {\n styleOverride = styleOverride || {};\n ctx.save();\n var retinaScaling = this.canvas.getRetinaScaling(), matrix, p;\n ctx.setTransform(retinaScaling, 0, 0, retinaScaling, 0, 0);\n ctx.strokeStyle = ctx.fillStyle = styleOverride.cornerColor || this.cornerColor;\n if (!this.transparentCorners) {\n ctx.strokeStyle = styleOverride.cornerStrokeColor || this.cornerStrokeColor;\n }\n this._setLineDash(ctx, styleOverride.cornerDashArray || this.cornerDashArray);\n this.setCoords();\n if (this.group) {\n // fabricJS does not really support drawing controls inside groups,\n // this piece of code here helps having at least the control in places.\n // If an application needs to show some objects as selected because of some UI state\n // can still call Object._renderControls() on any object they desire, independently of groups.\n // using no padding, circular controls and hiding the rotating cursor is higly suggested,\n matrix = this.group.calcTransformMatrix();\n }\n this.forEachControl(function(control, key, fabricObject) {\n p = fabricObject.oCoords[key];\n if (control.getVisibility(fabricObject, key)) {\n if (matrix) {\n p = fabric.util.transformPoint(p, matrix);\n }\n control.render(ctx, p.x, p.y, styleOverride, fabricObject);\n }\n });\n ctx.restore();\n\n return this;\n },\n\n /**\n * Returns true if the specified control is visible, false otherwise.\n * @param {String} controlKey The key of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.\n * @returns {Boolean} true if the specified control is visible, false otherwise\n */\n isControlVisible: function(controlKey) {\n return this.controls[controlKey] && this.controls[controlKey].getVisibility(this, controlKey);\n },\n\n /**\n * Sets the visibility of the specified control.\n * @param {String} controlKey The key of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.\n * @param {Boolean} visible true to set the specified control visible, false otherwise\n * @return {fabric.Object} thisArg\n * @chainable\n */\n setControlVisible: function(controlKey, visible) {\n if (!this._controlsVisibility) {\n this._controlsVisibility = {};\n }\n this._controlsVisibility[controlKey] = visible;\n return this;\n },\n\n /**\n * Sets the visibility state of object controls.\n * @param {Object} [options] Options object\n * @param {Boolean} [options.bl] true to enable the bottom-left control, false to disable it\n * @param {Boolean} [options.br] true to enable the bottom-right control, false to disable it\n * @param {Boolean} [options.mb] true to enable the middle-bottom control, false to disable it\n * @param {Boolean} [options.ml] true to enable the middle-left control, false to disable it\n * @param {Boolean} [options.mr] true to enable the middle-right control, false to disable it\n * @param {Boolean} [options.mt] true to enable the middle-top control, false to disable it\n * @param {Boolean} [options.tl] true to enable the top-left control, false to disable it\n * @param {Boolean} [options.tr] true to enable the top-right control, false to disable it\n * @param {Boolean} [options.mtr] true to enable the middle-top-rotate control, false to disable it\n * @return {fabric.Object} thisArg\n * @chainable\n */\n setControlsVisibility: function(options) {\n options || (options = { });\n\n for (var p in options) {\n this.setControlVisible(p, options[p]);\n }\n return this;\n },\n\n\n /**\n * This callback function is called every time _discardActiveObject or _setActiveObject\n * try to to deselect this object. If the function returns true, the process is cancelled\n * @param {Object} [options] options sent from the upper functions\n * @param {Event} [options.e] event if the process is generated by an event\n */\n onDeselect: function() {\n // implemented by sub-classes, as needed.\n },\n\n\n /**\n * This callback function is called every time _discardActiveObject or _setActiveObject\n * try to to select this object. If the function returns true, the process is cancelled\n * @param {Object} [options] options sent from the upper functions\n * @param {Event} [options.e] event if the process is generated by an event\n */\n onSelect: function() {\n // implemented by sub-classes, as needed.\n }\n });\n})();\n\n\nfabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {\n\n /**\n * Animation duration (in ms) for fx* methods\n * @type Number\n * @default\n */\n FX_DURATION: 500,\n\n /**\n * Centers object horizontally with animation.\n * @param {fabric.Object} object Object to center\n * @param {Object} [callbacks] Callbacks object with optional \"onComplete\" and/or \"onChange\" properties\n * @param {Function} [callbacks.onComplete] Invoked on completion\n * @param {Function} [callbacks.onChange] Invoked on every step of animation\n * @return {fabric.AnimationContext} context\n */\n fxCenterObjectH: function (object, callbacks) {\n callbacks = callbacks || { };\n\n var empty = function() { },\n onComplete = callbacks.onComplete || empty,\n onChange = callbacks.onChange || empty,\n _this = this;\n\n return fabric.util.animate({\n target: this,\n startValue: object.left,\n endValue: this.getCenterPoint().x,\n duration: this.FX_DURATION,\n onChange: function(value) {\n object.set('left', value);\n _this.requestRenderAll();\n onChange();\n },\n onComplete: function() {\n object.setCoords();\n onComplete();\n }\n });\n },\n\n /**\n * Centers object vertically with animation.\n * @param {fabric.Object} object Object to center\n * @param {Object} [callbacks] Callbacks object with optional \"onComplete\" and/or \"onChange\" properties\n * @param {Function} [callbacks.onComplete] Invoked on completion\n * @param {Function} [callbacks.onChange] Invoked on every step of animation\n * @return {fabric.AnimationContext} context\n */\n fxCenterObjectV: function (object, callbacks) {\n callbacks = callbacks || { };\n\n var empty = function() { },\n onComplete = callbacks.onComplete || empty,\n onChange = callbacks.onChange || empty,\n _this = this;\n\n return fabric.util.animate({\n target: this,\n startValue: object.top,\n endValue: this.getCenterPoint().y,\n duration: this.FX_DURATION,\n onChange: function(value) {\n object.set('top', value);\n _this.requestRenderAll();\n onChange();\n },\n onComplete: function() {\n object.setCoords();\n onComplete();\n }\n });\n },\n\n /**\n * Same as `fabric.Canvas#remove` but animated\n * @param {fabric.Object} object Object to remove\n * @param {Object} [callbacks] Callbacks object with optional \"onComplete\" and/or \"onChange\" properties\n * @param {Function} [callbacks.onComplete] Invoked on completion\n * @param {Function} [callbacks.onChange] Invoked on every step of animation\n * @return {fabric.AnimationContext} context\n */\n fxRemove: function (object, callbacks) {\n callbacks = callbacks || { };\n\n var empty = function() { },\n onComplete = callbacks.onComplete || empty,\n onChange = callbacks.onChange || empty,\n _this = this;\n\n return fabric.util.animate({\n target: this,\n startValue: object.opacity,\n endValue: 0,\n duration: this.FX_DURATION,\n onChange: function(value) {\n object.set('opacity', value);\n _this.requestRenderAll();\n onChange();\n },\n onComplete: function () {\n _this.remove(object);\n onComplete();\n }\n });\n }\n});\n\nfabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {\n /**\n * Animates object's properties\n * @param {String|Object} property Property to animate (if string) or properties to animate (if object)\n * @param {Number|Object} value Value to animate property to (if string was given first) or options object\n * @return {fabric.Object} thisArg\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#animation}\n * @return {fabric.AnimationContext | fabric.AnimationContext[]} animation context (or an array if passed multiple properties)\n *\n * As object — multiple properties\n *\n * object.animate({ left: ..., top: ... });\n * object.animate({ left: ..., top: ... }, { duration: ... });\n *\n * As string — one property\n *\n * object.animate('left', ...);\n * object.animate('left', { duration: ... });\n *\n */\n animate: function () {\n if (arguments[0] && typeof arguments[0] === 'object') {\n var propsToAnimate = [], prop, skipCallbacks, out = [];\n for (prop in arguments[0]) {\n propsToAnimate.push(prop);\n }\n for (var i = 0, len = propsToAnimate.length; i < len; i++) {\n prop = propsToAnimate[i];\n skipCallbacks = i !== len - 1;\n out.push(this._animate(prop, arguments[0][prop], arguments[1], skipCallbacks));\n }\n return out;\n }\n else {\n return this._animate.apply(this, arguments);\n }\n },\n\n /**\n * @private\n * @param {String} property Property to animate\n * @param {String} to Value to animate to\n * @param {Object} [options] Options object\n * @param {Boolean} [skipCallbacks] When true, callbacks like onchange and oncomplete are not invoked\n */\n _animate: function(property, to, options, skipCallbacks) {\n var _this = this, propPair;\n\n to = to.toString();\n\n if (!options) {\n options = { };\n }\n else {\n options = fabric.util.object.clone(options);\n }\n\n if (~property.indexOf('.')) {\n propPair = property.split('.');\n }\n\n var propIsColor =\n _this.colorProperties.indexOf(property) > -1 ||\n (propPair && _this.colorProperties.indexOf(propPair[1]) > -1);\n\n var currentValue = propPair\n ? this.get(propPair[0])[propPair[1]]\n : this.get(property);\n\n if (!('from' in options)) {\n options.from = currentValue;\n }\n\n if (!propIsColor) {\n if (~to.indexOf('=')) {\n to = currentValue + parseFloat(to.replace('=', ''));\n }\n else {\n to = parseFloat(to);\n }\n }\n\n var _options = {\n target: this,\n startValue: options.from,\n endValue: to,\n byValue: options.by,\n easing: options.easing,\n duration: options.duration,\n abort: options.abort && function(value, valueProgress, timeProgress) {\n return options.abort.call(_this, value, valueProgress, timeProgress);\n },\n onChange: function (value, valueProgress, timeProgress) {\n if (propPair) {\n _this[propPair[0]][propPair[1]] = value;\n }\n else {\n _this.set(property, value);\n }\n if (skipCallbacks) {\n return;\n }\n options.onChange && options.onChange(value, valueProgress, timeProgress);\n },\n onComplete: function (value, valueProgress, timeProgress) {\n if (skipCallbacks) {\n return;\n }\n\n _this.setCoords();\n options.onComplete && options.onComplete(value, valueProgress, timeProgress);\n }\n };\n\n if (propIsColor) {\n return fabric.util.animateColor(_options.startValue, _options.endValue, _options.duration, _options);\n }\n else {\n return fabric.util.animate(_options);\n }\n }\n});\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n extend = fabric.util.object.extend,\n clone = fabric.util.object.clone,\n coordProps = { x1: 1, x2: 1, y1: 1, y2: 1 };\n\n if (fabric.Line) {\n fabric.warn('fabric.Line is already defined');\n return;\n }\n\n /**\n * Line class\n * @class fabric.Line\n * @extends fabric.Object\n * @see {@link fabric.Line#initialize} for constructor definition\n */\n fabric.Line = fabric.util.createClass(fabric.Object, /** @lends fabric.Line.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'line',\n\n /**\n * x value or first line edge\n * @type Number\n * @default\n */\n x1: 0,\n\n /**\n * y value or first line edge\n * @type Number\n * @default\n */\n y1: 0,\n\n /**\n * x value or second line edge\n * @type Number\n * @default\n */\n x2: 0,\n\n /**\n * y value or second line edge\n * @type Number\n * @default\n */\n y2: 0,\n\n cacheProperties: fabric.Object.prototype.cacheProperties.concat('x1', 'x2', 'y1', 'y2'),\n\n /**\n * Constructor\n * @param {Array} [points] Array of points\n * @param {Object} [options] Options object\n * @return {fabric.Line} thisArg\n */\n initialize: function(points, options) {\n if (!points) {\n points = [0, 0, 0, 0];\n }\n\n this.callSuper('initialize', options);\n\n this.set('x1', points[0]);\n this.set('y1', points[1]);\n this.set('x2', points[2]);\n this.set('y2', points[3]);\n\n this._setWidthHeight(options);\n },\n\n /**\n * @private\n * @param {Object} [options] Options\n */\n _setWidthHeight: function(options) {\n options || (options = { });\n\n this.width = Math.abs(this.x2 - this.x1);\n this.height = Math.abs(this.y2 - this.y1);\n\n this.left = 'left' in options\n ? options.left\n : this._getLeftToOriginX();\n\n this.top = 'top' in options\n ? options.top\n : this._getTopToOriginY();\n },\n\n /**\n * @private\n * @param {String} key\n * @param {*} value\n */\n _set: function(key, value) {\n this.callSuper('_set', key, value);\n if (typeof coordProps[key] !== 'undefined') {\n this._setWidthHeight();\n }\n return this;\n },\n\n /**\n * @private\n * @return {Number} leftToOriginX Distance from left edge of canvas to originX of Line.\n */\n _getLeftToOriginX: makeEdgeToOriginGetter(\n { // property names\n origin: 'originX',\n axis1: 'x1',\n axis2: 'x2',\n dimension: 'width'\n },\n { // possible values of origin\n nearest: 'left',\n center: 'center',\n farthest: 'right'\n }\n ),\n\n /**\n * @private\n * @return {Number} topToOriginY Distance from top edge of canvas to originY of Line.\n */\n _getTopToOriginY: makeEdgeToOriginGetter(\n { // property names\n origin: 'originY',\n axis1: 'y1',\n axis2: 'y2',\n dimension: 'height'\n },\n { // possible values of origin\n nearest: 'top',\n center: 'center',\n farthest: 'bottom'\n }\n ),\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(ctx) {\n ctx.beginPath();\n\n\n var p = this.calcLinePoints();\n ctx.moveTo(p.x1, p.y1);\n ctx.lineTo(p.x2, p.y2);\n\n ctx.lineWidth = this.strokeWidth;\n\n // TODO: test this\n // make sure setting \"fill\" changes color of a line\n // (by copying fillStyle to strokeStyle, since line is stroked, not filled)\n var origStrokeStyle = ctx.strokeStyle;\n ctx.strokeStyle = this.stroke || ctx.fillStyle;\n this.stroke && this._renderStroke(ctx);\n ctx.strokeStyle = origStrokeStyle;\n },\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates\n * @private\n * @return {Object} center point from element coordinates\n */\n _findCenterFromElement: function() {\n return {\n x: (this.x1 + this.x2) / 2,\n y: (this.y1 + this.y2) / 2,\n };\n },\n\n /**\n * Returns object representation of an instance\n * @method toObject\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n return extend(this.callSuper('toObject', propertiesToInclude), this.calcLinePoints());\n },\n\n /*\n * Calculate object dimensions from its properties\n * @private\n */\n _getNonTransformedDimensions: function() {\n var dim = this.callSuper('_getNonTransformedDimensions');\n if (this.strokeLineCap === 'butt') {\n if (this.width === 0) {\n dim.y -= this.strokeWidth;\n }\n if (this.height === 0) {\n dim.x -= this.strokeWidth;\n }\n }\n return dim;\n },\n\n /**\n * Recalculates line points given width and height\n * @private\n */\n calcLinePoints: function() {\n var xMult = this.x1 <= this.x2 ? -1 : 1,\n yMult = this.y1 <= this.y2 ? -1 : 1,\n x1 = (xMult * this.width * 0.5),\n y1 = (yMult * this.height * 0.5),\n x2 = (xMult * this.width * -0.5),\n y2 = (yMult * this.height * -0.5);\n\n return {\n x1: x1,\n x2: x2,\n y1: y1,\n y2: y2\n };\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG: function() {\n var p = this.calcLinePoints();\n return [\n '\\n'\n ];\n },\n /* _TO_SVG_END_ */\n });\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link fabric.Line.fromElement})\n * @static\n * @memberOf fabric.Line\n * @see http://www.w3.org/TR/SVG/shapes.html#LineElement\n */\n fabric.Line.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x1 y1 x2 y2'.split(' '));\n\n /**\n * Returns fabric.Line instance from an SVG element\n * @static\n * @memberOf fabric.Line\n * @param {SVGElement} element Element to parse\n * @param {Object} [options] Options object\n * @param {Function} [callback] callback function invoked after parsing\n */\n fabric.Line.fromElement = function(element, callback, options) {\n options = options || { };\n var parsedAttributes = fabric.parseAttributes(element, fabric.Line.ATTRIBUTE_NAMES),\n points = [\n parsedAttributes.x1 || 0,\n parsedAttributes.y1 || 0,\n parsedAttributes.x2 || 0,\n parsedAttributes.y2 || 0\n ];\n callback(new fabric.Line(points, extend(parsedAttributes, options)));\n };\n /* _FROM_SVG_END_ */\n\n /**\n * Returns fabric.Line instance from an object representation\n * @static\n * @memberOf fabric.Line\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] invoked with new instance as first argument\n */\n fabric.Line.fromObject = function(object, callback) {\n function _callback(instance) {\n delete instance.points;\n callback && callback(instance);\n };\n var options = clone(object, true);\n options.points = [object.x1, object.y1, object.x2, object.y2];\n fabric.Object._fromObject('Line', options, _callback, 'points');\n };\n\n /**\n * Produces a function that calculates distance from canvas edge to Line origin.\n */\n function makeEdgeToOriginGetter(propertyNames, originValues) {\n var origin = propertyNames.origin,\n axis1 = propertyNames.axis1,\n axis2 = propertyNames.axis2,\n dimension = propertyNames.dimension,\n nearest = originValues.nearest,\n center = originValues.center,\n farthest = originValues.farthest;\n\n return function() {\n switch (this.get(origin)) {\n case nearest:\n return Math.min(this.get(axis1), this.get(axis2));\n case center:\n return Math.min(this.get(axis1), this.get(axis2)) + (0.5 * this.get(dimension));\n case farthest:\n return Math.max(this.get(axis1), this.get(axis2));\n }\n };\n\n }\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n degreesToRadians = fabric.util.degreesToRadians;\n\n if (fabric.Circle) {\n fabric.warn('fabric.Circle is already defined.');\n return;\n }\n\n /**\n * Circle class\n * @class fabric.Circle\n * @extends fabric.Object\n * @see {@link fabric.Circle#initialize} for constructor definition\n */\n fabric.Circle = fabric.util.createClass(fabric.Object, /** @lends fabric.Circle.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'circle',\n\n /**\n * Radius of this circle\n * @type Number\n * @default\n */\n radius: 0,\n\n /**\n * degrees of start of the circle.\n * probably will change to degrees in next major version\n * @type Number 0 - 359\n * @default 0\n */\n startAngle: 0,\n\n /**\n * End angle of the circle\n * probably will change to degrees in next major version\n * @type Number 1 - 360\n * @default 360\n */\n endAngle: 360,\n\n cacheProperties: fabric.Object.prototype.cacheProperties.concat('radius', 'startAngle', 'endAngle'),\n\n /**\n * @private\n * @param {String} key\n * @param {*} value\n * @return {fabric.Circle} thisArg\n */\n _set: function(key, value) {\n this.callSuper('_set', key, value);\n\n if (key === 'radius') {\n this.setRadius(value);\n }\n\n return this;\n },\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n return this.callSuper('toObject', ['radius', 'startAngle', 'endAngle'].concat(propertiesToInclude));\n },\n\n /* _TO_SVG_START_ */\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG: function() {\n var svgString, x = 0, y = 0,\n angle = (this.endAngle - this.startAngle) % 360;\n\n if (angle === 0) {\n svgString = [\n '\\n'\n ];\n }\n else {\n var start = degreesToRadians(this.startAngle),\n end = degreesToRadians(this.endAngle),\n radius = this.radius,\n startX = fabric.util.cos(start) * radius,\n startY = fabric.util.sin(start) * radius,\n endX = fabric.util.cos(end) * radius,\n endY = fabric.util.sin(end) * radius,\n largeFlag = angle > 180 ? '1' : '0';\n svgString = [\n '\\n'\n ];\n }\n return svgString;\n },\n /* _TO_SVG_END_ */\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render on\n */\n _render: function(ctx) {\n ctx.beginPath();\n ctx.arc(\n 0,\n 0,\n this.radius,\n degreesToRadians(this.startAngle),\n degreesToRadians(this.endAngle),\n false\n );\n this._renderPaintInOrder(ctx);\n },\n\n /**\n * Returns horizontal radius of an object (according to how an object is scaled)\n * @return {Number}\n */\n getRadiusX: function() {\n return this.get('radius') * this.get('scaleX');\n },\n\n /**\n * Returns vertical radius of an object (according to how an object is scaled)\n * @return {Number}\n */\n getRadiusY: function() {\n return this.get('radius') * this.get('scaleY');\n },\n\n /**\n * Sets radius of an object (and updates width accordingly)\n * @return {fabric.Circle} thisArg\n */\n setRadius: function(value) {\n this.radius = value;\n return this.set('width', value * 2).set('height', value * 2);\n },\n });\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement})\n * @static\n * @memberOf fabric.Circle\n * @see: http://www.w3.org/TR/SVG/shapes.html#CircleElement\n */\n fabric.Circle.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('cx cy r'.split(' '));\n\n /**\n * Returns {@link fabric.Circle} instance from an SVG element\n * @static\n * @memberOf fabric.Circle\n * @param {SVGElement} element Element to parse\n * @param {Function} [callback] Options callback invoked after parsing is finished\n * @param {Object} [options] Options object\n * @throws {Error} If value of `r` attribute is missing or invalid\n */\n fabric.Circle.fromElement = function(element, callback) {\n var parsedAttributes = fabric.parseAttributes(element, fabric.Circle.ATTRIBUTE_NAMES);\n\n if (!isValidRadius(parsedAttributes)) {\n throw new Error('value of `r` attribute is required and can not be negative');\n }\n\n parsedAttributes.left = (parsedAttributes.left || 0) - parsedAttributes.radius;\n parsedAttributes.top = (parsedAttributes.top || 0) - parsedAttributes.radius;\n callback(new fabric.Circle(parsedAttributes));\n };\n\n /**\n * @private\n */\n function isValidRadius(attributes) {\n return (('radius' in attributes) && (attributes.radius >= 0));\n }\n /* _FROM_SVG_END_ */\n\n /**\n * Returns {@link fabric.Circle} instance from an object representation\n * @static\n * @memberOf fabric.Circle\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] invoked with new instance as first argument\n * @return {void}\n */\n fabric.Circle.fromObject = function(object, callback) {\n fabric.Object._fromObject('Circle', object, callback);\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { });\n\n if (fabric.Triangle) {\n fabric.warn('fabric.Triangle is already defined');\n return;\n }\n\n /**\n * Triangle class\n * @class fabric.Triangle\n * @extends fabric.Object\n * @return {fabric.Triangle} thisArg\n * @see {@link fabric.Triangle#initialize} for constructor definition\n */\n fabric.Triangle = fabric.util.createClass(fabric.Object, /** @lends fabric.Triangle.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'triangle',\n\n /**\n * Width is set to 100 to compensate the old initialize code that was setting it to 100\n * @type Number\n * @default\n */\n width: 100,\n\n /**\n * Height is set to 100 to compensate the old initialize code that was setting it to 100\n * @type Number\n * @default\n */\n height: 100,\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(ctx) {\n var widthBy2 = this.width / 2,\n heightBy2 = this.height / 2;\n\n ctx.beginPath();\n ctx.moveTo(-widthBy2, heightBy2);\n ctx.lineTo(0, -heightBy2);\n ctx.lineTo(widthBy2, heightBy2);\n ctx.closePath();\n\n this._renderPaintInOrder(ctx);\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG: function() {\n var widthBy2 = this.width / 2,\n heightBy2 = this.height / 2,\n points = [\n -widthBy2 + ' ' + heightBy2,\n '0 ' + -heightBy2,\n widthBy2 + ' ' + heightBy2\n ].join(',');\n return [\n ''\n ];\n },\n /* _TO_SVG_END_ */\n });\n\n /**\n * Returns {@link fabric.Triangle} instance from an object representation\n * @static\n * @memberOf fabric.Triangle\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] invoked with new instance as first argument\n */\n fabric.Triangle.fromObject = function(object, callback) {\n return fabric.Object._fromObject('Triangle', object, callback);\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n piBy2 = Math.PI * 2;\n\n if (fabric.Ellipse) {\n fabric.warn('fabric.Ellipse is already defined.');\n return;\n }\n\n /**\n * Ellipse class\n * @class fabric.Ellipse\n * @extends fabric.Object\n * @return {fabric.Ellipse} thisArg\n * @see {@link fabric.Ellipse#initialize} for constructor definition\n */\n fabric.Ellipse = fabric.util.createClass(fabric.Object, /** @lends fabric.Ellipse.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'ellipse',\n\n /**\n * Horizontal radius\n * @type Number\n * @default\n */\n rx: 0,\n\n /**\n * Vertical radius\n * @type Number\n * @default\n */\n ry: 0,\n\n cacheProperties: fabric.Object.prototype.cacheProperties.concat('rx', 'ry'),\n\n /**\n * Constructor\n * @param {Object} [options] Options object\n * @return {fabric.Ellipse} thisArg\n */\n initialize: function(options) {\n this.callSuper('initialize', options);\n this.set('rx', options && options.rx || 0);\n this.set('ry', options && options.ry || 0);\n },\n\n /**\n * @private\n * @param {String} key\n * @param {*} value\n * @return {fabric.Ellipse} thisArg\n */\n _set: function(key, value) {\n this.callSuper('_set', key, value);\n switch (key) {\n\n case 'rx':\n this.rx = value;\n this.set('width', value * 2);\n break;\n\n case 'ry':\n this.ry = value;\n this.set('height', value * 2);\n break;\n\n }\n return this;\n },\n\n /**\n * Returns horizontal radius of an object (according to how an object is scaled)\n * @return {Number}\n */\n getRx: function() {\n return this.get('rx') * this.get('scaleX');\n },\n\n /**\n * Returns Vertical radius of an object (according to how an object is scaled)\n * @return {Number}\n */\n getRy: function() {\n return this.get('ry') * this.get('scaleY');\n },\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n return this.callSuper('toObject', ['rx', 'ry'].concat(propertiesToInclude));\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG: function() {\n return [\n '\\n'\n ];\n },\n /* _TO_SVG_END_ */\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render on\n */\n _render: function(ctx) {\n ctx.beginPath();\n ctx.save();\n ctx.transform(1, 0, 0, this.ry / this.rx, 0, 0);\n ctx.arc(\n 0,\n 0,\n this.rx,\n 0,\n piBy2,\n false);\n ctx.restore();\n this._renderPaintInOrder(ctx);\n },\n });\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement})\n * @static\n * @memberOf fabric.Ellipse\n * @see http://www.w3.org/TR/SVG/shapes.html#EllipseElement\n */\n fabric.Ellipse.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('cx cy rx ry'.split(' '));\n\n /**\n * Returns {@link fabric.Ellipse} instance from an SVG element\n * @static\n * @memberOf fabric.Ellipse\n * @param {SVGElement} element Element to parse\n * @param {Function} [callback] Options callback invoked after parsing is finished\n * @return {fabric.Ellipse}\n */\n fabric.Ellipse.fromElement = function(element, callback) {\n\n var parsedAttributes = fabric.parseAttributes(element, fabric.Ellipse.ATTRIBUTE_NAMES);\n\n parsedAttributes.left = (parsedAttributes.left || 0) - parsedAttributes.rx;\n parsedAttributes.top = (parsedAttributes.top || 0) - parsedAttributes.ry;\n callback(new fabric.Ellipse(parsedAttributes));\n };\n /* _FROM_SVG_END_ */\n\n /**\n * Returns {@link fabric.Ellipse} instance from an object representation\n * @static\n * @memberOf fabric.Ellipse\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] invoked with new instance as first argument\n * @return {void}\n */\n fabric.Ellipse.fromObject = function(object, callback) {\n fabric.Object._fromObject('Ellipse', object, callback);\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n extend = fabric.util.object.extend;\n\n if (fabric.Rect) {\n fabric.warn('fabric.Rect is already defined');\n return;\n }\n\n /**\n * Rectangle class\n * @class fabric.Rect\n * @extends fabric.Object\n * @return {fabric.Rect} thisArg\n * @see {@link fabric.Rect#initialize} for constructor definition\n */\n fabric.Rect = fabric.util.createClass(fabric.Object, /** @lends fabric.Rect.prototype */ {\n\n /**\n * List of properties to consider when checking if state of an object is changed ({@link fabric.Object#hasStateChanged})\n * as well as for history (undo/redo) purposes\n * @type Array\n */\n stateProperties: fabric.Object.prototype.stateProperties.concat('rx', 'ry'),\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'rect',\n\n /**\n * Horizontal border radius\n * @type Number\n * @default\n */\n rx: 0,\n\n /**\n * Vertical border radius\n * @type Number\n * @default\n */\n ry: 0,\n\n cacheProperties: fabric.Object.prototype.cacheProperties.concat('rx', 'ry'),\n\n /**\n * Constructor\n * @param {Object} [options] Options object\n * @return {Object} thisArg\n */\n initialize: function(options) {\n this.callSuper('initialize', options);\n this._initRxRy();\n },\n\n /**\n * Initializes rx/ry attributes\n * @private\n */\n _initRxRy: function() {\n if (this.rx && !this.ry) {\n this.ry = this.rx;\n }\n else if (this.ry && !this.rx) {\n this.rx = this.ry;\n }\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(ctx) {\n\n // 1x1 case (used in spray brush) optimization was removed because\n // with caching and higher zoom level this makes more damage than help\n\n var rx = this.rx ? Math.min(this.rx, this.width / 2) : 0,\n ry = this.ry ? Math.min(this.ry, this.height / 2) : 0,\n w = this.width,\n h = this.height,\n x = -this.width / 2,\n y = -this.height / 2,\n isRounded = rx !== 0 || ry !== 0,\n /* \"magic number\" for bezier approximations of arcs (http://itc.ktu.lt/itc354/Riskus354.pdf) */\n k = 1 - 0.5522847498;\n ctx.beginPath();\n\n ctx.moveTo(x + rx, y);\n\n ctx.lineTo(x + w - rx, y);\n isRounded && ctx.bezierCurveTo(x + w - k * rx, y, x + w, y + k * ry, x + w, y + ry);\n\n ctx.lineTo(x + w, y + h - ry);\n isRounded && ctx.bezierCurveTo(x + w, y + h - k * ry, x + w - k * rx, y + h, x + w - rx, y + h);\n\n ctx.lineTo(x + rx, y + h);\n isRounded && ctx.bezierCurveTo(x + k * rx, y + h, x, y + h - k * ry, x, y + h - ry);\n\n ctx.lineTo(x, y + ry);\n isRounded && ctx.bezierCurveTo(x, y + k * ry, x + k * rx, y, x + rx, y);\n\n ctx.closePath();\n\n this._renderPaintInOrder(ctx);\n },\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n return this.callSuper('toObject', ['rx', 'ry'].concat(propertiesToInclude));\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG: function() {\n var x = -this.width / 2, y = -this.height / 2;\n return [\n '\\n'\n ];\n },\n /* _TO_SVG_END_ */\n });\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`)\n * @static\n * @memberOf fabric.Rect\n * @see: http://www.w3.org/TR/SVG/shapes.html#RectElement\n */\n fabric.Rect.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x y rx ry width height'.split(' '));\n\n /**\n * Returns {@link fabric.Rect} instance from an SVG element\n * @static\n * @memberOf fabric.Rect\n * @param {SVGElement} element Element to parse\n * @param {Function} callback callback function invoked after parsing\n * @param {Object} [options] Options object\n */\n fabric.Rect.fromElement = function(element, callback, options) {\n if (!element) {\n return callback(null);\n }\n options = options || { };\n\n var parsedAttributes = fabric.parseAttributes(element, fabric.Rect.ATTRIBUTE_NAMES);\n parsedAttributes.left = parsedAttributes.left || 0;\n parsedAttributes.top = parsedAttributes.top || 0;\n parsedAttributes.height = parsedAttributes.height || 0;\n parsedAttributes.width = parsedAttributes.width || 0;\n var rect = new fabric.Rect(extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes));\n rect.visible = rect.visible && rect.width > 0 && rect.height > 0;\n callback(rect);\n };\n /* _FROM_SVG_END_ */\n\n /**\n * Returns {@link fabric.Rect} instance from an object representation\n * @static\n * @memberOf fabric.Rect\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] Callback to invoke when an fabric.Rect instance is created\n */\n fabric.Rect.fromObject = function(object, callback) {\n return fabric.Object._fromObject('Rect', object, callback);\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n extend = fabric.util.object.extend,\n min = fabric.util.array.min,\n max = fabric.util.array.max,\n toFixed = fabric.util.toFixed,\n projectStrokeOnPoints = fabric.util.projectStrokeOnPoints;\n\n if (fabric.Polyline) {\n fabric.warn('fabric.Polyline is already defined');\n return;\n }\n\n /**\n * Polyline class\n * @class fabric.Polyline\n * @extends fabric.Object\n * @see {@link fabric.Polyline#initialize} for constructor definition\n */\n fabric.Polyline = fabric.util.createClass(fabric.Object, /** @lends fabric.Polyline.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'polyline',\n\n /**\n * Points array\n * @type Array\n * @default\n */\n points: null,\n\n /**\n * WARNING: Feature in progress\n * Calculate the exact bounding box taking in account strokeWidth on acute angles\n * this will be turned to true by default on fabric 6.0\n * maybe will be left in as an optimization since calculations may be slow\n * @deprecated\n * @type Boolean\n * @default false\n */\n exactBoundingBox: false,\n\n cacheProperties: fabric.Object.prototype.cacheProperties.concat('points'),\n\n /**\n * Constructor\n * @param {Array} points Array of points (where each point is an object with x and y)\n * @param {Object} [options] Options object\n * @return {fabric.Polyline} thisArg\n * @example\n * var poly = new fabric.Polyline([\n * { x: 10, y: 10 },\n * { x: 50, y: 30 },\n * { x: 40, y: 70 },\n * { x: 60, y: 50 },\n * { x: 100, y: 150 },\n * { x: 40, y: 100 }\n * ], {\n * stroke: 'red',\n * left: 100,\n * top: 100\n * });\n */\n initialize: function(points, options) {\n options = options || {};\n this.points = points || [];\n this.callSuper('initialize', options);\n this._setPositionDimensions(options);\n },\n\n /**\n * @private\n */\n _projectStrokeOnPoints: function () {\n return projectStrokeOnPoints(this.points, this, true);\n },\n\n _setPositionDimensions: function(options) {\n var calcDim = this._calcDimensions(options), correctLeftTop,\n correctSize = this.exactBoundingBox ? this.strokeWidth : 0;\n this.width = calcDim.width - correctSize;\n this.height = calcDim.height - correctSize;\n if (!options.fromSVG) {\n correctLeftTop = this.translateToGivenOrigin(\n {\n // this looks bad, but is one way to keep it optional for now.\n x: calcDim.left - this.strokeWidth / 2 + correctSize / 2,\n y: calcDim.top - this.strokeWidth / 2 + correctSize / 2\n },\n 'left',\n 'top',\n this.originX,\n this.originY\n );\n }\n if (typeof options.left === 'undefined') {\n this.left = options.fromSVG ? calcDim.left : correctLeftTop.x;\n }\n if (typeof options.top === 'undefined') {\n this.top = options.fromSVG ? calcDim.top : correctLeftTop.y;\n }\n this.pathOffset = {\n x: calcDim.left + this.width / 2 + correctSize / 2,\n y: calcDim.top + this.height / 2 + correctSize / 2\n };\n },\n\n /**\n * Calculate the polygon min and max point from points array,\n * returning an object with left, top, width, height to measure the\n * polygon size\n * @return {Object} object.left X coordinate of the polygon leftmost point\n * @return {Object} object.top Y coordinate of the polygon topmost point\n * @return {Object} object.width distance between X coordinates of the polygon leftmost and rightmost point\n * @return {Object} object.height distance between Y coordinates of the polygon topmost and bottommost point\n * @private\n */\n _calcDimensions: function() {\n\n var points = this.exactBoundingBox ? this._projectStrokeOnPoints() : this.points,\n minX = min(points, 'x') || 0,\n minY = min(points, 'y') || 0,\n maxX = max(points, 'x') || 0,\n maxY = max(points, 'y') || 0,\n width = (maxX - minX),\n height = (maxY - minY);\n\n return {\n left: minX,\n top: minY,\n width: width,\n height: height,\n };\n },\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} Object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n return extend(this.callSuper('toObject', propertiesToInclude), {\n points: this.points.concat()\n });\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG: function() {\n var points = [], diffX = this.pathOffset.x, diffY = this.pathOffset.y,\n NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;\n\n for (var i = 0, len = this.points.length; i < len; i++) {\n points.push(\n toFixed(this.points[i].x - diffX, NUM_FRACTION_DIGITS), ',',\n toFixed(this.points[i].y - diffY, NUM_FRACTION_DIGITS), ' '\n );\n }\n return [\n '<' + this.type + ' ', 'COMMON_PARTS',\n 'points=\"', points.join(''),\n '\" />\\n'\n ];\n },\n /* _TO_SVG_END_ */\n\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n commonRender: function(ctx) {\n var point, len = this.points.length,\n x = this.pathOffset.x,\n y = this.pathOffset.y;\n\n if (!len || isNaN(this.points[len - 1].y)) {\n // do not draw if no points or odd points\n // NaN comes from parseFloat of a empty string in parser\n return false;\n }\n ctx.beginPath();\n ctx.moveTo(this.points[0].x - x, this.points[0].y - y);\n for (var i = 0; i < len; i++) {\n point = this.points[i];\n ctx.lineTo(point.x - x, point.y - y);\n }\n return true;\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(ctx) {\n if (!this.commonRender(ctx)) {\n return;\n }\n this._renderPaintInOrder(ctx);\n },\n\n /**\n * Returns complexity of an instance\n * @return {Number} complexity of this instance\n */\n complexity: function() {\n return this.get('points').length;\n }\n });\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link fabric.Polyline.fromElement})\n * @static\n * @memberOf fabric.Polyline\n * @see: http://www.w3.org/TR/SVG/shapes.html#PolylineElement\n */\n fabric.Polyline.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat();\n\n /**\n * Returns fabric.Polyline instance from an SVG element\n * @static\n * @memberOf fabric.Polyline\n * @param {SVGElement} element Element to parser\n * @param {Function} callback callback function invoked after parsing\n * @param {Object} [options] Options object\n */\n fabric.Polyline.fromElementGenerator = function(_class) {\n return function(element, callback, options) {\n if (!element) {\n return callback(null);\n }\n options || (options = { });\n\n var points = fabric.parsePointsAttribute(element.getAttribute('points')),\n parsedAttributes = fabric.parseAttributes(element, fabric[_class].ATTRIBUTE_NAMES);\n parsedAttributes.fromSVG = true;\n callback(new fabric[_class](points, extend(parsedAttributes, options)));\n };\n };\n\n fabric.Polyline.fromElement = fabric.Polyline.fromElementGenerator('Polyline');\n\n /* _FROM_SVG_END_ */\n\n /**\n * Returns fabric.Polyline instance from an object representation\n * @static\n * @memberOf fabric.Polyline\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created\n */\n fabric.Polyline.fromObject = function(object, callback) {\n return fabric.Object._fromObject('Polyline', object, callback, 'points');\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = {}),\n projectStrokeOnPoints = fabric.util.projectStrokeOnPoints;\n\n if (fabric.Polygon) {\n fabric.warn('fabric.Polygon is already defined');\n return;\n }\n\n /**\n * Polygon class\n * @class fabric.Polygon\n * @extends fabric.Polyline\n * @see {@link fabric.Polygon#initialize} for constructor definition\n */\n fabric.Polygon = fabric.util.createClass(fabric.Polyline, /** @lends fabric.Polygon.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'polygon',\n\n /**\n * @private\n */\n _projectStrokeOnPoints: function () {\n return projectStrokeOnPoints(this.points, this);\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(ctx) {\n if (!this.commonRender(ctx)) {\n return;\n }\n ctx.closePath();\n this._renderPaintInOrder(ctx);\n },\n\n });\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`)\n * @static\n * @memberOf fabric.Polygon\n * @see: http://www.w3.org/TR/SVG/shapes.html#PolygonElement\n */\n fabric.Polygon.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat();\n\n /**\n * Returns {@link fabric.Polygon} instance from an SVG element\n * @static\n * @memberOf fabric.Polygon\n * @param {SVGElement} element Element to parse\n * @param {Function} callback callback function invoked after parsing\n * @param {Object} [options] Options object\n */\n fabric.Polygon.fromElement = fabric.Polyline.fromElementGenerator('Polygon');\n /* _FROM_SVG_END_ */\n\n /**\n * Returns fabric.Polygon instance from an object representation\n * @static\n * @memberOf fabric.Polygon\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created\n * @return {void}\n */\n fabric.Polygon.fromObject = function(object, callback) {\n fabric.Object._fromObject('Polygon', object, callback, 'points');\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n min = fabric.util.array.min,\n max = fabric.util.array.max,\n extend = fabric.util.object.extend,\n clone = fabric.util.object.clone,\n toFixed = fabric.util.toFixed;\n\n if (fabric.Path) {\n fabric.warn('fabric.Path is already defined');\n return;\n }\n\n /**\n * Path class\n * @class fabric.Path\n * @extends fabric.Object\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#path_and_pathgroup}\n * @see {@link fabric.Path#initialize} for constructor definition\n */\n fabric.Path = fabric.util.createClass(fabric.Object, /** @lends fabric.Path.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'path',\n\n /**\n * Array of path points\n * @type Array\n * @default\n */\n path: null,\n\n cacheProperties: fabric.Object.prototype.cacheProperties.concat('path', 'fillRule'),\n\n stateProperties: fabric.Object.prototype.stateProperties.concat('path'),\n\n /**\n * Constructor\n * @param {Array|String} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {Object} [options] Options object\n * @return {fabric.Path} thisArg\n */\n initialize: function (path, options) {\n options = clone(options || {});\n delete options.path;\n this.callSuper('initialize', options);\n this._setPath(path || [], options);\n },\n\n /**\n * @private\n * @param {Array|String} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {Object} [options] Options object\n */\n _setPath: function (path, options) {\n this.path = fabric.util.makePathSimpler(\n Array.isArray(path) ? path : fabric.util.parsePath(path)\n );\n\n fabric.Polyline.prototype._setPositionDimensions.call(this, options || {});\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _renderPathCommands: function(ctx) {\n var current, // current instruction\n subpathStartX = 0,\n subpathStartY = 0,\n x = 0, // current x\n y = 0, // current y\n controlX = 0, // current control point x\n controlY = 0, // current control point y\n l = -this.pathOffset.x,\n t = -this.pathOffset.y;\n\n ctx.beginPath();\n\n for (var i = 0, len = this.path.length; i < len; ++i) {\n\n current = this.path[i];\n\n switch (current[0]) { // first letter\n\n case 'L': // lineto, absolute\n x = current[1];\n y = current[2];\n ctx.lineTo(x + l, y + t);\n break;\n\n case 'M': // moveTo, absolute\n x = current[1];\n y = current[2];\n subpathStartX = x;\n subpathStartY = y;\n ctx.moveTo(x + l, y + t);\n break;\n\n case 'C': // bezierCurveTo, absolute\n x = current[5];\n y = current[6];\n controlX = current[3];\n controlY = current[4];\n ctx.bezierCurveTo(\n current[1] + l,\n current[2] + t,\n controlX + l,\n controlY + t,\n x + l,\n y + t\n );\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n ctx.quadraticCurveTo(\n current[1] + l,\n current[2] + t,\n current[3] + l,\n current[4] + t\n );\n x = current[3];\n y = current[4];\n controlX = current[1];\n controlY = current[2];\n break;\n\n case 'z':\n case 'Z':\n x = subpathStartX;\n y = subpathStartY;\n ctx.closePath();\n break;\n }\n }\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _render: function(ctx) {\n this._renderPathCommands(ctx);\n this._renderPaintInOrder(ctx);\n },\n\n /**\n * Returns string representation of an instance\n * @return {String} string representation of an instance\n */\n toString: function() {\n return '#';\n },\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n return extend(this.callSuper('toObject', propertiesToInclude), {\n path: this.path.map(function(item) { return item.slice(); }),\n });\n },\n\n /**\n * Returns dataless object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toDatalessObject: function(propertiesToInclude) {\n var o = this.toObject(['sourcePath'].concat(propertiesToInclude));\n if (o.sourcePath) {\n delete o.path;\n }\n return o;\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG: function() {\n var path = fabric.util.joinPath(this.path);\n return [\n '\\n'\n ];\n },\n\n _getOffsetTransform: function() {\n var digits = fabric.Object.NUM_FRACTION_DIGITS;\n return ' translate(' + toFixed(-this.pathOffset.x, digits) + ', ' +\n toFixed(-this.pathOffset.y, digits) + ')';\n },\n\n /**\n * Returns svg clipPath representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {String} svg representation of an instance\n */\n toClipPathSVG: function(reviver) {\n var additionalTransform = this._getOffsetTransform();\n return '\\t' + this._createBaseClipPathSVGMarkup(\n this._toSVG(), { reviver: reviver, additionalTransform: additionalTransform }\n );\n },\n\n /**\n * Returns svg representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {String} svg representation of an instance\n */\n toSVG: function(reviver) {\n var additionalTransform = this._getOffsetTransform();\n return this._createBaseSVGMarkup(this._toSVG(), { reviver: reviver, additionalTransform: additionalTransform });\n },\n /* _TO_SVG_END_ */\n\n /**\n * Returns number representation of an instance complexity\n * @return {Number} complexity of this instance\n */\n complexity: function() {\n return this.path.length;\n },\n\n /**\n * @private\n */\n _calcDimensions: function() {\n\n var aX = [],\n aY = [],\n current, // current instruction\n subpathStartX = 0,\n subpathStartY = 0,\n x = 0, // current x\n y = 0, // current y\n bounds;\n\n for (var i = 0, len = this.path.length; i < len; ++i) {\n\n current = this.path[i];\n\n switch (current[0]) { // first letter\n\n case 'L': // lineto, absolute\n x = current[1];\n y = current[2];\n bounds = [];\n break;\n\n case 'M': // moveTo, absolute\n x = current[1];\n y = current[2];\n subpathStartX = x;\n subpathStartY = y;\n bounds = [];\n break;\n\n case 'C': // bezierCurveTo, absolute\n bounds = fabric.util.getBoundsOfCurve(x, y,\n current[1],\n current[2],\n current[3],\n current[4],\n current[5],\n current[6]\n );\n x = current[5];\n y = current[6];\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n bounds = fabric.util.getBoundsOfCurve(x, y,\n current[1],\n current[2],\n current[1],\n current[2],\n current[3],\n current[4]\n );\n x = current[3];\n y = current[4];\n break;\n\n case 'z':\n case 'Z':\n x = subpathStartX;\n y = subpathStartY;\n break;\n }\n bounds.forEach(function (point) {\n aX.push(point.x);\n aY.push(point.y);\n });\n aX.push(x);\n aY.push(y);\n }\n\n var minX = min(aX) || 0,\n minY = min(aY) || 0,\n maxX = max(aX) || 0,\n maxY = max(aY) || 0,\n deltaX = maxX - minX,\n deltaY = maxY - minY;\n\n return {\n left: minX,\n top: minY,\n width: deltaX,\n height: deltaY\n };\n }\n });\n\n /**\n * Creates an instance of fabric.Path from an object\n * @static\n * @memberOf fabric.Path\n * @param {Object} object\n * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created\n */\n fabric.Path.fromObject = function(object, callback) {\n if (typeof object.sourcePath === 'string') {\n var pathUrl = object.sourcePath;\n fabric.loadSVGFromURL(pathUrl, function (elements) {\n var path = elements[0];\n path.setOptions(object);\n if (object.clipPath) {\n fabric.util.enlivenObjects([object.clipPath], function(elivenedObjects) {\n path.clipPath = elivenedObjects[0];\n callback && callback(path);\n });\n }\n else {\n callback && callback(path);\n }\n });\n }\n else {\n fabric.Object._fromObject('Path', object, callback, 'path');\n }\n };\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by `fabric.Path.fromElement`)\n * @static\n * @memberOf fabric.Path\n * @see http://www.w3.org/TR/SVG/paths.html#PathElement\n */\n fabric.Path.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat(['d']);\n\n /**\n * Creates an instance of fabric.Path from an SVG element\n * @static\n * @memberOf fabric.Path\n * @param {SVGElement} element to parse\n * @param {Function} callback Callback to invoke when an fabric.Path instance is created\n * @param {Object} [options] Options object\n * @param {Function} [callback] Options callback invoked after parsing is finished\n */\n fabric.Path.fromElement = function(element, callback, options) {\n var parsedAttributes = fabric.parseAttributes(element, fabric.Path.ATTRIBUTE_NAMES);\n parsedAttributes.fromSVG = true;\n callback(new fabric.Path(parsedAttributes.d, extend(parsedAttributes, options)));\n };\n /* _FROM_SVG_END_ */\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n min = fabric.util.array.min,\n max = fabric.util.array.max;\n\n if (fabric.Group) {\n return;\n }\n\n /**\n * Group class\n * @class fabric.Group\n * @extends fabric.Object\n * @mixes fabric.Collection\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#groups}\n * @see {@link fabric.Group#initialize} for constructor definition\n */\n fabric.Group = fabric.util.createClass(fabric.Object, fabric.Collection, /** @lends fabric.Group.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'group',\n\n /**\n * Width of stroke\n * @type Number\n * @default\n */\n strokeWidth: 0,\n\n /**\n * Indicates if click, mouseover, mouseout events & hoverCursor should also check for subtargets\n * @type Boolean\n * @default\n */\n subTargetCheck: false,\n\n /**\n * Groups are container, do not render anything on theyr own, ence no cache properties\n * @type Array\n * @default\n */\n cacheProperties: [],\n\n /**\n * setOnGroup is a method used for TextBox that is no more used since 2.0.0 The behavior is still\n * available setting this boolean to true.\n * @type Boolean\n * @since 2.0.0\n * @default\n */\n useSetOnGroup: false,\n\n /**\n * Constructor\n * @param {Object} objects Group objects\n * @param {Object} [options] Options object\n * @param {Boolean} [isAlreadyGrouped] if true, objects have been grouped already.\n * @return {Object} thisArg\n */\n initialize: function(objects, options, isAlreadyGrouped) {\n options = options || {};\n this._objects = [];\n // if objects enclosed in a group have been grouped already,\n // we cannot change properties of objects.\n // Thus we need to set options to group without objects,\n isAlreadyGrouped && this.callSuper('initialize', options);\n this._objects = objects || [];\n for (var i = this._objects.length; i--; ) {\n this._objects[i].group = this;\n }\n\n if (!isAlreadyGrouped) {\n var center = options && options.centerPoint;\n // we want to set origins before calculating the bounding box.\n // so that the topleft can be set with that in mind.\n // if specific top and left are passed, are overwritten later\n // with the callSuper('initialize', options)\n if (options.originX !== undefined) {\n this.originX = options.originX;\n }\n if (options.originY !== undefined) {\n this.originY = options.originY;\n }\n // if coming from svg i do not want to calc bounds.\n // i assume width and height are passed along options\n center || this._calcBounds();\n this._updateObjectsCoords(center);\n delete options.centerPoint;\n this.callSuper('initialize', options);\n }\n else {\n this._updateObjectsACoords();\n }\n\n this.setCoords();\n },\n\n /**\n * @private\n */\n _updateObjectsACoords: function() {\n var skipControls = true;\n for (var i = this._objects.length; i--; ){\n this._objects[i].setCoords(skipControls);\n }\n },\n\n /**\n * @private\n * @param {Boolean} [skipCoordsChange] if true, coordinates of objects enclosed in a group do not change\n */\n _updateObjectsCoords: function(center) {\n var center = center || this.getCenterPoint();\n for (var i = this._objects.length; i--; ){\n this._updateObjectCoords(this._objects[i], center);\n }\n },\n\n /**\n * @private\n * @param {Object} object\n * @param {fabric.Point} center, current center of group.\n */\n _updateObjectCoords: function(object, center) {\n var objectLeft = object.left,\n objectTop = object.top,\n skipControls = true;\n\n object.set({\n left: objectLeft - center.x,\n top: objectTop - center.y\n });\n object.group = this;\n object.setCoords(skipControls);\n },\n\n /**\n * Returns string represenation of a group\n * @return {String}\n */\n toString: function() {\n return '#';\n },\n\n /**\n * Adds an object to a group; Then recalculates group's dimension, position.\n * @param {Object} object\n * @return {fabric.Group} thisArg\n * @chainable\n */\n addWithUpdate: function(object) {\n var nested = !!this.group;\n this._restoreObjectsState();\n fabric.util.resetObjectTransform(this);\n if (object) {\n if (nested) {\n // if this group is inside another group, we need to pre transform the object\n fabric.util.removeTransformFromObject(object, this.group.calcTransformMatrix());\n }\n this._objects.push(object);\n object.group = this;\n object._set('canvas', this.canvas);\n }\n this._calcBounds();\n this._updateObjectsCoords();\n this.dirty = true;\n if (nested) {\n this.group.addWithUpdate();\n }\n else {\n this.setCoords();\n }\n return this;\n },\n\n /**\n * Removes an object from a group; Then recalculates group's dimension, position.\n * @param {Object} object\n * @return {fabric.Group} thisArg\n * @chainable\n */\n removeWithUpdate: function(object) {\n this._restoreObjectsState();\n fabric.util.resetObjectTransform(this);\n\n this.remove(object);\n this._calcBounds();\n this._updateObjectsCoords();\n this.setCoords();\n this.dirty = true;\n return this;\n },\n\n /**\n * @private\n */\n _onObjectAdded: function(object) {\n this.dirty = true;\n object.group = this;\n object._set('canvas', this.canvas);\n },\n\n /**\n * @private\n */\n _onObjectRemoved: function(object) {\n this.dirty = true;\n delete object.group;\n },\n\n /**\n * @private\n */\n _set: function(key, value) {\n var i = this._objects.length;\n if (this.useSetOnGroup) {\n while (i--) {\n this._objects[i].setOnGroup(key, value);\n }\n }\n if (key === 'canvas') {\n while (i--) {\n this._objects[i]._set(key, value);\n }\n }\n fabric.Object.prototype._set.call(this, key, value);\n },\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n var _includeDefaultValues = this.includeDefaultValues;\n var objsToObject = this._objects\n .filter(function (obj) {\n return !obj.excludeFromExport;\n })\n .map(function (obj) {\n var originalDefaults = obj.includeDefaultValues;\n obj.includeDefaultValues = _includeDefaultValues;\n var _obj = obj.toObject(propertiesToInclude);\n obj.includeDefaultValues = originalDefaults;\n return _obj;\n });\n var obj = fabric.Object.prototype.toObject.call(this, propertiesToInclude);\n obj.objects = objsToObject;\n return obj;\n },\n\n /**\n * Returns object representation of an instance, in dataless mode.\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toDatalessObject: function(propertiesToInclude) {\n var objsToObject, sourcePath = this.sourcePath;\n if (sourcePath) {\n objsToObject = sourcePath;\n }\n else {\n var _includeDefaultValues = this.includeDefaultValues;\n objsToObject = this._objects.map(function(obj) {\n var originalDefaults = obj.includeDefaultValues;\n obj.includeDefaultValues = _includeDefaultValues;\n var _obj = obj.toDatalessObject(propertiesToInclude);\n obj.includeDefaultValues = originalDefaults;\n return _obj;\n });\n }\n var obj = fabric.Object.prototype.toDatalessObject.call(this, propertiesToInclude);\n obj.objects = objsToObject;\n return obj;\n },\n\n /**\n * Renders instance on a given context\n * @param {CanvasRenderingContext2D} ctx context to render instance on\n */\n render: function(ctx) {\n this._transformDone = true;\n this.callSuper('render', ctx);\n this._transformDone = false;\n },\n\n /**\n * Decide if the object should cache or not. Create its own cache level\n * needsItsOwnCache should be used when the object drawing method requires\n * a cache step. None of the fabric classes requires it.\n * Generally you do not cache objects in groups because the group is already cached.\n * @return {Boolean}\n */\n shouldCache: function() {\n var ownCache = fabric.Object.prototype.shouldCache.call(this);\n if (ownCache) {\n for (var i = 0, len = this._objects.length; i < len; i++) {\n if (this._objects[i].willDrawShadow()) {\n this.ownCaching = false;\n return false;\n }\n }\n }\n return ownCache;\n },\n\n /**\n * Check if this object or a child object will cast a shadow\n * @return {Boolean}\n */\n willDrawShadow: function() {\n if (fabric.Object.prototype.willDrawShadow.call(this)) {\n return true;\n }\n for (var i = 0, len = this._objects.length; i < len; i++) {\n if (this._objects[i].willDrawShadow()) {\n return true;\n }\n }\n return false;\n },\n\n /**\n * Check if this group or its parent group are caching, recursively up\n * @return {Boolean}\n */\n isOnACache: function() {\n return this.ownCaching || (this.group && this.group.isOnACache());\n },\n\n /**\n * Execute the drawing operation for an object on a specified context\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n drawObject: function(ctx) {\n for (var i = 0, len = this._objects.length; i < len; i++) {\n this._objects[i].render(ctx);\n }\n this._drawClipPath(ctx, this.clipPath);\n },\n\n /**\n * Check if cache is dirty\n */\n isCacheDirty: function(skipCanvas) {\n if (this.callSuper('isCacheDirty', skipCanvas)) {\n return true;\n }\n if (!this.statefullCache) {\n return false;\n }\n for (var i = 0, len = this._objects.length; i < len; i++) {\n if (this._objects[i].isCacheDirty(true)) {\n if (this._cacheCanvas) {\n // if this group has not a cache canvas there is nothing to clean\n var x = this.cacheWidth / this.zoomX, y = this.cacheHeight / this.zoomY;\n this._cacheContext.clearRect(-x / 2, -y / 2, x, y);\n }\n return true;\n }\n }\n return false;\n },\n\n /**\n * Restores original state of each of group objects (original state is that which was before group was created).\n * if the nested boolean is true, the original state will be restored just for the\n * first group and not for all the group chain\n * @private\n * @param {Boolean} nested tell the function to restore object state up to the parent group and not more\n * @return {fabric.Group} thisArg\n * @chainable\n */\n _restoreObjectsState: function() {\n var groupMatrix = this.calcOwnMatrix();\n this._objects.forEach(function(object) {\n // instead of using _this = this;\n fabric.util.addTransformToObject(object, groupMatrix);\n delete object.group;\n object.setCoords();\n });\n return this;\n },\n\n /**\n * Destroys a group (restoring state of its objects)\n * @return {fabric.Group} thisArg\n * @chainable\n */\n destroy: function() {\n // when group is destroyed objects needs to get a repaint to be eventually\n // displayed on canvas.\n this._objects.forEach(function(object) {\n object.set('dirty', true);\n });\n return this._restoreObjectsState();\n },\n\n dispose: function () {\n this.callSuper('dispose');\n this.forEachObject(function (object) {\n object.dispose && object.dispose();\n });\n this._objects = [];\n },\n\n /**\n * make a group an active selection, remove the group from canvas\n * the group has to be on canvas for this to work.\n * @return {fabric.ActiveSelection} thisArg\n * @chainable\n */\n toActiveSelection: function() {\n if (!this.canvas) {\n return;\n }\n var objects = this._objects, canvas = this.canvas;\n this._objects = [];\n var options = this.toObject();\n delete options.objects;\n var activeSelection = new fabric.ActiveSelection([]);\n activeSelection.set(options);\n activeSelection.type = 'activeSelection';\n canvas.remove(this);\n objects.forEach(function(object) {\n object.group = activeSelection;\n object.dirty = true;\n canvas.add(object);\n });\n activeSelection.canvas = canvas;\n activeSelection._objects = objects;\n canvas._activeObject = activeSelection;\n activeSelection.setCoords();\n return activeSelection;\n },\n\n /**\n * Destroys a group (restoring state of its objects)\n * @return {fabric.Group} thisArg\n * @chainable\n */\n ungroupOnCanvas: function() {\n return this._restoreObjectsState();\n },\n\n /**\n * Sets coordinates of all objects inside group\n * @return {fabric.Group} thisArg\n * @chainable\n */\n setObjectsCoords: function() {\n var skipControls = true;\n this.forEachObject(function(object) {\n object.setCoords(skipControls);\n });\n return this;\n },\n\n /**\n * @private\n */\n _calcBounds: function(onlyWidthHeight) {\n var aX = [],\n aY = [],\n o, prop, coords,\n props = ['tr', 'br', 'bl', 'tl'],\n i = 0, iLen = this._objects.length,\n j, jLen = props.length;\n\n for ( ; i < iLen; ++i) {\n o = this._objects[i];\n coords = o.calcACoords();\n for (j = 0; j < jLen; j++) {\n prop = props[j];\n aX.push(coords[prop].x);\n aY.push(coords[prop].y);\n }\n o.aCoords = coords;\n }\n\n this._getBounds(aX, aY, onlyWidthHeight);\n },\n\n /**\n * @private\n */\n _getBounds: function(aX, aY, onlyWidthHeight) {\n var minXY = new fabric.Point(min(aX), min(aY)),\n maxXY = new fabric.Point(max(aX), max(aY)),\n top = minXY.y || 0, left = minXY.x || 0,\n width = (maxXY.x - minXY.x) || 0,\n height = (maxXY.y - minXY.y) || 0;\n this.width = width;\n this.height = height;\n if (!onlyWidthHeight) {\n // the bounding box always finds the topleft most corner.\n // whatever is the group origin, we set up here the left/top position.\n this.setPositionByOrigin({ x: left, y: top }, 'left', 'top');\n }\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns svg representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {String} svg representation of an instance\n */\n _toSVG: function(reviver) {\n var svgString = ['\\n'];\n\n for (var i = 0, len = this._objects.length; i < len; i++) {\n svgString.push('\\t\\t', this._objects[i].toSVG(reviver));\n }\n svgString.push('\\n');\n return svgString;\n },\n\n /**\n * Returns styles-string for svg-export, specific version for group\n * @return {String}\n */\n getSvgStyles: function() {\n var opacity = typeof this.opacity !== 'undefined' && this.opacity !== 1 ?\n 'opacity: ' + this.opacity + ';' : '',\n visibility = this.visible ? '' : ' visibility: hidden;';\n return [\n opacity,\n this.getSvgFilter(),\n visibility\n ].join('');\n },\n\n /**\n * Returns svg clipPath representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {String} svg representation of an instance\n */\n toClipPathSVG: function(reviver) {\n var svgString = [];\n\n for (var i = 0, len = this._objects.length; i < len; i++) {\n svgString.push('\\t', this._objects[i].toClipPathSVG(reviver));\n }\n\n return this._createBaseClipPathSVGMarkup(svgString, { reviver: reviver });\n },\n /* _TO_SVG_END_ */\n });\n\n /**\n * Returns {@link fabric.Group} instance from an object representation\n * @static\n * @memberOf fabric.Group\n * @param {Object} object Object to create a group from\n * @param {Function} [callback] Callback to invoke when an group instance is created\n */\n fabric.Group.fromObject = function(object, callback) {\n var objects = object.objects,\n options = fabric.util.object.clone(object, true);\n delete options.objects;\n if (typeof objects === 'string') {\n // it has to be an url or something went wrong.\n fabric.loadSVGFromURL(objects, function (elements) {\n var group = fabric.util.groupSVGElements(elements, object, objects);\n var clipPath = options.clipPath;\n delete options.clipPath;\n group.set(options);\n if (clipPath) {\n fabric.util.enlivenObjects([clipPath], function(elivenedObjects) {\n group.clipPath = elivenedObjects[0];\n callback && callback(group);\n });\n }\n else {\n callback && callback(group);\n }\n });\n return;\n }\n fabric.util.enlivenObjects(objects, function (enlivenedObjects) {\n fabric.util.enlivenObjectEnlivables(object, options, function () {\n callback && callback(new fabric.Group(enlivenedObjects, options, true));\n });\n });\n };\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { });\n\n if (fabric.ActiveSelection) {\n return;\n }\n\n /**\n * Group class\n * @class fabric.ActiveSelection\n * @extends fabric.Group\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#groups}\n * @see {@link fabric.ActiveSelection#initialize} for constructor definition\n */\n fabric.ActiveSelection = fabric.util.createClass(fabric.Group, /** @lends fabric.ActiveSelection.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'activeSelection',\n\n /**\n * Constructor\n * @param {Object} objects ActiveSelection objects\n * @param {Object} [options] Options object\n * @return {Object} thisArg\n */\n initialize: function(objects, options) {\n options = options || {};\n this._objects = objects || [];\n for (var i = this._objects.length; i--; ) {\n this._objects[i].group = this;\n }\n\n if (options.originX) {\n this.originX = options.originX;\n }\n if (options.originY) {\n this.originY = options.originY;\n }\n this._calcBounds();\n this._updateObjectsCoords();\n fabric.Object.prototype.initialize.call(this, options);\n this.setCoords();\n },\n\n /**\n * Change te activeSelection to a normal group,\n * High level function that automatically adds it to canvas as\n * active object. no events fired.\n * @since 2.0.0\n * @return {fabric.Group}\n */\n toGroup: function() {\n var objects = this._objects.concat();\n this._objects = [];\n var options = fabric.Object.prototype.toObject.call(this);\n var newGroup = new fabric.Group([]);\n delete options.type;\n newGroup.set(options);\n objects.forEach(function(object) {\n object.canvas.remove(object);\n object.group = newGroup;\n });\n newGroup._objects = objects;\n if (!this.canvas) {\n return newGroup;\n }\n var canvas = this.canvas;\n canvas.add(newGroup);\n canvas._activeObject = newGroup;\n newGroup.setCoords();\n return newGroup;\n },\n\n /**\n * If returns true, deselection is cancelled.\n * @since 2.0.0\n * @return {Boolean} [cancel]\n */\n onDeselect: function() {\n this.destroy();\n return false;\n },\n\n /**\n * Returns string representation of a group\n * @return {String}\n */\n toString: function() {\n return '#';\n },\n\n /**\n * Decide if the object should cache or not. Create its own cache level\n * objectCaching is a global flag, wins over everything\n * needsItsOwnCache should be used when the object drawing method requires\n * a cache step. None of the fabric classes requires it.\n * Generally you do not cache objects in groups because the group outside is cached.\n * @return {Boolean}\n */\n shouldCache: function() {\n return false;\n },\n\n /**\n * Check if this group or its parent group are caching, recursively up\n * @return {Boolean}\n */\n isOnACache: function() {\n return false;\n },\n\n /**\n * Renders controls and borders for the object\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {Object} [styleOverride] properties to override the object style\n * @param {Object} [childrenOverride] properties to override the children overrides\n */\n _renderControls: function(ctx, styleOverride, childrenOverride) {\n ctx.save();\n ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;\n this.callSuper('_renderControls', ctx, styleOverride);\n childrenOverride = childrenOverride || { };\n if (typeof childrenOverride.hasControls === 'undefined') {\n childrenOverride.hasControls = false;\n }\n childrenOverride.forActiveSelection = true;\n for (var i = 0, len = this._objects.length; i < len; i++) {\n this._objects[i]._renderControls(ctx, childrenOverride);\n }\n ctx.restore();\n },\n });\n\n /**\n * Returns {@link fabric.ActiveSelection} instance from an object representation\n * @static\n * @memberOf fabric.ActiveSelection\n * @param {Object} object Object to create a group from\n * @param {Function} [callback] Callback to invoke when an ActiveSelection instance is created\n */\n fabric.ActiveSelection.fromObject = function(object, callback) {\n fabric.util.enlivenObjects(object.objects, function(enlivenedObjects) {\n delete object.objects;\n callback && callback(new fabric.ActiveSelection(enlivenedObjects, object, true));\n });\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var extend = fabric.util.object.extend;\n\n if (!global.fabric) {\n global.fabric = { };\n }\n\n if (global.fabric.Image) {\n fabric.warn('fabric.Image is already defined.');\n return;\n }\n\n /**\n * Image class\n * @class fabric.Image\n * @extends fabric.Object\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#images}\n * @see {@link fabric.Image#initialize} for constructor definition\n */\n fabric.Image = fabric.util.createClass(fabric.Object, /** @lends fabric.Image.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'image',\n\n /**\n * Width of a stroke.\n * For image quality a stroke multiple of 2 gives better results.\n * @type Number\n * @default\n */\n strokeWidth: 0,\n\n /**\n * When calling {@link fabric.Image.getSrc}, return value from element src with `element.getAttribute('src')`.\n * This allows for relative urls as image src.\n * @since 2.7.0\n * @type Boolean\n * @default\n */\n srcFromAttribute: false,\n\n /**\n * private\n * contains last value of scaleX to detect\n * if the Image got resized after the last Render\n * @type Number\n */\n _lastScaleX: 1,\n\n /**\n * private\n * contains last value of scaleY to detect\n * if the Image got resized after the last Render\n * @type Number\n */\n _lastScaleY: 1,\n\n /**\n * private\n * contains last value of scaling applied by the apply filter chain\n * @type Number\n */\n _filterScalingX: 1,\n\n /**\n * private\n * contains last value of scaling applied by the apply filter chain\n * @type Number\n */\n _filterScalingY: 1,\n\n /**\n * minimum scale factor under which any resizeFilter is triggered to resize the image\n * 0 will disable the automatic resize. 1 will trigger automatically always.\n * number bigger than 1 are not implemented yet.\n * @type Number\n */\n minimumScaleTrigger: 0.5,\n\n /**\n * List of properties to consider when checking if\n * state of an object is changed ({@link fabric.Object#hasStateChanged})\n * as well as for history (undo/redo) purposes\n * @type Array\n */\n stateProperties: fabric.Object.prototype.stateProperties.concat('cropX', 'cropY'),\n\n /**\n * List of properties to consider when checking if cache needs refresh\n * Those properties are checked by statefullCache ON ( or lazy mode if we want ) or from single\n * calls to Object.set(key, value). If the key is in this list, the object is marked as dirty\n * and refreshed at the next render\n * @type Array\n */\n cacheProperties: fabric.Object.prototype.cacheProperties.concat('cropX', 'cropY'),\n\n /**\n * key used to retrieve the texture representing this image\n * @since 2.0.0\n * @type String\n * @default\n */\n cacheKey: '',\n\n /**\n * Image crop in pixels from original image size.\n * @since 2.0.0\n * @type Number\n * @default\n */\n cropX: 0,\n\n /**\n * Image crop in pixels from original image size.\n * @since 2.0.0\n * @type Number\n * @default\n */\n cropY: 0,\n\n /**\n * Indicates whether this canvas will use image smoothing when painting this image.\n * Also influence if the cacheCanvas for this image uses imageSmoothing\n * @since 4.0.0-beta.11\n * @type Boolean\n * @default\n */\n imageSmoothing: true,\n\n /**\n * Constructor\n * Image can be initialized with any canvas drawable or a string.\n * The string should be a url and will be loaded as an image.\n * Canvas and Image element work out of the box, while videos require extra code to work.\n * Please check video element events for seeking.\n * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | String} element Image element\n * @param {Object} [options] Options object\n * @param {function} [callback] callback function to call after eventual filters applied.\n * @return {fabric.Image} thisArg\n */\n initialize: function(element, options) {\n options || (options = { });\n this.filters = [];\n this.cacheKey = 'texture' + fabric.Object.__uid++;\n this.callSuper('initialize', options);\n this._initElement(element, options);\n },\n\n /**\n * Returns image element which this instance if based on\n * @return {HTMLImageElement} Image element\n */\n getElement: function() {\n return this._element || {};\n },\n\n /**\n * Sets image element for this instance to a specified one.\n * If filters defined they are applied to new image.\n * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area.\n * @param {HTMLImageElement} element\n * @param {Object} [options] Options object\n * @return {fabric.Image} thisArg\n * @chainable\n */\n setElement: function(element, options) {\n this.removeTexture(this.cacheKey);\n this.removeTexture(this.cacheKey + '_filtered');\n this._element = element;\n this._originalElement = element;\n this._initConfig(options);\n if (this.filters.length !== 0) {\n this.applyFilters();\n }\n // resizeFilters work on the already filtered copy.\n // we need to apply resizeFilters AFTER normal filters.\n // applyResizeFilters is run more often than normal filters\n // and is triggered by user interactions rather than dev code\n if (this.resizeFilter) {\n this.applyResizeFilters();\n }\n return this;\n },\n\n /**\n * Delete a single texture if in webgl mode\n */\n removeTexture: function(key) {\n var backend = fabric.filterBackend;\n if (backend && backend.evictCachesForKey) {\n backend.evictCachesForKey(key);\n }\n },\n\n /**\n * Delete textures, reference to elements and eventually JSDOM cleanup\n */\n dispose: function () {\n this.callSuper('dispose');\n this.removeTexture(this.cacheKey);\n this.removeTexture(this.cacheKey + '_filtered');\n this._cacheContext = undefined;\n ['_originalElement', '_element', '_filteredEl', '_cacheCanvas'].forEach((function(element) {\n fabric.util.cleanUpJsdomNode(this[element]);\n this[element] = undefined;\n }).bind(this));\n },\n\n /**\n * Get the crossOrigin value (of the corresponding image element)\n */\n getCrossOrigin: function() {\n return this._originalElement && (this._originalElement.crossOrigin || null);\n },\n\n /**\n * Returns original size of an image\n * @return {Object} Object with \"width\" and \"height\" properties\n */\n getOriginalSize: function() {\n var element = this.getElement();\n return {\n width: element.naturalWidth || element.width,\n height: element.naturalHeight || element.height\n };\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _stroke: function(ctx) {\n if (!this.stroke || this.strokeWidth === 0) {\n return;\n }\n var w = this.width / 2, h = this.height / 2;\n ctx.beginPath();\n ctx.moveTo(-w, -h);\n ctx.lineTo(w, -h);\n ctx.lineTo(w, h);\n ctx.lineTo(-w, h);\n ctx.lineTo(-w, -h);\n ctx.closePath();\n },\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} Object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n var filters = [];\n\n this.filters.forEach(function(filterObj) {\n if (filterObj) {\n filters.push(filterObj.toObject());\n }\n });\n var object = extend(\n this.callSuper(\n 'toObject',\n ['cropX', 'cropY'].concat(propertiesToInclude)\n ), {\n src: this.getSrc(),\n crossOrigin: this.getCrossOrigin(),\n filters: filters,\n });\n if (this.resizeFilter) {\n object.resizeFilter = this.resizeFilter.toObject();\n }\n return object;\n },\n\n /**\n * Returns true if an image has crop applied, inspecting values of cropX,cropY,width,height.\n * @return {Boolean}\n */\n hasCrop: function() {\n return this.cropX || this.cropY || this.width < this._element.width || this.height < this._element.height;\n },\n\n /* _TO_SVG_START_ */\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG: function() {\n var svgString = [], imageMarkup = [], strokeSvg, element = this._element,\n x = -this.width / 2, y = -this.height / 2, clipPath = '', imageRendering = '';\n if (!element) {\n return [];\n }\n if (this.hasCrop()) {\n var clipPathId = fabric.Object.__uid++;\n svgString.push(\n '\\n',\n '\\t\\n',\n '\\n'\n );\n clipPath = ' clip-path=\"url(#imageCrop_' + clipPathId + ')\" ';\n }\n if (!this.imageSmoothing) {\n imageRendering = '\" image-rendering=\"optimizeSpeed';\n }\n imageMarkup.push('\\t element with actual transformation, then offsetting object to the top/left\n // so that object's center aligns with container's left/top\n '\" width=\"', element.width || element.naturalWidth,\n '\" height=\"', element.height || element.height,\n imageRendering,\n '\"', clipPath,\n '>\\n');\n\n if (this.stroke || this.strokeDashArray) {\n var origFill = this.fill;\n this.fill = null;\n strokeSvg = [\n '\\t\\n'\n ];\n this.fill = origFill;\n }\n if (this.paintFirst !== 'fill') {\n svgString = svgString.concat(strokeSvg, imageMarkup);\n }\n else {\n svgString = svgString.concat(imageMarkup, strokeSvg);\n }\n return svgString;\n },\n /* _TO_SVG_END_ */\n\n /**\n * Returns source of an image\n * @param {Boolean} filtered indicates if the src is needed for svg\n * @return {String} Source of an image\n */\n getSrc: function(filtered) {\n var element = filtered ? this._element : this._originalElement;\n if (element) {\n if (element.toDataURL) {\n return element.toDataURL();\n }\n\n if (this.srcFromAttribute) {\n return element.getAttribute('src');\n }\n else {\n return element.src;\n }\n }\n else {\n return this.src || '';\n }\n },\n\n /**\n * Sets source of an image\n * @param {String} src Source string (URL)\n * @param {Function} [callback] Callback is invoked when image has been loaded (and all filters have been applied)\n * @param {Object} [options] Options object\n * @param {String} [options.crossOrigin] crossOrigin value (one of \"\", \"anonymous\", \"use-credentials\")\n * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes\n * @return {fabric.Image} thisArg\n * @chainable\n */\n setSrc: function(src, callback, options) {\n fabric.util.loadImage(src, function(img, isError) {\n this.setElement(img, options);\n this._setWidthHeight();\n callback && callback(this, isError);\n }, this, options && options.crossOrigin);\n return this;\n },\n\n /**\n * Returns string representation of an instance\n * @return {String} String representation of an instance\n */\n toString: function() {\n return '#';\n },\n\n applyResizeFilters: function() {\n var filter = this.resizeFilter,\n minimumScale = this.minimumScaleTrigger,\n objectScale = this.getTotalObjectScaling(),\n scaleX = objectScale.scaleX,\n scaleY = objectScale.scaleY,\n elementToFilter = this._filteredEl || this._originalElement;\n if (this.group) {\n this.set('dirty', true);\n }\n if (!filter || (scaleX > minimumScale && scaleY > minimumScale)) {\n this._element = elementToFilter;\n this._filterScalingX = 1;\n this._filterScalingY = 1;\n this._lastScaleX = scaleX;\n this._lastScaleY = scaleY;\n return;\n }\n if (!fabric.filterBackend) {\n fabric.filterBackend = fabric.initFilterBackend();\n }\n var canvasEl = fabric.util.createCanvasElement(),\n cacheKey = this._filteredEl ? (this.cacheKey + '_filtered') : this.cacheKey,\n sourceWidth = elementToFilter.width, sourceHeight = elementToFilter.height;\n canvasEl.width = sourceWidth;\n canvasEl.height = sourceHeight;\n this._element = canvasEl;\n this._lastScaleX = filter.scaleX = scaleX;\n this._lastScaleY = filter.scaleY = scaleY;\n fabric.filterBackend.applyFilters(\n [filter], elementToFilter, sourceWidth, sourceHeight, this._element, cacheKey);\n this._filterScalingX = canvasEl.width / this._originalElement.width;\n this._filterScalingY = canvasEl.height / this._originalElement.height;\n },\n\n /**\n * Applies filters assigned to this image (from \"filters\" array) or from filter param\n * @method applyFilters\n * @param {Array} filters to be applied\n * @param {Boolean} forResizing specify if the filter operation is a resize operation\n * @return {thisArg} return the fabric.Image object\n * @chainable\n */\n applyFilters: function(filters) {\n\n filters = filters || this.filters || [];\n filters = filters.filter(function(filter) { return filter && !filter.isNeutralState(); });\n this.set('dirty', true);\n\n // needs to clear out or WEBGL will not resize correctly\n this.removeTexture(this.cacheKey + '_filtered');\n\n if (filters.length === 0) {\n this._element = this._originalElement;\n this._filteredEl = null;\n this._filterScalingX = 1;\n this._filterScalingY = 1;\n return this;\n }\n\n var imgElement = this._originalElement,\n sourceWidth = imgElement.naturalWidth || imgElement.width,\n sourceHeight = imgElement.naturalHeight || imgElement.height;\n\n if (this._element === this._originalElement) {\n // if the element is the same we need to create a new element\n var canvasEl = fabric.util.createCanvasElement();\n canvasEl.width = sourceWidth;\n canvasEl.height = sourceHeight;\n this._element = canvasEl;\n this._filteredEl = canvasEl;\n }\n else {\n // clear the existing element to get new filter data\n // also dereference the eventual resized _element\n this._element = this._filteredEl;\n this._filteredEl.getContext('2d').clearRect(0, 0, sourceWidth, sourceHeight);\n // we also need to resize again at next renderAll, so remove saved _lastScaleX/Y\n this._lastScaleX = 1;\n this._lastScaleY = 1;\n }\n if (!fabric.filterBackend) {\n fabric.filterBackend = fabric.initFilterBackend();\n }\n fabric.filterBackend.applyFilters(\n filters, this._originalElement, sourceWidth, sourceHeight, this._element, this.cacheKey);\n if (this._originalElement.width !== this._element.width ||\n this._originalElement.height !== this._element.height) {\n this._filterScalingX = this._element.width / this._originalElement.width;\n this._filterScalingY = this._element.height / this._originalElement.height;\n }\n return this;\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(ctx) {\n fabric.util.setImageSmoothing(ctx, this.imageSmoothing);\n if (this.isMoving !== true && this.resizeFilter && this._needsResize()) {\n this.applyResizeFilters();\n }\n this._stroke(ctx);\n this._renderPaintInOrder(ctx);\n },\n\n /**\n * Paint the cached copy of the object on the target context.\n * it will set the imageSmoothing for the draw operation\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n drawCacheOnCanvas: function(ctx) {\n fabric.util.setImageSmoothing(ctx, this.imageSmoothing);\n fabric.Object.prototype.drawCacheOnCanvas.call(this, ctx);\n },\n\n /**\n * Decide if the object should cache or not. Create its own cache level\n * needsItsOwnCache should be used when the object drawing method requires\n * a cache step. None of the fabric classes requires it.\n * Generally you do not cache objects in groups because the group outside is cached.\n * This is the special image version where we would like to avoid caching where possible.\n * Essentially images do not benefit from caching. They may require caching, and in that\n * case we do it. Also caching an image usually ends in a loss of details.\n * A full performance audit should be done.\n * @return {Boolean}\n */\n shouldCache: function() {\n return this.needsItsOwnCache();\n },\n\n _renderFill: function(ctx) {\n var elementToDraw = this._element;\n if (!elementToDraw) {\n return;\n }\n var scaleX = this._filterScalingX, scaleY = this._filterScalingY,\n w = this.width, h = this.height, min = Math.min, max = Math.max,\n // crop values cannot be lesser than 0.\n cropX = max(this.cropX, 0), cropY = max(this.cropY, 0),\n elWidth = elementToDraw.naturalWidth || elementToDraw.width,\n elHeight = elementToDraw.naturalHeight || elementToDraw.height,\n sX = cropX * scaleX,\n sY = cropY * scaleY,\n // the width height cannot exceed element width/height, starting from the crop offset.\n sW = min(w * scaleX, elWidth - sX),\n sH = min(h * scaleY, elHeight - sY),\n x = -w / 2, y = -h / 2,\n maxDestW = min(w, elWidth / scaleX - cropX),\n maxDestH = min(h, elHeight / scaleY - cropY);\n\n elementToDraw && ctx.drawImage(elementToDraw, sX, sY, sW, sH, x, y, maxDestW, maxDestH);\n },\n\n /**\n * needed to check if image needs resize\n * @private\n */\n _needsResize: function() {\n var scale = this.getTotalObjectScaling();\n return (scale.scaleX !== this._lastScaleX || scale.scaleY !== this._lastScaleY);\n },\n\n /**\n * @private\n */\n _resetWidthHeight: function() {\n this.set(this.getOriginalSize());\n },\n\n /**\n * The Image class's initialization method. This method is automatically\n * called by the constructor.\n * @private\n * @param {HTMLImageElement|String} element The element representing the image\n * @param {Object} [options] Options object\n */\n _initElement: function(element, options) {\n this.setElement(fabric.util.getById(element), options);\n fabric.util.addClass(this.getElement(), fabric.Image.CSS_CANVAS);\n },\n\n /**\n * @private\n * @param {Object} [options] Options object\n */\n _initConfig: function(options) {\n options || (options = { });\n this.setOptions(options);\n this._setWidthHeight(options);\n },\n\n /**\n * @private\n * @param {Array} filters to be initialized\n * @param {Function} callback Callback to invoke when all fabric.Image.filters instances are created\n */\n _initFilters: function(filters, callback) {\n if (filters && filters.length) {\n fabric.util.enlivenObjects(filters, function(enlivenedObjects) {\n callback && callback(enlivenedObjects);\n }, 'fabric.Image.filters');\n }\n else {\n callback && callback();\n }\n },\n\n /**\n * @private\n * Set the width and the height of the image object, using the element or the\n * options.\n * @param {Object} [options] Object with width/height properties\n */\n _setWidthHeight: function(options) {\n options || (options = { });\n var el = this.getElement();\n this.width = options.width || el.naturalWidth || el.width || 0;\n this.height = options.height || el.naturalHeight || el.height || 0;\n },\n\n /**\n * Calculate offset for center and scale factor for the image in order to respect\n * the preserveAspectRatio attribute\n * @private\n * @return {Object}\n */\n parsePreserveAspectRatioAttribute: function() {\n var pAR = fabric.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio || ''),\n rWidth = this._element.width, rHeight = this._element.height,\n scaleX = 1, scaleY = 1, offsetLeft = 0, offsetTop = 0, cropX = 0, cropY = 0,\n offset, pWidth = this.width, pHeight = this.height, parsedAttributes = { width: pWidth, height: pHeight };\n if (pAR && (pAR.alignX !== 'none' || pAR.alignY !== 'none')) {\n if (pAR.meetOrSlice === 'meet') {\n scaleX = scaleY = fabric.util.findScaleToFit(this._element, parsedAttributes);\n offset = (pWidth - rWidth * scaleX) / 2;\n if (pAR.alignX === 'Min') {\n offsetLeft = -offset;\n }\n if (pAR.alignX === 'Max') {\n offsetLeft = offset;\n }\n offset = (pHeight - rHeight * scaleY) / 2;\n if (pAR.alignY === 'Min') {\n offsetTop = -offset;\n }\n if (pAR.alignY === 'Max') {\n offsetTop = offset;\n }\n }\n if (pAR.meetOrSlice === 'slice') {\n scaleX = scaleY = fabric.util.findScaleToCover(this._element, parsedAttributes);\n offset = rWidth - pWidth / scaleX;\n if (pAR.alignX === 'Mid') {\n cropX = offset / 2;\n }\n if (pAR.alignX === 'Max') {\n cropX = offset;\n }\n offset = rHeight - pHeight / scaleY;\n if (pAR.alignY === 'Mid') {\n cropY = offset / 2;\n }\n if (pAR.alignY === 'Max') {\n cropY = offset;\n }\n rWidth = pWidth / scaleX;\n rHeight = pHeight / scaleY;\n }\n }\n else {\n scaleX = pWidth / rWidth;\n scaleY = pHeight / rHeight;\n }\n return {\n width: rWidth,\n height: rHeight,\n scaleX: scaleX,\n scaleY: scaleY,\n offsetLeft: offsetLeft,\n offsetTop: offsetTop,\n cropX: cropX,\n cropY: cropY\n };\n }\n });\n\n /**\n * Default CSS class name for canvas\n * @static\n * @type String\n * @default\n */\n fabric.Image.CSS_CANVAS = 'canvas-img';\n\n /**\n * Alias for getSrc\n * @static\n */\n fabric.Image.prototype.getSvgSrc = fabric.Image.prototype.getSrc;\n\n /**\n * Creates an instance of fabric.Image from its object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {Function} callback Callback to invoke when an image instance is created\n */\n fabric.Image.fromObject = function(_object, callback) {\n var object = fabric.util.object.clone(_object);\n fabric.util.loadImage(object.src, function(img, isError) {\n if (isError) {\n callback && callback(null, true);\n return;\n }\n fabric.Image.prototype._initFilters.call(object, object.filters, function(filters) {\n object.filters = filters || [];\n fabric.Image.prototype._initFilters.call(object, [object.resizeFilter], function(resizeFilters) {\n object.resizeFilter = resizeFilters[0];\n fabric.util.enlivenObjectEnlivables(object, object, function () {\n var image = new fabric.Image(img, object);\n callback(image, false);\n });\n });\n });\n }, null, object.crossOrigin);\n };\n\n /**\n * Creates an instance of fabric.Image from an URL string\n * @static\n * @param {String} url URL to create an image from\n * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument). Second argument is a boolean indicating if an error occurred or not.\n * @param {Object} [imgOptions] Options object\n */\n fabric.Image.fromURL = function(url, callback, imgOptions) {\n fabric.util.loadImage(url, function(img, isError) {\n callback && callback(new fabric.Image(img, imgOptions), isError);\n }, null, imgOptions && imgOptions.crossOrigin);\n };\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link fabric.Image.fromElement})\n * @static\n * @see {@link http://www.w3.org/TR/SVG/struct.html#ImageElement}\n */\n fabric.Image.ATTRIBUTE_NAMES =\n fabric.SHARED_ATTRIBUTES.concat(\n 'x y width height preserveAspectRatio xlink:href crossOrigin image-rendering'.split(' ')\n );\n\n /**\n * Returns {@link fabric.Image} instance from an SVG element\n * @static\n * @param {SVGElement} element Element to parse\n * @param {Object} [options] Options object\n * @param {Function} callback Callback to execute when fabric.Image object is created\n * @return {fabric.Image} Instance of fabric.Image\n */\n fabric.Image.fromElement = function(element, callback, options) {\n var parsedAttributes = fabric.parseAttributes(element, fabric.Image.ATTRIBUTE_NAMES);\n fabric.Image.fromURL(parsedAttributes['xlink:href'], callback,\n extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes));\n };\n /* _FROM_SVG_END_ */\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\nfabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {\n\n /**\n * @private\n * @return {Number} angle value\n */\n _getAngleValueForStraighten: function() {\n var angle = this.angle % 360;\n if (angle > 0) {\n return Math.round((angle - 1) / 90) * 90;\n }\n return Math.round(angle / 90) * 90;\n },\n\n /**\n * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer)\n * @return {fabric.Object} thisArg\n * @chainable\n */\n straighten: function() {\n return this.rotate(this._getAngleValueForStraighten());\n },\n\n /**\n * Same as {@link fabric.Object.prototype.straighten} but with animation\n * @param {Object} callbacks Object with callback functions\n * @param {Function} [callbacks.onComplete] Invoked on completion\n * @param {Function} [callbacks.onChange] Invoked on every step of animation\n * @return {fabric.Object} thisArg\n */\n fxStraighten: function(callbacks) {\n callbacks = callbacks || { };\n\n var empty = function() { },\n onComplete = callbacks.onComplete || empty,\n onChange = callbacks.onChange || empty,\n _this = this;\n\n return fabric.util.animate({\n target: this,\n startValue: this.get('angle'),\n endValue: this._getAngleValueForStraighten(),\n duration: this.FX_DURATION,\n onChange: function(value) {\n _this.rotate(value);\n onChange();\n },\n onComplete: function() {\n _this.setCoords();\n onComplete();\n },\n });\n }\n});\n\nfabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {\n\n /**\n * Straightens object, then rerenders canvas\n * @param {fabric.Object} object Object to straighten\n * @return {fabric.Canvas} thisArg\n * @chainable\n */\n straightenObject: function (object) {\n object.straighten();\n this.requestRenderAll();\n return this;\n },\n\n /**\n * Same as {@link fabric.Canvas.prototype.straightenObject}, but animated\n * @param {fabric.Object} object Object to straighten\n * @return {fabric.Canvas} thisArg\n */\n fxStraightenObject: function (object) {\n return object.fxStraighten({\n onChange: this.requestRenderAllBound\n });\n }\n});\n\n\n(function() {\n\n 'use strict';\n\n /**\n * Tests if webgl supports certain precision\n * @param {WebGL} Canvas WebGL context to test on\n * @param {String} Precision to test can be any of following: 'lowp', 'mediump', 'highp'\n * @returns {Boolean} Whether the user's browser WebGL supports given precision.\n */\n function testPrecision(gl, precision){\n var fragmentSource = 'precision ' + precision + ' float;\\nvoid main(){}';\n var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragmentShader, fragmentSource);\n gl.compileShader(fragmentShader);\n if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {\n return false;\n }\n return true;\n }\n\n /**\n * Indicate whether this filtering backend is supported by the user's browser.\n * @param {Number} tileSize check if the tileSize is supported\n * @returns {Boolean} Whether the user's browser supports WebGL.\n */\n fabric.isWebglSupported = function(tileSize) {\n if (fabric.isLikelyNode) {\n return false;\n }\n tileSize = tileSize || fabric.WebglFilterBackend.prototype.tileSize;\n var canvas = document.createElement('canvas');\n var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');\n var isSupported = false;\n // eslint-disable-next-line\n if (gl) {\n fabric.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);\n isSupported = fabric.maxTextureSize >= tileSize;\n var precisions = ['highp', 'mediump', 'lowp'];\n for (var i = 0; i < 3; i++){\n if (testPrecision(gl, precisions[i])){\n fabric.webGlPrecision = precisions[i];\n break;\n };\n }\n }\n this.isSupported = isSupported;\n return isSupported;\n };\n\n fabric.WebglFilterBackend = WebglFilterBackend;\n\n /**\n * WebGL filter backend.\n */\n function WebglFilterBackend(options) {\n if (options && options.tileSize) {\n this.tileSize = options.tileSize;\n }\n this.setupGLContext(this.tileSize, this.tileSize);\n this.captureGPUInfo();\n };\n\n WebglFilterBackend.prototype = /** @lends fabric.WebglFilterBackend.prototype */ {\n\n tileSize: 2048,\n\n /**\n * Experimental. This object is a sort of repository of help layers used to avoid\n * of recreating them during frequent filtering. If you are previewing a filter with\n * a slider you probably do not want to create help layers every filter step.\n * in this object there will be appended some canvases, created once, resized sometimes\n * cleared never. Clearing is left to the developer.\n **/\n resources: {\n\n },\n\n /**\n * Setup a WebGL context suitable for filtering, and bind any needed event handlers.\n */\n setupGLContext: function(width, height) {\n this.dispose();\n this.createWebGLCanvas(width, height);\n // eslint-disable-next-line\n this.aPosition = new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]);\n this.chooseFastestCopyGLTo2DMethod(width, height);\n },\n\n /**\n * Pick a method to copy data from GL context to 2d canvas. In some browsers using\n * putImageData is faster than drawImage for that specific operation.\n */\n chooseFastestCopyGLTo2DMethod: function(width, height) {\n var canMeasurePerf = typeof window.performance !== 'undefined', canUseImageData;\n try {\n new ImageData(1, 1);\n canUseImageData = true;\n }\n catch (e) {\n canUseImageData = false;\n }\n // eslint-disable-next-line no-undef\n var canUseArrayBuffer = typeof ArrayBuffer !== 'undefined';\n // eslint-disable-next-line no-undef\n var canUseUint8Clamped = typeof Uint8ClampedArray !== 'undefined';\n\n if (!(canMeasurePerf && canUseImageData && canUseArrayBuffer && canUseUint8Clamped)) {\n return;\n }\n\n var targetCanvas = fabric.util.createCanvasElement();\n // eslint-disable-next-line no-undef\n var imageBuffer = new ArrayBuffer(width * height * 4);\n if (fabric.forceGLPutImageData) {\n this.imageBuffer = imageBuffer;\n this.copyGLTo2D = copyGLTo2DPutImageData;\n return;\n }\n var testContext = {\n imageBuffer: imageBuffer,\n destinationWidth: width,\n destinationHeight: height,\n targetCanvas: targetCanvas\n };\n var startTime, drawImageTime, putImageDataTime;\n targetCanvas.width = width;\n targetCanvas.height = height;\n\n startTime = window.performance.now();\n copyGLTo2DDrawImage.call(testContext, this.gl, testContext);\n drawImageTime = window.performance.now() - startTime;\n\n startTime = window.performance.now();\n copyGLTo2DPutImageData.call(testContext, this.gl, testContext);\n putImageDataTime = window.performance.now() - startTime;\n\n if (drawImageTime > putImageDataTime) {\n this.imageBuffer = imageBuffer;\n this.copyGLTo2D = copyGLTo2DPutImageData;\n }\n else {\n this.copyGLTo2D = copyGLTo2DDrawImage;\n }\n },\n\n /**\n * Create a canvas element and associated WebGL context and attaches them as\n * class properties to the GLFilterBackend class.\n */\n createWebGLCanvas: function(width, height) {\n var canvas = fabric.util.createCanvasElement();\n canvas.width = width;\n canvas.height = height;\n var glOptions = {\n alpha: true,\n premultipliedAlpha: false,\n depth: false,\n stencil: false,\n antialias: false\n },\n gl = canvas.getContext('webgl', glOptions);\n if (!gl) {\n gl = canvas.getContext('experimental-webgl', glOptions);\n }\n if (!gl) {\n return;\n }\n gl.clearColor(0, 0, 0, 0);\n // this canvas can fire webglcontextlost and webglcontextrestored\n this.canvas = canvas;\n this.gl = gl;\n },\n\n /**\n * Attempts to apply the requested filters to the source provided, drawing the filtered output\n * to the provided target canvas.\n *\n * @param {Array} filters The filters to apply.\n * @param {HTMLImageElement|HTMLCanvasElement} source The source to be filtered.\n * @param {Number} width The width of the source input.\n * @param {Number} height The height of the source input.\n * @param {HTMLCanvasElement} targetCanvas The destination for filtered output to be drawn.\n * @param {String|undefined} cacheKey A key used to cache resources related to the source. If\n * omitted, caching will be skipped.\n */\n applyFilters: function(filters, source, width, height, targetCanvas, cacheKey) {\n var gl = this.gl;\n var cachedTexture;\n if (cacheKey) {\n cachedTexture = this.getCachedTexture(cacheKey, source);\n }\n var pipelineState = {\n originalWidth: source.width || source.originalWidth,\n originalHeight: source.height || source.originalHeight,\n sourceWidth: width,\n sourceHeight: height,\n destinationWidth: width,\n destinationHeight: height,\n context: gl,\n sourceTexture: this.createTexture(gl, width, height, !cachedTexture && source),\n targetTexture: this.createTexture(gl, width, height),\n originalTexture: cachedTexture ||\n this.createTexture(gl, width, height, !cachedTexture && source),\n passes: filters.length,\n webgl: true,\n aPosition: this.aPosition,\n programCache: this.programCache,\n pass: 0,\n filterBackend: this,\n targetCanvas: targetCanvas\n };\n var tempFbo = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, tempFbo);\n filters.forEach(function(filter) { filter && filter.applyTo(pipelineState); });\n resizeCanvasIfNeeded(pipelineState);\n this.copyGLTo2D(gl, pipelineState);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.deleteTexture(pipelineState.sourceTexture);\n gl.deleteTexture(pipelineState.targetTexture);\n gl.deleteFramebuffer(tempFbo);\n targetCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);\n return pipelineState;\n },\n\n /**\n * Detach event listeners, remove references, and clean up caches.\n */\n dispose: function() {\n if (this.canvas) {\n this.canvas = null;\n this.gl = null;\n }\n this.clearWebGLCaches();\n },\n\n /**\n * Wipe out WebGL-related caches.\n */\n clearWebGLCaches: function() {\n this.programCache = {};\n this.textureCache = {};\n },\n\n /**\n * Create a WebGL texture object.\n *\n * Accepts specific dimensions to initialize the texture to or a source image.\n *\n * @param {WebGLRenderingContext} gl The GL context to use for creating the texture.\n * @param {Number} width The width to initialize the texture at.\n * @param {Number} height The height to initialize the texture.\n * @param {HTMLImageElement|HTMLCanvasElement} textureImageSource A source for the texture data.\n * @param {Number} filterType gl.NEAREST or gl.LINEAR usually, webgl numeri constants\n * @returns {WebGLTexture}\n */\n createTexture: function(gl, width, height, textureImageSource, filterType) {\n var texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filterType || gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filterType || gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n if (textureImageSource) {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureImageSource);\n }\n else {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n }\n return texture;\n },\n\n /**\n * Can be optionally used to get a texture from the cache array\n *\n * If an existing texture is not found, a new texture is created and cached.\n *\n * @param {String} uniqueId A cache key to use to find an existing texture.\n * @param {HTMLImageElement|HTMLCanvasElement} textureImageSource A source to use to create the\n * texture cache entry if one does not already exist.\n */\n getCachedTexture: function(uniqueId, textureImageSource) {\n if (this.textureCache[uniqueId]) {\n return this.textureCache[uniqueId];\n }\n else {\n var texture = this.createTexture(\n this.gl, textureImageSource.width, textureImageSource.height, textureImageSource);\n this.textureCache[uniqueId] = texture;\n return texture;\n }\n },\n\n /**\n * Clear out cached resources related to a source image that has been\n * filtered previously.\n *\n * @param {String} cacheKey The cache key provided when the source image was filtered.\n */\n evictCachesForKey: function(cacheKey) {\n if (this.textureCache[cacheKey]) {\n this.gl.deleteTexture(this.textureCache[cacheKey]);\n delete this.textureCache[cacheKey];\n }\n },\n\n copyGLTo2D: copyGLTo2DDrawImage,\n\n /**\n * Attempt to extract GPU information strings from a WebGL context.\n *\n * Useful information when debugging or blacklisting specific GPUs.\n *\n * @returns {Object} A GPU info object with renderer and vendor strings.\n */\n captureGPUInfo: function() {\n if (this.gpuInfo) {\n return this.gpuInfo;\n }\n var gl = this.gl, gpuInfo = { renderer: '', vendor: '' };\n if (!gl) {\n return gpuInfo;\n }\n var ext = gl.getExtension('WEBGL_debug_renderer_info');\n if (ext) {\n var renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);\n var vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL);\n if (renderer) {\n gpuInfo.renderer = renderer.toLowerCase();\n }\n if (vendor) {\n gpuInfo.vendor = vendor.toLowerCase();\n }\n }\n this.gpuInfo = gpuInfo;\n return gpuInfo;\n },\n };\n})();\n\nfunction resizeCanvasIfNeeded(pipelineState) {\n var targetCanvas = pipelineState.targetCanvas,\n width = targetCanvas.width, height = targetCanvas.height,\n dWidth = pipelineState.destinationWidth,\n dHeight = pipelineState.destinationHeight;\n\n if (width !== dWidth || height !== dHeight) {\n targetCanvas.width = dWidth;\n targetCanvas.height = dHeight;\n }\n}\n\n/**\n * Copy an input WebGL canvas on to an output 2D canvas.\n *\n * The WebGL canvas is assumed to be upside down, with the top-left pixel of the\n * desired output image appearing in the bottom-left corner of the WebGL canvas.\n *\n * @param {WebGLRenderingContext} sourceContext The WebGL context to copy from.\n * @param {HTMLCanvasElement} targetCanvas The 2D target canvas to copy on to.\n * @param {Object} pipelineState The 2D target canvas to copy on to.\n */\nfunction copyGLTo2DDrawImage(gl, pipelineState) {\n var glCanvas = gl.canvas, targetCanvas = pipelineState.targetCanvas,\n ctx = targetCanvas.getContext('2d');\n ctx.translate(0, targetCanvas.height); // move it down again\n ctx.scale(1, -1); // vertical flip\n // where is my image on the big glcanvas?\n var sourceY = glCanvas.height - targetCanvas.height;\n ctx.drawImage(glCanvas, 0, sourceY, targetCanvas.width, targetCanvas.height, 0, 0,\n targetCanvas.width, targetCanvas.height);\n}\n\n/**\n * Copy an input WebGL canvas on to an output 2D canvas using 2d canvas' putImageData\n * API. Measurably faster than using ctx.drawImage in Firefox (version 54 on OSX Sierra).\n *\n * @param {WebGLRenderingContext} sourceContext The WebGL context to copy from.\n * @param {HTMLCanvasElement} targetCanvas The 2D target canvas to copy on to.\n * @param {Object} pipelineState The 2D target canvas to copy on to.\n */\nfunction copyGLTo2DPutImageData(gl, pipelineState) {\n var targetCanvas = pipelineState.targetCanvas, ctx = targetCanvas.getContext('2d'),\n dWidth = pipelineState.destinationWidth,\n dHeight = pipelineState.destinationHeight,\n numBytes = dWidth * dHeight * 4;\n\n // eslint-disable-next-line no-undef\n var u8 = new Uint8Array(this.imageBuffer, 0, numBytes);\n // eslint-disable-next-line no-undef\n var u8Clamped = new Uint8ClampedArray(this.imageBuffer, 0, numBytes);\n\n gl.readPixels(0, 0, dWidth, dHeight, gl.RGBA, gl.UNSIGNED_BYTE, u8);\n var imgData = new ImageData(u8Clamped, dWidth, dHeight);\n ctx.putImageData(imgData, 0, 0);\n}\n\n\n(function() {\n\n 'use strict';\n\n var noop = function() {};\n\n fabric.Canvas2dFilterBackend = Canvas2dFilterBackend;\n\n /**\n * Canvas 2D filter backend.\n */\n function Canvas2dFilterBackend() {};\n\n Canvas2dFilterBackend.prototype = /** @lends fabric.Canvas2dFilterBackend.prototype */ {\n evictCachesForKey: noop,\n dispose: noop,\n clearWebGLCaches: noop,\n\n /**\n * Experimental. This object is a sort of repository of help layers used to avoid\n * of recreating them during frequent filtering. If you are previewing a filter with\n * a slider you probably do not want to create help layers every filter step.\n * in this object there will be appended some canvases, created once, resized sometimes\n * cleared never. Clearing is left to the developer.\n **/\n resources: {\n\n },\n\n /**\n * Apply a set of filters against a source image and draw the filtered output\n * to the provided destination canvas.\n *\n * @param {EnhancedFilter} filters The filter to apply.\n * @param {HTMLImageElement|HTMLCanvasElement} sourceElement The source to be filtered.\n * @param {Number} sourceWidth The width of the source input.\n * @param {Number} sourceHeight The height of the source input.\n * @param {HTMLCanvasElement} targetCanvas The destination for filtered output to be drawn.\n */\n applyFilters: function(filters, sourceElement, sourceWidth, sourceHeight, targetCanvas) {\n var ctx = targetCanvas.getContext('2d');\n ctx.drawImage(sourceElement, 0, 0, sourceWidth, sourceHeight);\n var imageData = ctx.getImageData(0, 0, sourceWidth, sourceHeight);\n var originalImageData = ctx.getImageData(0, 0, sourceWidth, sourceHeight);\n var pipelineState = {\n sourceWidth: sourceWidth,\n sourceHeight: sourceHeight,\n imageData: imageData,\n originalEl: sourceElement,\n originalImageData: originalImageData,\n canvasEl: targetCanvas,\n ctx: ctx,\n filterBackend: this,\n };\n filters.forEach(function(filter) { filter.applyTo(pipelineState); });\n if (pipelineState.imageData.width !== sourceWidth || pipelineState.imageData.height !== sourceHeight) {\n targetCanvas.width = pipelineState.imageData.width;\n targetCanvas.height = pipelineState.imageData.height;\n }\n ctx.putImageData(pipelineState.imageData, 0, 0);\n return pipelineState;\n },\n\n };\n})();\n\n\n/**\n * @namespace fabric.Image.filters\n * @memberOf fabric.Image\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#image_filters}\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n */\nfabric.Image = fabric.Image || { };\nfabric.Image.filters = fabric.Image.filters || { };\n\n/**\n * Root filter class from which all filter classes inherit from\n * @class fabric.Image.filters.BaseFilter\n * @memberOf fabric.Image.filters\n */\nfabric.Image.filters.BaseFilter = fabric.util.createClass(/** @lends fabric.Image.filters.BaseFilter.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'BaseFilter',\n\n /**\n * Array of attributes to send with buffers. do not modify\n * @private\n */\n\n vertexSource: 'attribute vec2 aPosition;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vTexCoord = aPosition;\\n' +\n 'gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\\n' +\n '}',\n\n fragmentSource: 'precision highp float;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'void main() {\\n' +\n 'gl_FragColor = texture2D(uTexture, vTexCoord);\\n' +\n '}',\n\n /**\n * Constructor\n * @param {Object} [options] Options object\n */\n initialize: function(options) {\n if (options) {\n this.setOptions(options);\n }\n },\n\n /**\n * Sets filter's properties from options\n * @param {Object} [options] Options object\n */\n setOptions: function(options) {\n for (var prop in options) {\n this[prop] = options[prop];\n }\n },\n\n /**\n * Compile this filter's shader program.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context to use for shader compilation.\n * @param {String} fragmentSource fragmentShader source for compilation\n * @param {String} vertexSource vertexShader source for compilation\n */\n createProgram: function(gl, fragmentSource, vertexSource) {\n fragmentSource = fragmentSource || this.fragmentSource;\n vertexSource = vertexSource || this.vertexSource;\n if (fabric.webGlPrecision !== 'highp'){\n fragmentSource = fragmentSource.replace(\n /precision highp float/g,\n 'precision ' + fabric.webGlPrecision + ' float'\n );\n }\n var vertexShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertexShader, vertexSource);\n gl.compileShader(vertexShader);\n if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {\n throw new Error(\n // eslint-disable-next-line prefer-template\n 'Vertex shader compile error for ' + this.type + ': ' +\n gl.getShaderInfoLog(vertexShader)\n );\n }\n\n var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragmentShader, fragmentSource);\n gl.compileShader(fragmentShader);\n if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {\n throw new Error(\n // eslint-disable-next-line prefer-template\n 'Fragment shader compile error for ' + this.type + ': ' +\n gl.getShaderInfoLog(fragmentShader)\n );\n }\n\n var program = gl.createProgram();\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n gl.linkProgram(program);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n throw new Error(\n // eslint-disable-next-line prefer-template\n 'Shader link error for \"${this.type}\" ' +\n gl.getProgramInfoLog(program)\n );\n }\n\n var attributeLocations = this.getAttributeLocations(gl, program);\n var uniformLocations = this.getUniformLocations(gl, program) || { };\n uniformLocations.uStepW = gl.getUniformLocation(program, 'uStepW');\n uniformLocations.uStepH = gl.getUniformLocation(program, 'uStepH');\n return {\n program: program,\n attributeLocations: attributeLocations,\n uniformLocations: uniformLocations\n };\n },\n\n /**\n * Return a map of attribute names to WebGLAttributeLocation objects.\n *\n * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.\n * @param {WebGLShaderProgram} program The shader program from which to take attribute locations.\n * @returns {Object} A map of attribute names to attribute locations.\n */\n getAttributeLocations: function(gl, program) {\n return {\n aPosition: gl.getAttribLocation(program, 'aPosition'),\n };\n },\n\n /**\n * Return a map of uniform names to WebGLUniformLocation objects.\n *\n * Intended to be overridden by subclasses.\n *\n * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.\n * @param {WebGLShaderProgram} program The shader program from which to take uniform locations.\n * @returns {Object} A map of uniform names to uniform locations.\n */\n getUniformLocations: function (/* gl, program */) {\n // in case i do not need any special uniform i need to return an empty object\n return { };\n },\n\n /**\n * Send attribute data from this filter to its shader program on the GPU.\n *\n * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.\n * @param {Object} attributeLocations A map of shader attribute names to their locations.\n */\n sendAttributeData: function(gl, attributeLocations, aPositionData) {\n var attributeLocation = attributeLocations.aPosition;\n var buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.enableVertexAttribArray(attributeLocation);\n gl.vertexAttribPointer(attributeLocation, 2, gl.FLOAT, false, 0, 0);\n gl.bufferData(gl.ARRAY_BUFFER, aPositionData, gl.STATIC_DRAW);\n },\n\n _setupFrameBuffer: function(options) {\n var gl = options.context, width, height;\n if (options.passes > 1) {\n width = options.destinationWidth;\n height = options.destinationHeight;\n if (options.sourceWidth !== width || options.sourceHeight !== height) {\n gl.deleteTexture(options.targetTexture);\n options.targetTexture = options.filterBackend.createTexture(gl, width, height);\n }\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D,\n options.targetTexture, 0);\n }\n else {\n // draw last filter on canvas and not to framebuffer.\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.finish();\n }\n },\n\n _swapTextures: function(options) {\n options.passes--;\n options.pass++;\n var temp = options.targetTexture;\n options.targetTexture = options.sourceTexture;\n options.sourceTexture = temp;\n },\n\n /**\n * Generic isNeutral implementation for one parameter based filters.\n * Used only in image applyFilters to discard filters that will not have an effect\n * on the image\n * Other filters may need their own version ( ColorMatrix, HueRotation, gamma, ComposedFilter )\n * @param {Object} options\n **/\n isNeutralState: function(/* options */) {\n var main = this.mainParameter,\n _class = fabric.Image.filters[this.type].prototype;\n if (main) {\n if (Array.isArray(_class[main])) {\n for (var i = _class[main].length; i--;) {\n if (this[main][i] !== _class[main][i]) {\n return false;\n }\n }\n return true;\n }\n else {\n return _class[main] === this[main];\n }\n }\n else {\n return false;\n }\n },\n\n /**\n * Apply this filter to the input image data provided.\n *\n * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.\n *\n * @param {Object} options\n * @param {Number} options.passes The number of filters remaining to be executed\n * @param {Boolean} options.webgl Whether to use webgl to render the filter.\n * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.\n * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n applyTo: function(options) {\n if (options.webgl) {\n this._setupFrameBuffer(options);\n this.applyToWebGL(options);\n this._swapTextures(options);\n }\n else {\n this.applyTo2d(options);\n }\n },\n\n /**\n * Retrieves the cached shader.\n * @param {Object} options\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n retrieveShader: function(options) {\n if (!options.programCache.hasOwnProperty(this.type)) {\n options.programCache[this.type] = this.createProgram(options.context);\n }\n return options.programCache[this.type];\n },\n\n /**\n * Apply this filter using webgl.\n *\n * @param {Object} options\n * @param {Number} options.passes The number of filters remaining to be executed\n * @param {Boolean} options.webgl Whether to use webgl to render the filter.\n * @param {WebGLTexture} options.originalTexture The texture of the original input image.\n * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.\n * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n applyToWebGL: function(options) {\n var gl = options.context;\n var shader = this.retrieveShader(options);\n if (options.pass === 0 && options.originalTexture) {\n gl.bindTexture(gl.TEXTURE_2D, options.originalTexture);\n }\n else {\n gl.bindTexture(gl.TEXTURE_2D, options.sourceTexture);\n }\n gl.useProgram(shader.program);\n this.sendAttributeData(gl, shader.attributeLocations, options.aPosition);\n\n gl.uniform1f(shader.uniformLocations.uStepW, 1 / options.sourceWidth);\n gl.uniform1f(shader.uniformLocations.uStepH, 1 / options.sourceHeight);\n\n this.sendUniformData(gl, shader.uniformLocations);\n gl.viewport(0, 0, options.destinationWidth, options.destinationHeight);\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n },\n\n bindAdditionalTexture: function(gl, texture, textureUnit) {\n gl.activeTexture(textureUnit);\n gl.bindTexture(gl.TEXTURE_2D, texture);\n // reset active texture to 0 as usual\n gl.activeTexture(gl.TEXTURE0);\n },\n\n unbindAdditionalTexture: function(gl, textureUnit) {\n gl.activeTexture(textureUnit);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.activeTexture(gl.TEXTURE0);\n },\n\n getMainParameter: function() {\n return this[this.mainParameter];\n },\n\n setMainParameter: function(value) {\n this[this.mainParameter] = value;\n },\n\n /**\n * Send uniform data from this filter to its shader program on the GPU.\n *\n * Intended to be overridden by subclasses.\n *\n * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.\n * @param {Object} uniformLocations A map of shader uniform names to their locations.\n */\n sendUniformData: function(/* gl, uniformLocations */) {\n // Intentionally left blank. Override me in subclasses.\n },\n\n /**\n * If needed by a 2d filter, this functions can create an helper canvas to be used\n * remember that options.targetCanvas is available for use till end of chain.\n */\n createHelpLayer: function(options) {\n if (!options.helpLayer) {\n var helpLayer = document.createElement('canvas');\n helpLayer.width = options.sourceWidth;\n helpLayer.height = options.sourceHeight;\n options.helpLayer = helpLayer;\n }\n },\n\n /**\n * Returns object representation of an instance\n * @return {Object} Object representation of an instance\n */\n toObject: function() {\n var object = { type: this.type }, mainP = this.mainParameter;\n if (mainP) {\n object[mainP] = this[mainP];\n }\n return object;\n },\n\n /**\n * Returns a JSON representation of an instance\n * @return {Object} JSON\n */\n toJSON: function() {\n // delegate, not alias\n return this.toObject();\n }\n});\n\nfabric.Image.filters.BaseFilter.fromObject = function(object, callback) {\n var filter = new fabric.Image.filters[object.type](object);\n callback && callback(filter);\n return filter;\n};\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Color Matrix filter class\n * @class fabric.Image.filters.ColorMatrix\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.ColorMatrix#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @see {@Link http://www.webwasp.co.uk/tutorials/219/Color_Matrix_Filter.php}\n * @see {@Link http://phoboslab.org/log/2013/11/fast-image-filters-with-webgl}\n * @example Kodachrome filter\n * var filter = new fabric.Image.filters.ColorMatrix({\n * matrix: [\n 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,\n -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,\n -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,\n 0, 0, 0, 1, 0\n ]\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.ColorMatrix = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.ColorMatrix.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'ColorMatrix',\n\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'uniform mat4 uColorMatrix;\\n' +\n 'uniform vec4 uConstants;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'color *= uColorMatrix;\\n' +\n 'color += uConstants;\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n\n /**\n * Colormatrix for pixels.\n * array of 20 floats. Numbers in positions 4, 9, 14, 19 loose meaning\n * outside the -1, 1 range.\n * 0.0039215686 is the part of 1 that get translated to 1 in 2d\n * @param {Array} matrix array of 20 numbers.\n * @default\n */\n matrix: [\n 1, 0, 0, 0, 0,\n 0, 1, 0, 0, 0,\n 0, 0, 1, 0, 0,\n 0, 0, 0, 1, 0\n ],\n\n mainParameter: 'matrix',\n\n /**\n * Lock the colormatrix on the color part, skipping alpha, mainly for non webgl scenario\n * to save some calculation\n * @type Boolean\n * @default true\n */\n colorsOnly: true,\n\n /**\n * Constructor\n * @param {Object} [options] Options object\n */\n initialize: function(options) {\n this.callSuper('initialize', options);\n // create a new array instead mutating the prototype with push\n this.matrix = this.matrix.slice(0);\n },\n\n /**\n * Apply the ColorMatrix operation to a Uint8Array representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8Array to be filtered.\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n data = imageData.data,\n iLen = data.length,\n m = this.matrix,\n r, g, b, a, i, colorsOnly = this.colorsOnly;\n\n for (i = 0; i < iLen; i += 4) {\n r = data[i];\n g = data[i + 1];\n b = data[i + 2];\n if (colorsOnly) {\n data[i] = r * m[0] + g * m[1] + b * m[2] + m[4] * 255;\n data[i + 1] = r * m[5] + g * m[6] + b * m[7] + m[9] * 255;\n data[i + 2] = r * m[10] + g * m[11] + b * m[12] + m[14] * 255;\n }\n else {\n a = data[i + 3];\n data[i] = r * m[0] + g * m[1] + b * m[2] + a * m[3] + m[4] * 255;\n data[i + 1] = r * m[5] + g * m[6] + b * m[7] + a * m[8] + m[9] * 255;\n data[i + 2] = r * m[10] + g * m[11] + b * m[12] + a * m[13] + m[14] * 255;\n data[i + 3] = r * m[15] + g * m[16] + b * m[17] + a * m[18] + m[19] * 255;\n }\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uColorMatrix: gl.getUniformLocation(program, 'uColorMatrix'),\n uConstants: gl.getUniformLocation(program, 'uConstants'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n var m = this.matrix,\n matrix = [\n m[0], m[1], m[2], m[3],\n m[5], m[6], m[7], m[8],\n m[10], m[11], m[12], m[13],\n m[15], m[16], m[17], m[18]\n ],\n constants = [m[4], m[9], m[14], m[19]];\n gl.uniformMatrix4fv(uniformLocations.uColorMatrix, false, matrix);\n gl.uniform4fv(uniformLocations.uConstants, constants);\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] function to invoke after filter creation\n * @return {fabric.Image.filters.ColorMatrix} Instance of fabric.Image.filters.ColorMatrix\n */\n fabric.Image.filters.ColorMatrix.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Brightness filter class\n * @class fabric.Image.filters.Brightness\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Brightness#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Brightness({\n * brightness: 0.05\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.Brightness = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Brightness.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Brightness',\n\n /**\n * Fragment source for the brightness program\n */\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uBrightness;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'color.rgb += uBrightness;\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n\n /**\n * Brightness value, from -1 to 1.\n * translated to -255 to 255 for 2d\n * 0.0039215686 is the part of 1 that get translated to 1 in 2d\n * @param {Number} brightness\n * @default\n */\n brightness: 0,\n\n /**\n * Describe the property that is the filter parameter\n * @param {String} m\n * @default\n */\n mainParameter: 'brightness',\n\n /**\n * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.\n */\n applyTo2d: function(options) {\n if (this.brightness === 0) {\n return;\n }\n var imageData = options.imageData,\n data = imageData.data, i, len = data.length,\n brightness = Math.round(this.brightness * 255);\n for (i = 0; i < len; i += 4) {\n data[i] = data[i] + brightness;\n data[i + 1] = data[i + 1] + brightness;\n data[i + 2] = data[i + 2] + brightness;\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uBrightness: gl.getUniformLocation(program, 'uBrightness'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform1f(uniformLocations.uBrightness, this.brightness);\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Brightness} Instance of fabric.Image.filters.Brightness\n */\n fabric.Image.filters.Brightness.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n extend = fabric.util.object.extend,\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Adapted from html5rocks article\n * @class fabric.Image.filters.Convolute\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Convolute#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example Sharpen filter\n * var filter = new fabric.Image.filters.Convolute({\n * matrix: [ 0, -1, 0,\n * -1, 5, -1,\n * 0, -1, 0 ]\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n * @example Blur filter\n * var filter = new fabric.Image.filters.Convolute({\n * matrix: [ 1/9, 1/9, 1/9,\n * 1/9, 1/9, 1/9,\n * 1/9, 1/9, 1/9 ]\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n * @example Emboss filter\n * var filter = new fabric.Image.filters.Convolute({\n * matrix: [ 1, 1, 1,\n * 1, 0.7, -1,\n * -1, -1, -1 ]\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n * @example Emboss filter with opaqueness\n * var filter = new fabric.Image.filters.Convolute({\n * opaque: true,\n * matrix: [ 1, 1, 1,\n * 1, 0.7, -1,\n * -1, -1, -1 ]\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n */\n filters.Convolute = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Convolute.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Convolute',\n\n /*\n * Opaque value (true/false)\n */\n opaque: false,\n\n /*\n * matrix for the filter, max 9x9\n */\n matrix: [0, 0, 0, 0, 1, 0, 0, 0, 0],\n\n /**\n * Fragment source for the brightness program\n */\n fragmentSource: {\n Convolute_3_1: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uMatrix[9];\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0, 0, 0, 0);\\n' +\n 'for (float h = 0.0; h < 3.0; h+=1.0) {\\n' +\n 'for (float w = 0.0; w < 3.0; w+=1.0) {\\n' +\n 'vec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\\n' +\n 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\\n' +\n '}\\n' +\n '}\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n Convolute_3_0: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uMatrix[9];\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0, 0, 0, 1);\\n' +\n 'for (float h = 0.0; h < 3.0; h+=1.0) {\\n' +\n 'for (float w = 0.0; w < 3.0; w+=1.0) {\\n' +\n 'vec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\\n' +\n 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\\n' +\n '}\\n' +\n '}\\n' +\n 'float alpha = texture2D(uTexture, vTexCoord).a;\\n' +\n 'gl_FragColor = color;\\n' +\n 'gl_FragColor.a = alpha;\\n' +\n '}',\n Convolute_5_1: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uMatrix[25];\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0, 0, 0, 0);\\n' +\n 'for (float h = 0.0; h < 5.0; h+=1.0) {\\n' +\n 'for (float w = 0.0; w < 5.0; w+=1.0) {\\n' +\n 'vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\\n' +\n 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\\n' +\n '}\\n' +\n '}\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n Convolute_5_0: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uMatrix[25];\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0, 0, 0, 1);\\n' +\n 'for (float h = 0.0; h < 5.0; h+=1.0) {\\n' +\n 'for (float w = 0.0; w < 5.0; w+=1.0) {\\n' +\n 'vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\\n' +\n 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\\n' +\n '}\\n' +\n '}\\n' +\n 'float alpha = texture2D(uTexture, vTexCoord).a;\\n' +\n 'gl_FragColor = color;\\n' +\n 'gl_FragColor.a = alpha;\\n' +\n '}',\n Convolute_7_1: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uMatrix[49];\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0, 0, 0, 0);\\n' +\n 'for (float h = 0.0; h < 7.0; h+=1.0) {\\n' +\n 'for (float w = 0.0; w < 7.0; w+=1.0) {\\n' +\n 'vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\\n' +\n 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\\n' +\n '}\\n' +\n '}\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n Convolute_7_0: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uMatrix[49];\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0, 0, 0, 1);\\n' +\n 'for (float h = 0.0; h < 7.0; h+=1.0) {\\n' +\n 'for (float w = 0.0; w < 7.0; w+=1.0) {\\n' +\n 'vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\\n' +\n 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\\n' +\n '}\\n' +\n '}\\n' +\n 'float alpha = texture2D(uTexture, vTexCoord).a;\\n' +\n 'gl_FragColor = color;\\n' +\n 'gl_FragColor.a = alpha;\\n' +\n '}',\n Convolute_9_1: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uMatrix[81];\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0, 0, 0, 0);\\n' +\n 'for (float h = 0.0; h < 9.0; h+=1.0) {\\n' +\n 'for (float w = 0.0; w < 9.0; w+=1.0) {\\n' +\n 'vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\\n' +\n 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\\n' +\n '}\\n' +\n '}\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n Convolute_9_0: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uMatrix[81];\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0, 0, 0, 1);\\n' +\n 'for (float h = 0.0; h < 9.0; h+=1.0) {\\n' +\n 'for (float w = 0.0; w < 9.0; w+=1.0) {\\n' +\n 'vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\\n' +\n 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\\n' +\n '}\\n' +\n '}\\n' +\n 'float alpha = texture2D(uTexture, vTexCoord).a;\\n' +\n 'gl_FragColor = color;\\n' +\n 'gl_FragColor.a = alpha;\\n' +\n '}',\n },\n\n /**\n * Constructor\n * @memberOf fabric.Image.filters.Convolute.prototype\n * @param {Object} [options] Options object\n * @param {Boolean} [options.opaque=false] Opaque value (true/false)\n * @param {Array} [options.matrix] Filter matrix\n */\n\n\n /**\n * Retrieves the cached shader.\n * @param {Object} options\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n retrieveShader: function(options) {\n var size = Math.sqrt(this.matrix.length);\n var cacheKey = this.type + '_' + size + '_' + (this.opaque ? 1 : 0);\n var shaderSource = this.fragmentSource[cacheKey];\n if (!options.programCache.hasOwnProperty(cacheKey)) {\n options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);\n }\n return options.programCache[cacheKey];\n },\n\n /**\n * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n data = imageData.data,\n weights = this.matrix,\n side = Math.round(Math.sqrt(weights.length)),\n halfSide = Math.floor(side / 2),\n sw = imageData.width,\n sh = imageData.height,\n output = options.ctx.createImageData(sw, sh),\n dst = output.data,\n // go through the destination image pixels\n alphaFac = this.opaque ? 1 : 0,\n r, g, b, a, dstOff,\n scx, scy, srcOff, wt,\n x, y, cx, cy;\n\n for (y = 0; y < sh; y++) {\n for (x = 0; x < sw; x++) {\n dstOff = (y * sw + x) * 4;\n // calculate the weighed sum of the source image pixels that\n // fall under the convolution matrix\n r = 0; g = 0; b = 0; a = 0;\n\n for (cy = 0; cy < side; cy++) {\n for (cx = 0; cx < side; cx++) {\n scy = y + cy - halfSide;\n scx = x + cx - halfSide;\n\n // eslint-disable-next-line max-depth\n if (scy < 0 || scy >= sh || scx < 0 || scx >= sw) {\n continue;\n }\n\n srcOff = (scy * sw + scx) * 4;\n wt = weights[cy * side + cx];\n\n r += data[srcOff] * wt;\n g += data[srcOff + 1] * wt;\n b += data[srcOff + 2] * wt;\n // eslint-disable-next-line max-depth\n if (!alphaFac) {\n a += data[srcOff + 3] * wt;\n }\n }\n }\n dst[dstOff] = r;\n dst[dstOff + 1] = g;\n dst[dstOff + 2] = b;\n if (!alphaFac) {\n dst[dstOff + 3] = a;\n }\n else {\n dst[dstOff + 3] = data[dstOff + 3];\n }\n }\n }\n options.imageData = output;\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uMatrix: gl.getUniformLocation(program, 'uMatrix'),\n uOpaque: gl.getUniformLocation(program, 'uOpaque'),\n uHalfSize: gl.getUniformLocation(program, 'uHalfSize'),\n uSize: gl.getUniformLocation(program, 'uSize'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform1fv(uniformLocations.uMatrix, this.matrix);\n },\n\n /**\n * Returns object representation of an instance\n * @return {Object} Object representation of an instance\n */\n toObject: function() {\n return extend(this.callSuper('toObject'), {\n opaque: this.opaque,\n matrix: this.matrix\n });\n }\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Convolute} Instance of fabric.Image.filters.Convolute\n */\n fabric.Image.filters.Convolute.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Grayscale image filter class\n * @class fabric.Image.filters.Grayscale\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Grayscale();\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.Grayscale = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Grayscale.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Grayscale',\n\n fragmentSource: {\n average: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'float average = (color.r + color.b + color.g) / 3.0;\\n' +\n 'gl_FragColor = vec4(average, average, average, color.a);\\n' +\n '}',\n lightness: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform int uMode;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 col = texture2D(uTexture, vTexCoord);\\n' +\n 'float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\\n' +\n 'gl_FragColor = vec4(average, average, average, col.a);\\n' +\n '}',\n luminosity: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform int uMode;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 col = texture2D(uTexture, vTexCoord);\\n' +\n 'float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\\n' +\n 'gl_FragColor = vec4(average, average, average, col.a);\\n' +\n '}',\n },\n\n\n /**\n * Grayscale mode, between 'average', 'lightness', 'luminosity'\n * @param {String} type\n * @default\n */\n mode: 'average',\n\n mainParameter: 'mode',\n\n /**\n * Apply the Grayscale operation to a Uint8Array representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8Array to be filtered.\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n data = imageData.data, i,\n len = data.length, value,\n mode = this.mode;\n for (i = 0; i < len; i += 4) {\n if (mode === 'average') {\n value = (data[i] + data[i + 1] + data[i + 2]) / 3;\n }\n else if (mode === 'lightness') {\n value = (Math.min(data[i], data[i + 1], data[i + 2]) +\n Math.max(data[i], data[i + 1], data[i + 2])) / 2;\n }\n else if (mode === 'luminosity') {\n value = 0.21 * data[i] + 0.72 * data[i + 1] + 0.07 * data[i + 2];\n }\n data[i] = value;\n data[i + 1] = value;\n data[i + 2] = value;\n }\n },\n\n /**\n * Retrieves the cached shader.\n * @param {Object} options\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n retrieveShader: function(options) {\n var cacheKey = this.type + '_' + this.mode;\n if (!options.programCache.hasOwnProperty(cacheKey)) {\n var shaderSource = this.fragmentSource[this.mode];\n options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);\n }\n return options.programCache[cacheKey];\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uMode: gl.getUniformLocation(program, 'uMode'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n // default average mode.\n var mode = 1;\n gl.uniform1i(uniformLocations.uMode, mode);\n },\n\n /**\n * Grayscale filter isNeutralState implementation\n * The filter is never neutral\n * on the image\n **/\n isNeutralState: function() {\n return false;\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Grayscale} Instance of fabric.Image.filters.Grayscale\n */\n fabric.Image.filters.Grayscale.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Invert filter class\n * @class fabric.Image.filters.Invert\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Invert();\n * object.filters.push(filter);\n * object.applyFilters(canvas.renderAll.bind(canvas));\n */\n filters.Invert = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Invert.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Invert',\n\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform int uInvert;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'if (uInvert == 1) {\\n' +\n 'gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\\n' +\n '} else {\\n' +\n 'gl_FragColor = color;\\n' +\n '}\\n' +\n '}',\n\n /**\n * Filter invert. if false, does nothing\n * @param {Boolean} invert\n * @default\n */\n invert: true,\n\n mainParameter: 'invert',\n\n /**\n * Apply the Invert operation to a Uint8Array representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8Array to be filtered.\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n data = imageData.data, i,\n len = data.length;\n for (i = 0; i < len; i += 4) {\n data[i] = 255 - data[i];\n data[i + 1] = 255 - data[i + 1];\n data[i + 2] = 255 - data[i + 2];\n }\n },\n\n /**\n * Invert filter isNeutralState implementation\n * Used only in image applyFilters to discard filters that will not have an effect\n * on the image\n * @param {Object} options\n **/\n isNeutralState: function() {\n return !this.invert;\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uInvert: gl.getUniformLocation(program, 'uInvert'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform1i(uniformLocations.uInvert, this.invert);\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Invert} Instance of fabric.Image.filters.Invert\n */\n fabric.Image.filters.Invert.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n extend = fabric.util.object.extend,\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Noise filter class\n * @class fabric.Image.filters.Noise\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Noise#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Noise({\n * noise: 700\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n */\n filters.Noise = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Noise.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Noise',\n\n /**\n * Fragment source for the noise program\n */\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uStepH;\\n' +\n 'uniform float uNoise;\\n' +\n 'uniform float uSeed;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'float rand(vec2 co, float seed, float vScale) {\\n' +\n 'return fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\\n' +\n '}\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n\n /**\n * Describe the property that is the filter parameter\n * @param {String} m\n * @default\n */\n mainParameter: 'noise',\n\n /**\n * Noise value, from\n * @param {Number} noise\n * @default\n */\n noise: 0,\n\n /**\n * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.\n */\n applyTo2d: function(options) {\n if (this.noise === 0) {\n return;\n }\n var imageData = options.imageData,\n data = imageData.data, i, len = data.length,\n noise = this.noise, rand;\n\n for (i = 0, len = data.length; i < len; i += 4) {\n\n rand = (0.5 - Math.random()) * noise;\n\n data[i] += rand;\n data[i + 1] += rand;\n data[i + 2] += rand;\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uNoise: gl.getUniformLocation(program, 'uNoise'),\n uSeed: gl.getUniformLocation(program, 'uSeed'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform1f(uniformLocations.uNoise, this.noise / 255);\n gl.uniform1f(uniformLocations.uSeed, Math.random());\n },\n\n /**\n * Returns object representation of an instance\n * @return {Object} Object representation of an instance\n */\n toObject: function() {\n return extend(this.callSuper('toObject'), {\n noise: this.noise\n });\n }\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Noise} Instance of fabric.Image.filters.Noise\n */\n fabric.Image.filters.Noise.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Pixelate filter class\n * @class fabric.Image.filters.Pixelate\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Pixelate#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Pixelate({\n * blocksize: 8\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.Pixelate = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Pixelate.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Pixelate',\n\n blocksize: 4,\n\n mainParameter: 'blocksize',\n\n /**\n * Fragment source for the Pixelate program\n */\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uBlocksize;\\n' +\n 'uniform float uStepW;\\n' +\n 'uniform float uStepH;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'float blockW = uBlocksize * uStepW;\\n' +\n 'float blockH = uBlocksize * uStepW;\\n' +\n 'int posX = int(vTexCoord.x / blockW);\\n' +\n 'int posY = int(vTexCoord.y / blockH);\\n' +\n 'float fposX = float(posX);\\n' +\n 'float fposY = float(posY);\\n' +\n 'vec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\\n' +\n 'vec4 color = texture2D(uTexture, squareCoords);\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n\n /**\n * Apply the Pixelate operation to a Uint8ClampedArray representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n data = imageData.data,\n iLen = imageData.height,\n jLen = imageData.width,\n index, i, j, r, g, b, a,\n _i, _j, _iLen, _jLen;\n\n for (i = 0; i < iLen; i += this.blocksize) {\n for (j = 0; j < jLen; j += this.blocksize) {\n\n index = (i * 4) * jLen + (j * 4);\n\n r = data[index];\n g = data[index + 1];\n b = data[index + 2];\n a = data[index + 3];\n\n _iLen = Math.min(i + this.blocksize, iLen);\n _jLen = Math.min(j + this.blocksize, jLen);\n for (_i = i; _i < _iLen; _i++) {\n for (_j = j; _j < _jLen; _j++) {\n index = (_i * 4) * jLen + (_j * 4);\n data[index] = r;\n data[index + 1] = g;\n data[index + 2] = b;\n data[index + 3] = a;\n }\n }\n }\n }\n },\n\n /**\n * Indicate when the filter is not gonna apply changes to the image\n **/\n isNeutralState: function() {\n return this.blocksize === 1;\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uBlocksize: gl.getUniformLocation(program, 'uBlocksize'),\n uStepW: gl.getUniformLocation(program, 'uStepW'),\n uStepH: gl.getUniformLocation(program, 'uStepH'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform1f(uniformLocations.uBlocksize, this.blocksize);\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Pixelate} Instance of fabric.Image.filters.Pixelate\n */\n fabric.Image.filters.Pixelate.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n extend = fabric.util.object.extend,\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Remove white filter class\n * @class fabric.Image.filters.RemoveColor\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.RemoveColor#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.RemoveColor({\n * threshold: 0.2,\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n */\n filters.RemoveColor = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.RemoveColor.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'RemoveColor',\n\n /**\n * Color to remove, in any format understood by fabric.Color.\n * @param {String} type\n * @default\n */\n color: '#FFFFFF',\n\n /**\n * Fragment source for the brightness program\n */\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform vec4 uLow;\\n' +\n 'uniform vec4 uHigh;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'gl_FragColor = texture2D(uTexture, vTexCoord);\\n' +\n 'if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\\n' +\n 'gl_FragColor.a = 0.0;\\n' +\n '}\\n' +\n '}',\n\n /**\n * distance to actual color, as value up or down from each r,g,b\n * between 0 and 1\n **/\n distance: 0.02,\n\n /**\n * For color to remove inside distance, use alpha channel for a smoother deletion\n * NOT IMPLEMENTED YET\n **/\n useAlpha: false,\n\n /**\n * Constructor\n * @memberOf fabric.Image.filters.RemoveWhite.prototype\n * @param {Object} [options] Options object\n * @param {Number} [options.color=#RRGGBB] Threshold value\n * @param {Number} [options.distance=10] Distance value\n */\n\n /**\n * Applies filter to canvas element\n * @param {Object} canvasEl Canvas element to apply filter to\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n data = imageData.data, i,\n distance = this.distance * 255,\n r, g, b,\n source = new fabric.Color(this.color).getSource(),\n lowC = [\n source[0] - distance,\n source[1] - distance,\n source[2] - distance,\n ],\n highC = [\n source[0] + distance,\n source[1] + distance,\n source[2] + distance,\n ];\n\n\n for (i = 0; i < data.length; i += 4) {\n r = data[i];\n g = data[i + 1];\n b = data[i + 2];\n\n if (r > lowC[0] &&\n g > lowC[1] &&\n b > lowC[2] &&\n r < highC[0] &&\n g < highC[1] &&\n b < highC[2]) {\n data[i + 3] = 0;\n }\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uLow: gl.getUniformLocation(program, 'uLow'),\n uHigh: gl.getUniformLocation(program, 'uHigh'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n var source = new fabric.Color(this.color).getSource(),\n distance = parseFloat(this.distance),\n lowC = [\n 0 + source[0] / 255 - distance,\n 0 + source[1] / 255 - distance,\n 0 + source[2] / 255 - distance,\n 1\n ],\n highC = [\n source[0] / 255 + distance,\n source[1] / 255 + distance,\n source[2] / 255 + distance,\n 1\n ];\n gl.uniform4fv(uniformLocations.uLow, lowC);\n gl.uniform4fv(uniformLocations.uHigh, highC);\n },\n\n /**\n * Returns object representation of an instance\n * @return {Object} Object representation of an instance\n */\n toObject: function() {\n return extend(this.callSuper('toObject'), {\n color: this.color,\n distance: this.distance\n });\n }\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.RemoveColor} Instance of fabric.Image.filters.RemoveWhite\n */\n fabric.Image.filters.RemoveColor.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n var matrices = {\n Brownie: [\n 0.59970,0.34553,-0.27082,0,0.186,\n -0.03770,0.86095,0.15059,0,-0.1449,\n 0.24113,-0.07441,0.44972,0,-0.02965,\n 0,0,0,1,0\n ],\n Vintage: [\n 0.62793,0.32021,-0.03965,0,0.03784,\n 0.02578,0.64411,0.03259,0,0.02926,\n 0.04660,-0.08512,0.52416,0,0.02023,\n 0,0,0,1,0\n ],\n Kodachrome: [\n 1.12855,-0.39673,-0.03992,0,0.24991,\n -0.16404,1.08352,-0.05498,0,0.09698,\n -0.16786,-0.56034,1.60148,0,0.13972,\n 0,0,0,1,0\n ],\n Technicolor: [\n 1.91252,-0.85453,-0.09155,0,0.04624,\n -0.30878,1.76589,-0.10601,0,-0.27589,\n -0.23110,-0.75018,1.84759,0,0.12137,\n 0,0,0,1,0\n ],\n Polaroid: [\n 1.438,-0.062,-0.062,0,0,\n -0.122,1.378,-0.122,0,0,\n -0.016,-0.016,1.483,0,0,\n 0,0,0,1,0\n ],\n Sepia: [\n 0.393, 0.769, 0.189, 0, 0,\n 0.349, 0.686, 0.168, 0, 0,\n 0.272, 0.534, 0.131, 0, 0,\n 0, 0, 0, 1, 0\n ],\n BlackWhite: [\n 1.5, 1.5, 1.5, 0, -1,\n 1.5, 1.5, 1.5, 0, -1,\n 1.5, 1.5, 1.5, 0, -1,\n 0, 0, 0, 1, 0,\n ]\n };\n\n for (var key in matrices) {\n filters[key] = createClass(filters.ColorMatrix, /** @lends fabric.Image.filters.Sepia.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: key,\n\n /**\n * Colormatrix for the effect\n * array of 20 floats. Numbers in positions 4, 9, 14, 19 loose meaning\n * outside the -1, 1 range.\n * @param {Array} matrix array of 20 numbers.\n * @default\n */\n matrix: matrices[key],\n\n /**\n * Lock the matrix export for this kind of static, parameter less filters.\n */\n mainParameter: false,\n /**\n * Lock the colormatrix on the color part, skipping alpha\n */\n colorsOnly: true,\n\n });\n fabric.Image.filters[key].fromObject = fabric.Image.filters.BaseFilter.fromObject;\n }\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n 'use strict';\n\n var fabric = global.fabric,\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Color Blend filter class\n * @class fabric.Image.filter.BlendColor\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @example\n * var filter = new fabric.Image.filters.BlendColor({\n * color: '#000',\n * mode: 'multiply'\n * });\n *\n * var filter = new fabric.Image.filters.BlendImage({\n * image: fabricImageObject,\n * mode: 'multiply',\n * alpha: 0.5\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n */\n\n filters.BlendColor = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Blend.prototype */ {\n type: 'BlendColor',\n\n /**\n * Color to make the blend operation with. default to a reddish color since black or white\n * gives always strong result.\n * @type String\n * @default\n **/\n color: '#F95C63',\n\n /**\n * Blend mode for the filter: one of multiply, add, diff, screen, subtract,\n * darken, lighten, overlay, exclusion, tint.\n * @type String\n * @default\n **/\n mode: 'multiply',\n\n /**\n * alpha value. represent the strength of the blend color operation.\n * @type Number\n * @default\n **/\n alpha: 1,\n\n /**\n * Fragment source for the Multiply program\n */\n fragmentSource: {\n multiply: 'gl_FragColor.rgb *= uColor.rgb;\\n',\n screen: 'gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\\n',\n add: 'gl_FragColor.rgb += uColor.rgb;\\n',\n diff: 'gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\\n',\n subtract: 'gl_FragColor.rgb -= uColor.rgb;\\n',\n lighten: 'gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\\n',\n darken: 'gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\\n',\n exclusion: 'gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\\n',\n overlay: 'if (uColor.r < 0.5) {\\n' +\n 'gl_FragColor.r *= 2.0 * uColor.r;\\n' +\n '} else {\\n' +\n 'gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\\n' +\n '}\\n' +\n 'if (uColor.g < 0.5) {\\n' +\n 'gl_FragColor.g *= 2.0 * uColor.g;\\n' +\n '} else {\\n' +\n 'gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\\n' +\n '}\\n' +\n 'if (uColor.b < 0.5) {\\n' +\n 'gl_FragColor.b *= 2.0 * uColor.b;\\n' +\n '} else {\\n' +\n 'gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\\n' +\n '}\\n',\n tint: 'gl_FragColor.rgb *= (1.0 - uColor.a);\\n' +\n 'gl_FragColor.rgb += uColor.rgb;\\n',\n },\n\n /**\n * build the fragment source for the filters, joining the common part with\n * the specific one.\n * @param {String} mode the mode of the filter, a key of this.fragmentSource\n * @return {String} the source to be compiled\n * @private\n */\n buildSource: function(mode) {\n return 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform vec4 uColor;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'gl_FragColor = color;\\n' +\n 'if (color.a > 0.0) {\\n' +\n this.fragmentSource[mode] +\n '}\\n' +\n '}';\n },\n\n /**\n * Retrieves the cached shader.\n * @param {Object} options\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n retrieveShader: function(options) {\n var cacheKey = this.type + '_' + this.mode, shaderSource;\n if (!options.programCache.hasOwnProperty(cacheKey)) {\n shaderSource = this.buildSource(this.mode);\n options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);\n }\n return options.programCache[cacheKey];\n },\n\n /**\n * Apply the Blend operation to a Uint8ClampedArray representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n data = imageData.data, iLen = data.length,\n tr, tg, tb,\n r, g, b,\n source, alpha1 = 1 - this.alpha;\n\n source = new fabric.Color(this.color).getSource();\n tr = source[0] * this.alpha;\n tg = source[1] * this.alpha;\n tb = source[2] * this.alpha;\n\n for (var i = 0; i < iLen; i += 4) {\n\n r = data[i];\n g = data[i + 1];\n b = data[i + 2];\n\n switch (this.mode) {\n case 'multiply':\n data[i] = r * tr / 255;\n data[i + 1] = g * tg / 255;\n data[i + 2] = b * tb / 255;\n break;\n case 'screen':\n data[i] = 255 - (255 - r) * (255 - tr) / 255;\n data[i + 1] = 255 - (255 - g) * (255 - tg) / 255;\n data[i + 2] = 255 - (255 - b) * (255 - tb) / 255;\n break;\n case 'add':\n data[i] = r + tr;\n data[i + 1] = g + tg;\n data[i + 2] = b + tb;\n break;\n case 'diff':\n case 'difference':\n data[i] = Math.abs(r - tr);\n data[i + 1] = Math.abs(g - tg);\n data[i + 2] = Math.abs(b - tb);\n break;\n case 'subtract':\n data[i] = r - tr;\n data[i + 1] = g - tg;\n data[i + 2] = b - tb;\n break;\n case 'darken':\n data[i] = Math.min(r, tr);\n data[i + 1] = Math.min(g, tg);\n data[i + 2] = Math.min(b, tb);\n break;\n case 'lighten':\n data[i] = Math.max(r, tr);\n data[i + 1] = Math.max(g, tg);\n data[i + 2] = Math.max(b, tb);\n break;\n case 'overlay':\n data[i] = tr < 128 ? (2 * r * tr / 255) : (255 - 2 * (255 - r) * (255 - tr) / 255);\n data[i + 1] = tg < 128 ? (2 * g * tg / 255) : (255 - 2 * (255 - g) * (255 - tg) / 255);\n data[i + 2] = tb < 128 ? (2 * b * tb / 255) : (255 - 2 * (255 - b) * (255 - tb) / 255);\n break;\n case 'exclusion':\n data[i] = tr + r - ((2 * tr * r) / 255);\n data[i + 1] = tg + g - ((2 * tg * g) / 255);\n data[i + 2] = tb + b - ((2 * tb * b) / 255);\n break;\n case 'tint':\n data[i] = tr + r * alpha1;\n data[i + 1] = tg + g * alpha1;\n data[i + 2] = tb + b * alpha1;\n }\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uColor: gl.getUniformLocation(program, 'uColor'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n var source = new fabric.Color(this.color).getSource();\n source[0] = this.alpha * source[0] / 255;\n source[1] = this.alpha * source[1] / 255;\n source[2] = this.alpha * source[2] / 255;\n source[3] = this.alpha;\n gl.uniform4fv(uniformLocations.uColor, source);\n },\n\n /**\n * Returns object representation of an instance\n * @return {Object} Object representation of an instance\n */\n toObject: function() {\n return {\n type: this.type,\n color: this.color,\n mode: this.mode,\n alpha: this.alpha\n };\n }\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.BlendColor} Instance of fabric.Image.filters.BlendColor\n */\n fabric.Image.filters.BlendColor.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n 'use strict';\n\n var fabric = global.fabric,\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Image Blend filter class\n * @class fabric.Image.filter.BlendImage\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @example\n * var filter = new fabric.Image.filters.BlendColor({\n * color: '#000',\n * mode: 'multiply'\n * });\n *\n * var filter = new fabric.Image.filters.BlendImage({\n * image: fabricImageObject,\n * mode: 'multiply',\n * alpha: 0.5\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n */\n\n filters.BlendImage = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.BlendImage.prototype */ {\n type: 'BlendImage',\n\n /**\n * Color to make the blend operation with. default to a reddish color since black or white\n * gives always strong result.\n **/\n image: null,\n\n /**\n * Blend mode for the filter (one of \"multiply\", \"mask\")\n * @type String\n * @default\n **/\n mode: 'multiply',\n\n /**\n * alpha value. represent the strength of the blend image operation.\n * not implemented.\n **/\n alpha: 1,\n\n vertexSource: 'attribute vec2 aPosition;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'varying vec2 vTexCoord2;\\n' +\n 'uniform mat3 uTransformMatrix;\\n' +\n 'void main() {\\n' +\n 'vTexCoord = aPosition;\\n' +\n 'vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\\n' +\n 'gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\\n' +\n '}',\n\n /**\n * Fragment source for the Multiply program\n */\n fragmentSource: {\n multiply: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform sampler2D uImage;\\n' +\n 'uniform vec4 uColor;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'varying vec2 vTexCoord2;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'vec4 color2 = texture2D(uImage, vTexCoord2);\\n' +\n 'color.rgba *= color2.rgba;\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n mask: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform sampler2D uImage;\\n' +\n 'uniform vec4 uColor;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'varying vec2 vTexCoord2;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'vec4 color2 = texture2D(uImage, vTexCoord2);\\n' +\n 'color.a = color2.a;\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n },\n\n /**\n * Retrieves the cached shader.\n * @param {Object} options\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n retrieveShader: function(options) {\n var cacheKey = this.type + '_' + this.mode;\n var shaderSource = this.fragmentSource[this.mode];\n if (!options.programCache.hasOwnProperty(cacheKey)) {\n options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);\n }\n return options.programCache[cacheKey];\n },\n\n applyToWebGL: function(options) {\n // load texture to blend.\n var gl = options.context,\n texture = this.createTexture(options.filterBackend, this.image);\n this.bindAdditionalTexture(gl, texture, gl.TEXTURE1);\n this.callSuper('applyToWebGL', options);\n this.unbindAdditionalTexture(gl, gl.TEXTURE1);\n },\n\n createTexture: function(backend, image) {\n return backend.getCachedTexture(image.cacheKey, image._element);\n },\n\n /**\n * Calculate a transformMatrix to adapt the image to blend over\n * @param {Object} options\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n calculateMatrix: function() {\n var image = this.image,\n width = image._element.width,\n height = image._element.height;\n return [\n 1 / image.scaleX, 0, 0,\n 0, 1 / image.scaleY, 0,\n -image.left / width, -image.top / height, 1\n ];\n },\n\n /**\n * Apply the Blend operation to a Uint8ClampedArray representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n resources = options.filterBackend.resources,\n data = imageData.data, iLen = data.length,\n width = imageData.width,\n height = imageData.height,\n tr, tg, tb, ta,\n r, g, b, a,\n canvas1, context, image = this.image, blendData;\n\n if (!resources.blendImage) {\n resources.blendImage = fabric.util.createCanvasElement();\n }\n canvas1 = resources.blendImage;\n context = canvas1.getContext('2d');\n if (canvas1.width !== width || canvas1.height !== height) {\n canvas1.width = width;\n canvas1.height = height;\n }\n else {\n context.clearRect(0, 0, width, height);\n }\n context.setTransform(image.scaleX, 0, 0, image.scaleY, image.left, image.top);\n context.drawImage(image._element, 0, 0, width, height);\n blendData = context.getImageData(0, 0, width, height).data;\n for (var i = 0; i < iLen; i += 4) {\n\n r = data[i];\n g = data[i + 1];\n b = data[i + 2];\n a = data[i + 3];\n\n tr = blendData[i];\n tg = blendData[i + 1];\n tb = blendData[i + 2];\n ta = blendData[i + 3];\n\n switch (this.mode) {\n case 'multiply':\n data[i] = r * tr / 255;\n data[i + 1] = g * tg / 255;\n data[i + 2] = b * tb / 255;\n data[i + 3] = a * ta / 255;\n break;\n case 'mask':\n data[i + 3] = ta;\n break;\n }\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uTransformMatrix: gl.getUniformLocation(program, 'uTransformMatrix'),\n uImage: gl.getUniformLocation(program, 'uImage'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n var matrix = this.calculateMatrix();\n gl.uniform1i(uniformLocations.uImage, 1); // texture unit 1.\n gl.uniformMatrix3fv(uniformLocations.uTransformMatrix, false, matrix);\n },\n\n /**\n * Returns object representation of an instance\n * @return {Object} Object representation of an instance\n */\n toObject: function() {\n return {\n type: this.type,\n image: this.image && this.image.toObject(),\n mode: this.mode,\n alpha: this.alpha\n };\n }\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} callback to be invoked after filter creation\n * @return {fabric.Image.filters.BlendImage} Instance of fabric.Image.filters.BlendImage\n */\n fabric.Image.filters.BlendImage.fromObject = function(object, callback) {\n fabric.Image.fromObject(object.image, function(image) {\n var options = fabric.util.object.clone(object);\n options.image = image;\n callback(new fabric.Image.filters.BlendImage(options));\n });\n };\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }), pow = Math.pow, floor = Math.floor,\n sqrt = Math.sqrt, abs = Math.abs, round = Math.round, sin = Math.sin,\n ceil = Math.ceil,\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Resize image filter class\n * @class fabric.Image.filters.Resize\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Resize();\n * object.filters.push(filter);\n * object.applyFilters(canvas.renderAll.bind(canvas));\n */\n filters.Resize = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Resize.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Resize',\n\n /**\n * Resize type\n * for webgl resizeType is just lanczos, for canvas2d can be:\n * bilinear, hermite, sliceHack, lanczos.\n * @param {String} resizeType\n * @default\n */\n resizeType: 'hermite',\n\n /**\n * Scale factor for resizing, x axis\n * @param {Number} scaleX\n * @default\n */\n scaleX: 1,\n\n /**\n * Scale factor for resizing, y axis\n * @param {Number} scaleY\n * @default\n */\n scaleY: 1,\n\n /**\n * LanczosLobes parameter for lanczos filter, valid for resizeType lanczos\n * @param {Number} lanczosLobes\n * @default\n */\n lanczosLobes: 3,\n\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uDelta: gl.getUniformLocation(program, 'uDelta'),\n uTaps: gl.getUniformLocation(program, 'uTaps'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform2fv(uniformLocations.uDelta, this.horizontal ? [1 / this.width, 0] : [0, 1 / this.height]);\n gl.uniform1fv(uniformLocations.uTaps, this.taps);\n },\n\n /**\n * Retrieves the cached shader.\n * @param {Object} options\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n retrieveShader: function(options) {\n var filterWindow = this.getFilterWindow(), cacheKey = this.type + '_' + filterWindow;\n if (!options.programCache.hasOwnProperty(cacheKey)) {\n var fragmentShader = this.generateShader(filterWindow);\n options.programCache[cacheKey] = this.createProgram(options.context, fragmentShader);\n }\n return options.programCache[cacheKey];\n },\n\n getFilterWindow: function() {\n var scale = this.tempScale;\n return Math.ceil(this.lanczosLobes / scale);\n },\n\n getTaps: function() {\n var lobeFunction = this.lanczosCreate(this.lanczosLobes), scale = this.tempScale,\n filterWindow = this.getFilterWindow(), taps = new Array(filterWindow);\n for (var i = 1; i <= filterWindow; i++) {\n taps[i - 1] = lobeFunction(i * scale);\n }\n return taps;\n },\n\n /**\n * Generate vertex and shader sources from the necessary steps numbers\n * @param {Number} filterWindow\n */\n generateShader: function(filterWindow) {\n var offsets = new Array(filterWindow),\n fragmentShader = this.fragmentSourceTOP, filterWindow;\n\n for (var i = 1; i <= filterWindow; i++) {\n offsets[i - 1] = i + '.0 * uDelta';\n }\n\n fragmentShader += 'uniform float uTaps[' + filterWindow + '];\\n';\n fragmentShader += 'void main() {\\n';\n fragmentShader += ' vec4 color = texture2D(uTexture, vTexCoord);\\n';\n fragmentShader += ' float sum = 1.0;\\n';\n\n offsets.forEach(function(offset, i) {\n fragmentShader += ' color += texture2D(uTexture, vTexCoord + ' + offset + ') * uTaps[' + i + '];\\n';\n fragmentShader += ' color += texture2D(uTexture, vTexCoord - ' + offset + ') * uTaps[' + i + '];\\n';\n fragmentShader += ' sum += 2.0 * uTaps[' + i + '];\\n';\n });\n fragmentShader += ' gl_FragColor = color / sum;\\n';\n fragmentShader += '}';\n return fragmentShader;\n },\n\n fragmentSourceTOP: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform vec2 uDelta;\\n' +\n 'varying vec2 vTexCoord;\\n',\n\n /**\n * Apply the resize filter to the image\n * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.\n *\n * @param {Object} options\n * @param {Number} options.passes The number of filters remaining to be executed\n * @param {Boolean} options.webgl Whether to use webgl to render the filter.\n * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.\n * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n applyTo: function(options) {\n if (options.webgl) {\n options.passes++;\n this.width = options.sourceWidth;\n this.horizontal = true;\n this.dW = Math.round(this.width * this.scaleX);\n this.dH = options.sourceHeight;\n this.tempScale = this.dW / this.width;\n this.taps = this.getTaps();\n options.destinationWidth = this.dW;\n this._setupFrameBuffer(options);\n this.applyToWebGL(options);\n this._swapTextures(options);\n options.sourceWidth = options.destinationWidth;\n\n this.height = options.sourceHeight;\n this.horizontal = false;\n this.dH = Math.round(this.height * this.scaleY);\n this.tempScale = this.dH / this.height;\n this.taps = this.getTaps();\n options.destinationHeight = this.dH;\n this._setupFrameBuffer(options);\n this.applyToWebGL(options);\n this._swapTextures(options);\n options.sourceHeight = options.destinationHeight;\n }\n else {\n this.applyTo2d(options);\n }\n },\n\n isNeutralState: function() {\n return this.scaleX === 1 && this.scaleY === 1;\n },\n\n lanczosCreate: function(lobes) {\n return function(x) {\n if (x >= lobes || x <= -lobes) {\n return 0.0;\n }\n if (x < 1.19209290E-07 && x > -1.19209290E-07) {\n return 1.0;\n }\n x *= Math.PI;\n var xx = x / lobes;\n return (sin(x) / x) * sin(xx) / xx;\n };\n },\n\n /**\n * Applies filter to canvas element\n * @memberOf fabric.Image.filters.Resize.prototype\n * @param {Object} canvasEl Canvas element to apply filter to\n * @param {Number} scaleX\n * @param {Number} scaleY\n */\n applyTo2d: function(options) {\n var imageData = options.imageData,\n scaleX = this.scaleX,\n scaleY = this.scaleY;\n\n this.rcpScaleX = 1 / scaleX;\n this.rcpScaleY = 1 / scaleY;\n\n var oW = imageData.width, oH = imageData.height,\n dW = round(oW * scaleX), dH = round(oH * scaleY),\n newData;\n\n if (this.resizeType === 'sliceHack') {\n newData = this.sliceByTwo(options, oW, oH, dW, dH);\n }\n else if (this.resizeType === 'hermite') {\n newData = this.hermiteFastResize(options, oW, oH, dW, dH);\n }\n else if (this.resizeType === 'bilinear') {\n newData = this.bilinearFiltering(options, oW, oH, dW, dH);\n }\n else if (this.resizeType === 'lanczos') {\n newData = this.lanczosResize(options, oW, oH, dW, dH);\n }\n options.imageData = newData;\n },\n\n /**\n * Filter sliceByTwo\n * @param {Object} canvasEl Canvas element to apply filter to\n * @param {Number} oW Original Width\n * @param {Number} oH Original Height\n * @param {Number} dW Destination Width\n * @param {Number} dH Destination Height\n * @returns {ImageData}\n */\n sliceByTwo: function(options, oW, oH, dW, dH) {\n var imageData = options.imageData,\n mult = 0.5, doneW = false, doneH = false, stepW = oW * mult,\n stepH = oH * mult, resources = fabric.filterBackend.resources,\n tmpCanvas, ctx, sX = 0, sY = 0, dX = oW, dY = 0;\n if (!resources.sliceByTwo) {\n resources.sliceByTwo = document.createElement('canvas');\n }\n tmpCanvas = resources.sliceByTwo;\n if (tmpCanvas.width < oW * 1.5 || tmpCanvas.height < oH) {\n tmpCanvas.width = oW * 1.5;\n tmpCanvas.height = oH;\n }\n ctx = tmpCanvas.getContext('2d');\n ctx.clearRect(0, 0, oW * 1.5, oH);\n ctx.putImageData(imageData, 0, 0);\n\n dW = floor(dW);\n dH = floor(dH);\n\n while (!doneW || !doneH) {\n oW = stepW;\n oH = stepH;\n if (dW < floor(stepW * mult)) {\n stepW = floor(stepW * mult);\n }\n else {\n stepW = dW;\n doneW = true;\n }\n if (dH < floor(stepH * mult)) {\n stepH = floor(stepH * mult);\n }\n else {\n stepH = dH;\n doneH = true;\n }\n ctx.drawImage(tmpCanvas, sX, sY, oW, oH, dX, dY, stepW, stepH);\n sX = dX;\n sY = dY;\n dY += stepH;\n }\n return ctx.getImageData(sX, sY, dW, dH);\n },\n\n /**\n * Filter lanczosResize\n * @param {Object} canvasEl Canvas element to apply filter to\n * @param {Number} oW Original Width\n * @param {Number} oH Original Height\n * @param {Number} dW Destination Width\n * @param {Number} dH Destination Height\n * @returns {ImageData}\n */\n lanczosResize: function(options, oW, oH, dW, dH) {\n\n function process(u) {\n var v, i, weight, idx, a, red, green,\n blue, alpha, fX, fY;\n center.x = (u + 0.5) * ratioX;\n icenter.x = floor(center.x);\n for (v = 0; v < dH; v++) {\n center.y = (v + 0.5) * ratioY;\n icenter.y = floor(center.y);\n a = 0; red = 0; green = 0; blue = 0; alpha = 0;\n for (i = icenter.x - range2X; i <= icenter.x + range2X; i++) {\n if (i < 0 || i >= oW) {\n continue;\n }\n fX = floor(1000 * abs(i - center.x));\n if (!cacheLanc[fX]) {\n cacheLanc[fX] = { };\n }\n for (var j = icenter.y - range2Y; j <= icenter.y + range2Y; j++) {\n if (j < 0 || j >= oH) {\n continue;\n }\n fY = floor(1000 * abs(j - center.y));\n if (!cacheLanc[fX][fY]) {\n cacheLanc[fX][fY] = lanczos(sqrt(pow(fX * rcpRatioX, 2) + pow(fY * rcpRatioY, 2)) / 1000);\n }\n weight = cacheLanc[fX][fY];\n if (weight > 0) {\n idx = (j * oW + i) * 4;\n a += weight;\n red += weight * srcData[idx];\n green += weight * srcData[idx + 1];\n blue += weight * srcData[idx + 2];\n alpha += weight * srcData[idx + 3];\n }\n }\n }\n idx = (v * dW + u) * 4;\n destData[idx] = red / a;\n destData[idx + 1] = green / a;\n destData[idx + 2] = blue / a;\n destData[idx + 3] = alpha / a;\n }\n\n if (++u < dW) {\n return process(u);\n }\n else {\n return destImg;\n }\n }\n\n var srcData = options.imageData.data,\n destImg = options.ctx.createImageData(dW, dH),\n destData = destImg.data,\n lanczos = this.lanczosCreate(this.lanczosLobes),\n ratioX = this.rcpScaleX, ratioY = this.rcpScaleY,\n rcpRatioX = 2 / this.rcpScaleX, rcpRatioY = 2 / this.rcpScaleY,\n range2X = ceil(ratioX * this.lanczosLobes / 2),\n range2Y = ceil(ratioY * this.lanczosLobes / 2),\n cacheLanc = { }, center = { }, icenter = { };\n\n return process(0);\n },\n\n /**\n * bilinearFiltering\n * @param {Object} canvasEl Canvas element to apply filter to\n * @param {Number} oW Original Width\n * @param {Number} oH Original Height\n * @param {Number} dW Destination Width\n * @param {Number} dH Destination Height\n * @returns {ImageData}\n */\n bilinearFiltering: function(options, oW, oH, dW, dH) {\n var a, b, c, d, x, y, i, j, xDiff, yDiff, chnl,\n color, offset = 0, origPix, ratioX = this.rcpScaleX,\n ratioY = this.rcpScaleY,\n w4 = 4 * (oW - 1), img = options.imageData,\n pixels = img.data, destImage = options.ctx.createImageData(dW, dH),\n destPixels = destImage.data;\n for (i = 0; i < dH; i++) {\n for (j = 0; j < dW; j++) {\n x = floor(ratioX * j);\n y = floor(ratioY * i);\n xDiff = ratioX * j - x;\n yDiff = ratioY * i - y;\n origPix = 4 * (y * oW + x);\n\n for (chnl = 0; chnl < 4; chnl++) {\n a = pixels[origPix + chnl];\n b = pixels[origPix + 4 + chnl];\n c = pixels[origPix + w4 + chnl];\n d = pixels[origPix + w4 + 4 + chnl];\n color = a * (1 - xDiff) * (1 - yDiff) + b * xDiff * (1 - yDiff) +\n c * yDiff * (1 - xDiff) + d * xDiff * yDiff;\n destPixels[offset++] = color;\n }\n }\n }\n return destImage;\n },\n\n /**\n * hermiteFastResize\n * @param {Object} canvasEl Canvas element to apply filter to\n * @param {Number} oW Original Width\n * @param {Number} oH Original Height\n * @param {Number} dW Destination Width\n * @param {Number} dH Destination Height\n * @returns {ImageData}\n */\n hermiteFastResize: function(options, oW, oH, dW, dH) {\n var ratioW = this.rcpScaleX, ratioH = this.rcpScaleY,\n ratioWHalf = ceil(ratioW / 2),\n ratioHHalf = ceil(ratioH / 2),\n img = options.imageData, data = img.data,\n img2 = options.ctx.createImageData(dW, dH), data2 = img2.data;\n for (var j = 0; j < dH; j++) {\n for (var i = 0; i < dW; i++) {\n var x2 = (i + j * dW) * 4, weight = 0, weights = 0, weightsAlpha = 0,\n gxR = 0, gxG = 0, gxB = 0, gxA = 0, centerY = (j + 0.5) * ratioH;\n for (var yy = floor(j * ratioH); yy < (j + 1) * ratioH; yy++) {\n var dy = abs(centerY - (yy + 0.5)) / ratioHHalf,\n centerX = (i + 0.5) * ratioW, w0 = dy * dy;\n for (var xx = floor(i * ratioW); xx < (i + 1) * ratioW; xx++) {\n var dx = abs(centerX - (xx + 0.5)) / ratioWHalf,\n w = sqrt(w0 + dx * dx);\n /* eslint-disable max-depth */\n if (w > 1 && w < -1) {\n continue;\n }\n //hermite filter\n weight = 2 * w * w * w - 3 * w * w + 1;\n if (weight > 0) {\n dx = 4 * (xx + yy * oW);\n //alpha\n gxA += weight * data[dx + 3];\n weightsAlpha += weight;\n //colors\n if (data[dx + 3] < 255) {\n weight = weight * data[dx + 3] / 250;\n }\n gxR += weight * data[dx];\n gxG += weight * data[dx + 1];\n gxB += weight * data[dx + 2];\n weights += weight;\n }\n /* eslint-enable max-depth */\n }\n }\n data2[x2] = gxR / weights;\n data2[x2 + 1] = gxG / weights;\n data2[x2 + 2] = gxB / weights;\n data2[x2 + 3] = gxA / weightsAlpha;\n }\n }\n return img2;\n },\n\n /**\n * Returns object representation of an instance\n * @return {Object} Object representation of an instance\n */\n toObject: function() {\n return {\n type: this.type,\n scaleX: this.scaleX,\n scaleY: this.scaleY,\n resizeType: this.resizeType,\n lanczosLobes: this.lanczosLobes\n };\n }\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Resize} Instance of fabric.Image.filters.Resize\n */\n fabric.Image.filters.Resize.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Contrast filter class\n * @class fabric.Image.filters.Contrast\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Contrast#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Contrast({\n * contrast: 0.25\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.Contrast = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Contrast.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Contrast',\n\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uContrast;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\\n' +\n 'color.rgb = contrastF * (color.rgb - 0.5) + 0.5;\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n\n /**\n * contrast value, range from -1 to 1.\n * @param {Number} contrast\n * @default 0\n */\n contrast: 0,\n\n mainParameter: 'contrast',\n\n /**\n * Constructor\n * @memberOf fabric.Image.filters.Contrast.prototype\n * @param {Object} [options] Options object\n * @param {Number} [options.contrast=0] Value to contrast the image up (-1...1)\n */\n\n /**\n * Apply the Contrast operation to a Uint8Array representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8Array to be filtered.\n */\n applyTo2d: function(options) {\n if (this.contrast === 0) {\n return;\n }\n var imageData = options.imageData, i, len,\n data = imageData.data, len = data.length,\n contrast = Math.floor(this.contrast * 255),\n contrastF = 259 * (contrast + 255) / (255 * (259 - contrast));\n\n for (i = 0; i < len; i += 4) {\n data[i] = contrastF * (data[i] - 128) + 128;\n data[i + 1] = contrastF * (data[i + 1] - 128) + 128;\n data[i + 2] = contrastF * (data[i + 2] - 128) + 128;\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uContrast: gl.getUniformLocation(program, 'uContrast'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform1f(uniformLocations.uContrast, this.contrast);\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Contrast} Instance of fabric.Image.filters.Contrast\n */\n fabric.Image.filters.Contrast.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Saturate filter class\n * @class fabric.Image.filters.Saturation\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Saturation#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Saturation({\n * saturation: 1\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.Saturation = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Saturation.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Saturation',\n\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uSaturation;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'float rgMax = max(color.r, color.g);\\n' +\n 'float rgbMax = max(rgMax, color.b);\\n' +\n 'color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\\n' +\n 'color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\\n' +\n 'color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n\n /**\n * Saturation value, from -1 to 1.\n * Increases/decreases the color saturation.\n * A value of 0 has no effect.\n * \n * @param {Number} saturation\n * @default\n */\n saturation: 0,\n\n mainParameter: 'saturation',\n\n /**\n * Constructor\n * @memberOf fabric.Image.filters.Saturate.prototype\n * @param {Object} [options] Options object\n * @param {Number} [options.saturate=0] Value to saturate the image (-1...1)\n */\n\n /**\n * Apply the Saturation operation to a Uint8ClampedArray representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.\n */\n applyTo2d: function(options) {\n if (this.saturation === 0) {\n return;\n }\n var imageData = options.imageData,\n data = imageData.data, len = data.length,\n adjust = -this.saturation, i, max;\n\n for (i = 0; i < len; i += 4) {\n max = Math.max(data[i], data[i + 1], data[i + 2]);\n data[i] += max !== data[i] ? (max - data[i]) * adjust : 0;\n data[i + 1] += max !== data[i + 1] ? (max - data[i + 1]) * adjust : 0;\n data[i + 2] += max !== data[i + 2] ? (max - data[i + 2]) * adjust : 0;\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uSaturation: gl.getUniformLocation(program, 'uSaturation'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform1f(uniformLocations.uSaturation, -this.saturation);\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Saturation} Instance of fabric.Image.filters.Saturate\n */\n fabric.Image.filters.Saturation.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Vibrance filter class\n * @class fabric.Image.filters.Vibrance\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Vibrance#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Vibrance({\n * vibrance: 1\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.Vibrance = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Vibrance.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Vibrance',\n\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform float uVibrance;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'float max = max(color.r, max(color.g, color.b));\\n' +\n 'float avg = (color.r + color.g + color.b) / 3.0;\\n' +\n 'float amt = (abs(max - avg) * 2.0) * uVibrance;\\n' +\n 'color.r += max != color.r ? (max - color.r) * amt : 0.00;\\n' +\n 'color.g += max != color.g ? (max - color.g) * amt : 0.00;\\n' +\n 'color.b += max != color.b ? (max - color.b) * amt : 0.00;\\n' +\n 'gl_FragColor = color;\\n' +\n '}',\n\n /**\n * Vibrance value, from -1 to 1.\n * Increases/decreases the saturation of more muted colors with less effect on saturated colors.\n * A value of 0 has no effect.\n * \n * @param {Number} vibrance\n * @default\n */\n vibrance: 0,\n\n mainParameter: 'vibrance',\n\n /**\n * Constructor\n * @memberOf fabric.Image.filters.Vibrance.prototype\n * @param {Object} [options] Options object\n * @param {Number} [options.vibrance=0] Vibrance value for the image (between -1 and 1)\n */\n\n /**\n * Apply the Vibrance operation to a Uint8ClampedArray representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.\n */\n applyTo2d: function(options) {\n if (this.vibrance === 0) {\n return;\n }\n var imageData = options.imageData,\n data = imageData.data, len = data.length,\n adjust = -this.vibrance, i, max, avg, amt;\n\n for (i = 0; i < len; i += 4) {\n max = Math.max(data[i], data[i + 1], data[i + 2]);\n avg = (data[i] + data[i + 1] + data[i + 2]) / 3;\n amt = ((Math.abs(max - avg) * 2 / 255) * adjust);\n data[i] += max !== data[i] ? (max - data[i]) * amt : 0;\n data[i + 1] += max !== data[i + 1] ? (max - data[i + 1]) * amt : 0;\n data[i + 2] += max !== data[i + 2] ? (max - data[i + 2]) * amt : 0;\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uVibrance: gl.getUniformLocation(program, 'uVibrance'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform1f(uniformLocations.uVibrance, -this.vibrance);\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Vibrance} Instance of fabric.Image.filters.Vibrance\n */\n fabric.Image.filters.Vibrance.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Blur filter class\n * @class fabric.Image.filters.Blur\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Blur#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Blur({\n * blur: 0.5\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n * canvas.renderAll();\n */\n filters.Blur = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Blur.prototype */ {\n\n type: 'Blur',\n\n /*\n'gl_FragColor = vec4(0.0);',\n'gl_FragColor += texture2D(texture, vTexCoord + -7 * uDelta)*0.0044299121055113265;',\n'gl_FragColor += texture2D(texture, vTexCoord + -6 * uDelta)*0.00895781211794;',\n'gl_FragColor += texture2D(texture, vTexCoord + -5 * uDelta)*0.0215963866053;',\n'gl_FragColor += texture2D(texture, vTexCoord + -4 * uDelta)*0.0443683338718;',\n'gl_FragColor += texture2D(texture, vTexCoord + -3 * uDelta)*0.0776744219933;',\n'gl_FragColor += texture2D(texture, vTexCoord + -2 * uDelta)*0.115876621105;',\n'gl_FragColor += texture2D(texture, vTexCoord + -1 * uDelta)*0.147308056121;',\n'gl_FragColor += texture2D(texture, vTexCoord )*0.159576912161;',\n'gl_FragColor += texture2D(texture, vTexCoord + 1 * uDelta)*0.147308056121;',\n'gl_FragColor += texture2D(texture, vTexCoord + 2 * uDelta)*0.115876621105;',\n'gl_FragColor += texture2D(texture, vTexCoord + 3 * uDelta)*0.0776744219933;',\n'gl_FragColor += texture2D(texture, vTexCoord + 4 * uDelta)*0.0443683338718;',\n'gl_FragColor += texture2D(texture, vTexCoord + 5 * uDelta)*0.0215963866053;',\n'gl_FragColor += texture2D(texture, vTexCoord + 6 * uDelta)*0.00895781211794;',\n'gl_FragColor += texture2D(texture, vTexCoord + 7 * uDelta)*0.0044299121055113265;',\n*/\n\n /* eslint-disable max-len */\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform vec2 uDelta;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'const float nSamples = 15.0;\\n' +\n 'vec3 v3offset = vec3(12.9898, 78.233, 151.7182);\\n' +\n 'float random(vec3 scale) {\\n' +\n /* use the fragment position for a different seed per-pixel */\n 'return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\\n' +\n '}\\n' +\n 'void main() {\\n' +\n 'vec4 color = vec4(0.0);\\n' +\n 'float total = 0.0;\\n' +\n 'float offset = random(v3offset);\\n' +\n 'for (float t = -nSamples; t <= nSamples; t++) {\\n' +\n 'float percent = (t + offset - 0.5) / nSamples;\\n' +\n 'float weight = 1.0 - abs(percent);\\n' +\n 'color += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\\n' +\n 'total += weight;\\n' +\n '}\\n' +\n 'gl_FragColor = color / total;\\n' +\n '}',\n /* eslint-enable max-len */\n\n /**\n * blur value, in percentage of image dimensions.\n * specific to keep the image blur constant at different resolutions\n * range between 0 and 1.\n * @type Number\n * @default\n */\n blur: 0,\n\n mainParameter: 'blur',\n\n applyTo: function(options) {\n if (options.webgl) {\n // this aspectRatio is used to give the same blur to vertical and horizontal\n this.aspectRatio = options.sourceWidth / options.sourceHeight;\n options.passes++;\n this._setupFrameBuffer(options);\n this.horizontal = true;\n this.applyToWebGL(options);\n this._swapTextures(options);\n this._setupFrameBuffer(options);\n this.horizontal = false;\n this.applyToWebGL(options);\n this._swapTextures(options);\n }\n else {\n this.applyTo2d(options);\n }\n },\n\n applyTo2d: function(options) {\n // paint canvasEl with current image data.\n //options.ctx.putImageData(options.imageData, 0, 0);\n options.imageData = this.simpleBlur(options);\n },\n\n simpleBlur: function(options) {\n var resources = options.filterBackend.resources, canvas1, canvas2,\n width = options.imageData.width,\n height = options.imageData.height;\n\n if (!resources.blurLayer1) {\n resources.blurLayer1 = fabric.util.createCanvasElement();\n resources.blurLayer2 = fabric.util.createCanvasElement();\n }\n canvas1 = resources.blurLayer1;\n canvas2 = resources.blurLayer2;\n if (canvas1.width !== width || canvas1.height !== height) {\n canvas2.width = canvas1.width = width;\n canvas2.height = canvas1.height = height;\n }\n var ctx1 = canvas1.getContext('2d'),\n ctx2 = canvas2.getContext('2d'),\n nSamples = 15,\n random, percent, j, i,\n blur = this.blur * 0.06 * 0.5;\n\n // load first canvas\n ctx1.putImageData(options.imageData, 0, 0);\n ctx2.clearRect(0, 0, width, height);\n\n for (i = -nSamples; i <= nSamples; i++) {\n random = (Math.random() - 0.5) / 4;\n percent = i / nSamples;\n j = blur * percent * width + random;\n ctx2.globalAlpha = 1 - Math.abs(percent);\n ctx2.drawImage(canvas1, j, random);\n ctx1.drawImage(canvas2, 0, 0);\n ctx2.globalAlpha = 1;\n ctx2.clearRect(0, 0, canvas2.width, canvas2.height);\n }\n for (i = -nSamples; i <= nSamples; i++) {\n random = (Math.random() - 0.5) / 4;\n percent = i / nSamples;\n j = blur * percent * height + random;\n ctx2.globalAlpha = 1 - Math.abs(percent);\n ctx2.drawImage(canvas1, random, j);\n ctx1.drawImage(canvas2, 0, 0);\n ctx2.globalAlpha = 1;\n ctx2.clearRect(0, 0, canvas2.width, canvas2.height);\n }\n options.ctx.drawImage(canvas1, 0, 0);\n var newImageData = options.ctx.getImageData(0, 0, canvas1.width, canvas1.height);\n ctx1.globalAlpha = 1;\n ctx1.clearRect(0, 0, canvas1.width, canvas1.height);\n return newImageData;\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n delta: gl.getUniformLocation(program, 'uDelta'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n var delta = this.chooseRightDelta();\n gl.uniform2fv(uniformLocations.delta, delta);\n },\n\n /**\n * choose right value of image percentage to blur with\n * @returns {Array} a numeric array with delta values\n */\n chooseRightDelta: function() {\n var blurScale = 1, delta = [0, 0], blur;\n if (this.horizontal) {\n if (this.aspectRatio > 1) {\n // image is wide, i want to shrink radius horizontal\n blurScale = 1 / this.aspectRatio;\n }\n }\n else {\n if (this.aspectRatio < 1) {\n // image is tall, i want to shrink radius vertical\n blurScale = this.aspectRatio;\n }\n }\n blur = blurScale * this.blur * 0.12;\n if (this.horizontal) {\n delta[0] = blur;\n }\n else {\n delta[1] = blur;\n }\n return delta;\n },\n });\n\n /**\n * Deserialize a JSON definition of a BlurFilter into a concrete instance.\n */\n filters.Blur.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * Gamma filter class\n * @class fabric.Image.filters.Gamma\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.Gamma#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.Gamma({\n * gamma: [1, 0.5, 2.1]\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.Gamma = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Gamma.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'Gamma',\n\n fragmentSource: 'precision highp float;\\n' +\n 'uniform sampler2D uTexture;\\n' +\n 'uniform vec3 uGamma;\\n' +\n 'varying vec2 vTexCoord;\\n' +\n 'void main() {\\n' +\n 'vec4 color = texture2D(uTexture, vTexCoord);\\n' +\n 'vec3 correction = (1.0 / uGamma);\\n' +\n 'color.r = pow(color.r, correction.r);\\n' +\n 'color.g = pow(color.g, correction.g);\\n' +\n 'color.b = pow(color.b, correction.b);\\n' +\n 'gl_FragColor = color;\\n' +\n 'gl_FragColor.rgb *= color.a;\\n' +\n '}',\n\n /**\n * Gamma array value, from 0.01 to 2.2.\n * @param {Array} gamma\n * @default\n */\n gamma: [1, 1, 1],\n\n /**\n * Describe the property that is the filter parameter\n * @param {String} m\n * @default\n */\n mainParameter: 'gamma',\n\n /**\n * Constructor\n * @param {Object} [options] Options object\n */\n initialize: function(options) {\n this.gamma = [1, 1, 1];\n filters.BaseFilter.prototype.initialize.call(this, options);\n },\n\n /**\n * Apply the Gamma operation to a Uint8Array representing the pixels of an image.\n *\n * @param {Object} options\n * @param {ImageData} options.imageData The Uint8Array to be filtered.\n */\n applyTo2d: function(options) {\n var imageData = options.imageData, data = imageData.data,\n gamma = this.gamma, len = data.length,\n rInv = 1 / gamma[0], gInv = 1 / gamma[1],\n bInv = 1 / gamma[2], i;\n\n if (!this.rVals) {\n // eslint-disable-next-line\n this.rVals = new Uint8Array(256);\n // eslint-disable-next-line\n this.gVals = new Uint8Array(256);\n // eslint-disable-next-line\n this.bVals = new Uint8Array(256);\n }\n\n // This is an optimization - pre-compute a look-up table for each color channel\n // instead of performing these pow calls for each pixel in the image.\n for (i = 0, len = 256; i < len; i++) {\n this.rVals[i] = Math.pow(i / 255, rInv) * 255;\n this.gVals[i] = Math.pow(i / 255, gInv) * 255;\n this.bVals[i] = Math.pow(i / 255, bInv) * 255;\n }\n for (i = 0, len = data.length; i < len; i += 4) {\n data[i] = this.rVals[data[i]];\n data[i + 1] = this.gVals[data[i + 1]];\n data[i + 2] = this.bVals[data[i + 2]];\n }\n },\n\n /**\n * Return WebGL uniform locations for this filter's shader.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {WebGLShaderProgram} program This filter's compiled shader program.\n */\n getUniformLocations: function(gl, program) {\n return {\n uGamma: gl.getUniformLocation(program, 'uGamma'),\n };\n },\n\n /**\n * Send data from this filter to its shader program's uniforms.\n *\n * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.\n * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects\n */\n sendUniformData: function(gl, uniformLocations) {\n gl.uniform3fv(uniformLocations.uGamma, this.gamma);\n },\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.Gamma} Instance of fabric.Image.filters.Gamma\n */\n fabric.Image.filters.Gamma.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * A container class that knows how to apply a sequence of filters to an input image.\n */\n filters.Composed = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Composed.prototype */ {\n\n type: 'Composed',\n\n /**\n * A non sparse array of filters to apply\n */\n subFilters: [],\n\n /**\n * Constructor\n * @param {Object} [options] Options object\n */\n initialize: function(options) {\n this.callSuper('initialize', options);\n // create a new array instead mutating the prototype with push\n this.subFilters = this.subFilters.slice(0);\n },\n\n /**\n * Apply this container's filters to the input image provided.\n *\n * @param {Object} options\n * @param {Number} options.passes The number of filters remaining to be applied.\n */\n applyTo: function(options) {\n options.passes += this.subFilters.length - 1;\n this.subFilters.forEach(function(filter) {\n filter.applyTo(options);\n });\n },\n\n /**\n * Serialize this filter into JSON.\n *\n * @returns {Object} A JSON representation of this filter.\n */\n toObject: function() {\n return fabric.util.object.extend(this.callSuper('toObject'), {\n subFilters: this.subFilters.map(function(filter) { return filter.toObject(); }),\n });\n },\n\n isNeutralState: function() {\n return !this.subFilters.some(function(filter) { return !filter.isNeutralState(); });\n }\n });\n\n /**\n * Deserialize a JSON definition of a ComposedFilter into a concrete instance.\n */\n fabric.Image.filters.Composed.fromObject = function(object, callback) {\n var filters = object.subFilters || [],\n subFilters = filters.map(function(filter) {\n return new fabric.Image.filters[filter.type](filter);\n }),\n instance = new fabric.Image.filters.Composed({ subFilters: subFilters });\n callback && callback(instance);\n return instance;\n };\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n filters = fabric.Image.filters,\n createClass = fabric.util.createClass;\n\n /**\n * HueRotation filter class\n * @class fabric.Image.filters.HueRotation\n * @memberOf fabric.Image.filters\n * @extends fabric.Image.filters.BaseFilter\n * @see {@link fabric.Image.filters.HueRotation#initialize} for constructor definition\n * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}\n * @example\n * var filter = new fabric.Image.filters.HueRotation({\n * rotation: -0.5\n * });\n * object.filters.push(filter);\n * object.applyFilters();\n */\n filters.HueRotation = createClass(filters.ColorMatrix, /** @lends fabric.Image.filters.HueRotation.prototype */ {\n\n /**\n * Filter type\n * @param {String} type\n * @default\n */\n type: 'HueRotation',\n\n /**\n * HueRotation value, from -1 to 1.\n * the unit is radians\n * @param {Number} myParameter\n * @default\n */\n rotation: 0,\n\n /**\n * Describe the property that is the filter parameter\n * @param {String} m\n * @default\n */\n mainParameter: 'rotation',\n\n calculateMatrix: function() {\n var rad = this.rotation * Math.PI, cos = fabric.util.cos(rad), sin = fabric.util.sin(rad),\n aThird = 1 / 3, aThirdSqtSin = Math.sqrt(aThird) * sin, OneMinusCos = 1 - cos;\n this.matrix = [\n 1, 0, 0, 0, 0,\n 0, 1, 0, 0, 0,\n 0, 0, 1, 0, 0,\n 0, 0, 0, 1, 0\n ];\n this.matrix[0] = cos + OneMinusCos / 3;\n this.matrix[1] = aThird * OneMinusCos - aThirdSqtSin;\n this.matrix[2] = aThird * OneMinusCos + aThirdSqtSin;\n this.matrix[5] = aThird * OneMinusCos + aThirdSqtSin;\n this.matrix[6] = cos + aThird * OneMinusCos;\n this.matrix[7] = aThird * OneMinusCos - aThirdSqtSin;\n this.matrix[10] = aThird * OneMinusCos - aThirdSqtSin;\n this.matrix[11] = aThird * OneMinusCos + aThirdSqtSin;\n this.matrix[12] = cos + aThird * OneMinusCos;\n },\n\n /**\n * HueRotation isNeutralState implementation\n * Used only in image applyFilters to discard filters that will not have an effect\n * on the image\n * @param {Object} options\n **/\n isNeutralState: function(options) {\n this.calculateMatrix();\n return filters.BaseFilter.prototype.isNeutralState.call(this, options);\n },\n\n /**\n * Apply this filter to the input image data provided.\n *\n * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.\n *\n * @param {Object} options\n * @param {Number} options.passes The number of filters remaining to be executed\n * @param {Boolean} options.webgl Whether to use webgl to render the filter.\n * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.\n * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.\n * @param {WebGLRenderingContext} options.context The GL context used for rendering.\n * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.\n */\n applyTo: function(options) {\n this.calculateMatrix();\n filters.BaseFilter.prototype.applyTo.call(this, options);\n },\n\n });\n\n /**\n * Returns filter instance from an object representation\n * @static\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] to be invoked after filter creation\n * @return {fabric.Image.filters.HueRotation} Instance of fabric.Image.filters.HueRotation\n */\n fabric.Image.filters.HueRotation.fromObject = fabric.Image.filters.BaseFilter.fromObject;\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = { }),\n clone = fabric.util.object.clone;\n\n if (fabric.Text) {\n fabric.warn('fabric.Text is already defined');\n return;\n }\n\n var additionalProps =\n ('fontFamily fontWeight fontSize text underline overline linethrough' +\n ' textAlign fontStyle lineHeight textBackgroundColor charSpacing styles' +\n ' direction path pathStartOffset pathSide pathAlign').split(' ');\n\n /**\n * Text class\n * @class fabric.Text\n * @extends fabric.Object\n * @return {fabric.Text} thisArg\n * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#text}\n * @see {@link fabric.Text#initialize} for constructor definition\n */\n fabric.Text = fabric.util.createClass(fabric.Object, /** @lends fabric.Text.prototype */ {\n\n /**\n * Properties which when set cause object to change dimensions\n * @type Array\n * @private\n */\n _dimensionAffectingProps: [\n 'fontSize',\n 'fontWeight',\n 'fontFamily',\n 'fontStyle',\n 'lineHeight',\n 'text',\n 'charSpacing',\n 'textAlign',\n 'styles',\n 'path',\n 'pathStartOffset',\n 'pathSide',\n 'pathAlign'\n ],\n\n /**\n * @private\n */\n _reNewline: /\\r?\\n/,\n\n /**\n * Use this regular expression to filter for whitespaces that is not a new line.\n * Mostly used when text is 'justify' aligned.\n * @private\n */\n _reSpacesAndTabs: /[ \\t\\r]/g,\n\n /**\n * Use this regular expression to filter for whitespace that is not a new line.\n * Mostly used when text is 'justify' aligned.\n * @private\n */\n _reSpaceAndTab: /[ \\t\\r]/,\n\n /**\n * Use this regular expression to filter consecutive groups of non spaces.\n * Mostly used when text is 'justify' aligned.\n * @private\n */\n _reWords: /\\S+/g,\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'text',\n\n /**\n * Font size (in pixels)\n * @type Number\n * @default\n */\n fontSize: 40,\n\n /**\n * Font weight (e.g. bold, normal, 400, 600, 800)\n * @type {(Number|String)}\n * @default\n */\n fontWeight: 'normal',\n\n /**\n * Font family\n * @type String\n * @default\n */\n fontFamily: 'Times New Roman',\n\n /**\n * Text decoration underline.\n * @type Boolean\n * @default\n */\n underline: false,\n\n /**\n * Text decoration overline.\n * @type Boolean\n * @default\n */\n overline: false,\n\n /**\n * Text decoration linethrough.\n * @type Boolean\n * @default\n */\n linethrough: false,\n\n /**\n * Text alignment. Possible values: \"left\", \"center\", \"right\", \"justify\",\n * \"justify-left\", \"justify-center\" or \"justify-right\".\n * @type String\n * @default\n */\n textAlign: 'left',\n\n /**\n * Font style . Possible values: \"\", \"normal\", \"italic\" or \"oblique\".\n * @type String\n * @default\n */\n fontStyle: 'normal',\n\n /**\n * Line height\n * @type Number\n * @default\n */\n lineHeight: 1.16,\n\n /**\n * Superscript schema object (minimum overlap)\n * @type {Object}\n * @default\n */\n superscript: {\n size: 0.60, // fontSize factor\n baseline: -0.35 // baseline-shift factor (upwards)\n },\n\n /**\n * Subscript schema object (minimum overlap)\n * @type {Object}\n * @default\n */\n subscript: {\n size: 0.60, // fontSize factor\n baseline: 0.11 // baseline-shift factor (downwards)\n },\n\n /**\n * Background color of text lines\n * @type String\n * @default\n */\n textBackgroundColor: '',\n\n /**\n * List of properties to consider when checking if\n * state of an object is changed ({@link fabric.Object#hasStateChanged})\n * as well as for history (undo/redo) purposes\n * @type Array\n */\n stateProperties: fabric.Object.prototype.stateProperties.concat(additionalProps),\n\n /**\n * List of properties to consider when checking if cache needs refresh\n * @type Array\n */\n cacheProperties: fabric.Object.prototype.cacheProperties.concat(additionalProps),\n\n /**\n * When defined, an object is rendered via stroke and this property specifies its color.\n * Backwards incompatibility note: This property was named \"strokeStyle\" until v1.1.6\n * @type String\n * @default\n */\n stroke: null,\n\n /**\n * Shadow object representing shadow of this shape.\n * Backwards incompatibility note: This property was named \"textShadow\" (String) until v1.2.11\n * @type fabric.Shadow\n * @default\n */\n shadow: null,\n\n /**\n * fabric.Path that the text should follow.\n * since 4.6.0 the path will be drawn automatically.\n * if you want to make the path visible, give it a stroke and strokeWidth or fill value\n * if you want it to be hidden, assign visible = false to the path.\n * This feature is in BETA, and SVG import/export is not yet supported.\n * @type fabric.Path\n * @example\n * var textPath = new fabric.Text('Text on a path', {\n * top: 150,\n * left: 150,\n * textAlign: 'center',\n * charSpacing: -50,\n * path: new fabric.Path('M 0 0 C 50 -100 150 -100 200 0', {\n * strokeWidth: 1,\n * visible: false\n * }),\n * pathSide: 'left',\n * pathStartOffset: 0\n * });\n * @default\n */\n path: null,\n\n /**\n * Offset amount for text path starting position\n * Only used when text has a path\n * @type Number\n * @default\n */\n pathStartOffset: 0,\n\n /**\n * Which side of the path the text should be drawn on.\n * Only used when text has a path\n * @type {String} 'left|right'\n * @default\n */\n pathSide: 'left',\n\n /**\n * How text is aligned to the path. This property determines\n * the perpendicular position of each character relative to the path.\n * (one of \"baseline\", \"center\", \"ascender\", \"descender\")\n * This feature is in BETA, and its behavior may change\n * @type String\n * @default\n */\n pathAlign: 'baseline',\n\n /**\n * @private\n */\n _fontSizeFraction: 0.222,\n\n /**\n * @private\n */\n offsets: {\n underline: 0.10,\n linethrough: -0.315,\n overline: -0.88\n },\n\n /**\n * Text Line proportion to font Size (in pixels)\n * @type Number\n * @default\n */\n _fontSizeMult: 1.13,\n\n /**\n * additional space between characters\n * expressed in thousands of em unit\n * @type Number\n * @default\n */\n charSpacing: 0,\n\n /**\n * Object containing character styles - top-level properties -> line numbers,\n * 2nd-level properties - character numbers\n * @type Object\n * @default\n */\n styles: null,\n\n /**\n * Reference to a context to measure text char or couple of chars\n * the cacheContext of the canvas will be used or a freshly created one if the object is not on canvas\n * once created it will be referenced on fabric._measuringContext to avoid creating a canvas for every\n * text object created.\n * @type {CanvasRenderingContext2D}\n * @default\n */\n _measuringContext: null,\n\n /**\n * Baseline shift, styles only, keep at 0 for the main text object\n * @type {Number}\n * @default\n */\n deltaY: 0,\n\n /**\n * WARNING: EXPERIMENTAL. NOT SUPPORTED YET\n * determine the direction of the text.\n * This has to be set manually together with textAlign and originX for proper\n * experience.\n * some interesting link for the future\n * https://www.w3.org/International/questions/qa-bidi-unicode-controls\n * @since 4.5.0\n * @type {String} 'ltr|rtl'\n * @default\n */\n direction: 'ltr',\n\n /**\n * Array of properties that define a style unit (of 'styles').\n * @type {Array}\n * @default\n */\n _styleProperties: [\n 'stroke',\n 'strokeWidth',\n 'fill',\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'fontStyle',\n 'underline',\n 'overline',\n 'linethrough',\n 'deltaY',\n 'textBackgroundColor',\n ],\n\n /**\n * contains characters bounding boxes\n */\n __charBounds: [],\n\n /**\n * use this size when measuring text. To avoid IE11 rounding errors\n * @type {Number}\n * @default\n * @readonly\n * @private\n */\n CACHE_FONT_SIZE: 400,\n\n /**\n * contains the min text width to avoid getting 0\n * @type {Number}\n * @default\n */\n MIN_TEXT_WIDTH: 2,\n\n /**\n * Constructor\n * @param {String} text Text string\n * @param {Object} [options] Options object\n * @return {fabric.Text} thisArg\n */\n initialize: function(text, options) {\n this.styles = options ? (options.styles || { }) : { };\n this.text = text;\n this.__skipDimension = true;\n this.callSuper('initialize', options);\n if (this.path) {\n this.setPathInfo();\n }\n this.__skipDimension = false;\n this.initDimensions();\n this.setCoords();\n this.setupState({ propertySet: '_dimensionAffectingProps' });\n },\n\n /**\n * If text has a path, it will add the extra information needed\n * for path and text calculations\n * @return {fabric.Text} thisArg\n */\n setPathInfo: function() {\n var path = this.path;\n if (path) {\n path.segmentsInfo = fabric.util.getPathSegmentsInfo(path.path);\n }\n },\n\n /**\n * Return a context for measurement of text string.\n * if created it gets stored for reuse\n * this is for internal use, please do not use it\n * @private\n * @param {String} text Text string\n * @param {Object} [options] Options object\n * @return {fabric.Text} thisArg\n */\n getMeasuringContext: function() {\n // if we did not return we have to measure something.\n if (!fabric._measuringContext) {\n fabric._measuringContext = this.canvas && this.canvas.contextCache ||\n fabric.util.createCanvasElement().getContext('2d');\n }\n return fabric._measuringContext;\n },\n\n /**\n * @private\n * Divides text into lines of text and lines of graphemes.\n */\n _splitText: function() {\n var newLines = this._splitTextIntoLines(this.text);\n this.textLines = newLines.lines;\n this._textLines = newLines.graphemeLines;\n this._unwrappedTextLines = newLines._unwrappedLines;\n this._text = newLines.graphemeText;\n return newLines;\n },\n\n /**\n * Initialize or update text dimensions.\n * Updates this.width and this.height with the proper values.\n * Does not return dimensions.\n */\n initDimensions: function() {\n if (this.__skipDimension) {\n return;\n }\n this._splitText();\n this._clearCache();\n if (this.path) {\n this.width = this.path.width;\n this.height = this.path.height;\n }\n else {\n this.width = this.calcTextWidth() || this.cursorWidth || this.MIN_TEXT_WIDTH;\n this.height = this.calcTextHeight();\n }\n if (this.textAlign.indexOf('justify') !== -1) {\n // once text is measured we need to make space fatter to make justified text.\n this.enlargeSpaces();\n }\n this.saveState({ propertySet: '_dimensionAffectingProps' });\n },\n\n /**\n * Enlarge space boxes and shift the others\n */\n enlargeSpaces: function() {\n var diffSpace, currentLineWidth, numberOfSpaces, accumulatedSpace, line, charBound, spaces;\n for (var i = 0, len = this._textLines.length; i < len; i++) {\n if (this.textAlign !== 'justify' && (i === len - 1 || this.isEndOfWrapping(i))) {\n continue;\n }\n accumulatedSpace = 0;\n line = this._textLines[i];\n currentLineWidth = this.getLineWidth(i);\n if (currentLineWidth < this.width && (spaces = this.textLines[i].match(this._reSpacesAndTabs))) {\n numberOfSpaces = spaces.length;\n diffSpace = (this.width - currentLineWidth) / numberOfSpaces;\n for (var j = 0, jlen = line.length; j <= jlen; j++) {\n charBound = this.__charBounds[i][j];\n if (this._reSpaceAndTab.test(line[j])) {\n charBound.width += diffSpace;\n charBound.kernedWidth += diffSpace;\n charBound.left += accumulatedSpace;\n accumulatedSpace += diffSpace;\n }\n else {\n charBound.left += accumulatedSpace;\n }\n }\n }\n }\n },\n\n /**\n * Detect if the text line is ended with an hard break\n * text and itext do not have wrapping, return false\n * @return {Boolean}\n */\n isEndOfWrapping: function(lineIndex) {\n return lineIndex === this._textLines.length - 1;\n },\n\n /**\n * Detect if a line has a linebreak and so we need to account for it when moving\n * and counting style.\n * It return always for text and Itext.\n * @return Number\n */\n missingNewlineOffset: function() {\n return 1;\n },\n\n /**\n * Returns string representation of an instance\n * @return {String} String representation of text object\n */\n toString: function() {\n return '#';\n },\n\n /**\n * Return the dimension and the zoom level needed to create a cache canvas\n * big enough to host the object to be cached.\n * @private\n * @param {Object} dim.x width of object to be cached\n * @param {Object} dim.y height of object to be cached\n * @return {Object}.width width of canvas\n * @return {Object}.height height of canvas\n * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache\n * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache\n */\n _getCacheCanvasDimensions: function() {\n var dims = this.callSuper('_getCacheCanvasDimensions');\n var fontSize = this.fontSize;\n dims.width += fontSize * dims.zoomX;\n dims.height += fontSize * dims.zoomY;\n return dims;\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(ctx) {\n var path = this.path;\n path && !path.isNotVisible() && path._render(ctx);\n this._setTextStyles(ctx);\n this._renderTextLinesBackground(ctx);\n this._renderTextDecoration(ctx, 'underline');\n this._renderText(ctx);\n this._renderTextDecoration(ctx, 'overline');\n this._renderTextDecoration(ctx, 'linethrough');\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderText: function(ctx) {\n if (this.paintFirst === 'stroke') {\n this._renderTextStroke(ctx);\n this._renderTextFill(ctx);\n }\n else {\n this._renderTextFill(ctx);\n this._renderTextStroke(ctx);\n }\n },\n\n /**\n * Set the font parameter of the context with the object properties or with charStyle\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {Object} [charStyle] object with font style properties\n * @param {String} [charStyle.fontFamily] Font Family\n * @param {Number} [charStyle.fontSize] Font size in pixels. ( without px suffix )\n * @param {String} [charStyle.fontWeight] Font weight\n * @param {String} [charStyle.fontStyle] Font style (italic|normal)\n */\n _setTextStyles: function(ctx, charStyle, forMeasuring) {\n ctx.textBaseline = 'alphabetical';\n if (this.path) {\n switch (this.pathAlign) {\n case 'center':\n ctx.textBaseline = 'middle';\n break;\n case 'ascender':\n ctx.textBaseline = 'top';\n break;\n case 'descender':\n ctx.textBaseline = 'bottom';\n break;\n }\n }\n ctx.font = this._getFontDeclaration(charStyle, forMeasuring);\n },\n\n /**\n * calculate and return the text Width measuring each line.\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @return {Number} Maximum width of fabric.Text object\n */\n calcTextWidth: function() {\n var maxWidth = this.getLineWidth(0);\n\n for (var i = 1, len = this._textLines.length; i < len; i++) {\n var currentLineWidth = this.getLineWidth(i);\n if (currentLineWidth > maxWidth) {\n maxWidth = currentLineWidth;\n }\n }\n return maxWidth;\n },\n\n /**\n * @private\n * @param {String} method Method name (\"fillText\" or \"strokeText\")\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {String} line Text to render\n * @param {Number} left Left position of text\n * @param {Number} top Top position of text\n * @param {Number} lineIndex Index of a line in a text\n */\n _renderTextLine: function(method, ctx, line, left, top, lineIndex) {\n this._renderChars(method, ctx, line, left, top, lineIndex);\n },\n\n /**\n * Renders the text background for lines, taking care of style\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderTextLinesBackground: function(ctx) {\n if (!this.textBackgroundColor && !this.styleHas('textBackgroundColor')) {\n return;\n }\n var heightOfLine,\n lineLeftOffset, originalFill = ctx.fillStyle,\n line, lastColor,\n leftOffset = this._getLeftOffset(),\n lineTopOffset = this._getTopOffset(),\n boxStart = 0, boxWidth = 0, charBox, currentColor, path = this.path,\n drawStart;\n\n for (var i = 0, len = this._textLines.length; i < len; i++) {\n heightOfLine = this.getHeightOfLine(i);\n if (!this.textBackgroundColor && !this.styleHas('textBackgroundColor', i)) {\n lineTopOffset += heightOfLine;\n continue;\n }\n line = this._textLines[i];\n lineLeftOffset = this._getLineLeftOffset(i);\n boxWidth = 0;\n boxStart = 0;\n lastColor = this.getValueOfPropertyAt(i, 0, 'textBackgroundColor');\n for (var j = 0, jlen = line.length; j < jlen; j++) {\n charBox = this.__charBounds[i][j];\n currentColor = this.getValueOfPropertyAt(i, j, 'textBackgroundColor');\n if (path) {\n ctx.save();\n ctx.translate(charBox.renderLeft, charBox.renderTop);\n ctx.rotate(charBox.angle);\n ctx.fillStyle = currentColor;\n currentColor && ctx.fillRect(\n -charBox.width / 2,\n -heightOfLine / this.lineHeight * (1 - this._fontSizeFraction),\n charBox.width,\n heightOfLine / this.lineHeight\n );\n ctx.restore();\n }\n else if (currentColor !== lastColor) {\n drawStart = leftOffset + lineLeftOffset + boxStart;\n if (this.direction === 'rtl') {\n drawStart = this.width - drawStart - boxWidth;\n }\n ctx.fillStyle = lastColor;\n lastColor && ctx.fillRect(\n drawStart,\n lineTopOffset,\n boxWidth,\n heightOfLine / this.lineHeight\n );\n boxStart = charBox.left;\n boxWidth = charBox.width;\n lastColor = currentColor;\n }\n else {\n boxWidth += charBox.kernedWidth;\n }\n }\n if (currentColor && !path) {\n drawStart = leftOffset + lineLeftOffset + boxStart;\n if (this.direction === 'rtl') {\n drawStart = this.width - drawStart - boxWidth;\n }\n ctx.fillStyle = currentColor;\n ctx.fillRect(\n drawStart,\n lineTopOffset,\n boxWidth,\n heightOfLine / this.lineHeight\n );\n }\n lineTopOffset += heightOfLine;\n }\n ctx.fillStyle = originalFill;\n // if there is text background color no\n // other shadows should be casted\n this._removeShadow(ctx);\n },\n\n /**\n * @private\n * @param {Object} decl style declaration for cache\n * @param {String} decl.fontFamily fontFamily\n * @param {String} decl.fontStyle fontStyle\n * @param {String} decl.fontWeight fontWeight\n * @return {Object} reference to cache\n */\n getFontCache: function(decl) {\n var fontFamily = decl.fontFamily.toLowerCase();\n if (!fabric.charWidthsCache[fontFamily]) {\n fabric.charWidthsCache[fontFamily] = { };\n }\n var cache = fabric.charWidthsCache[fontFamily],\n cacheProp = decl.fontStyle.toLowerCase() + '_' + (decl.fontWeight + '').toLowerCase();\n if (!cache[cacheProp]) {\n cache[cacheProp] = { };\n }\n return cache[cacheProp];\n },\n\n /**\n * measure and return the width of a single character.\n * possibly overridden to accommodate different measure logic or\n * to hook some external lib for character measurement\n * @private\n * @param {String} _char, char to be measured\n * @param {Object} charStyle style of char to be measured\n * @param {String} [previousChar] previous char\n * @param {Object} [prevCharStyle] style of previous char\n */\n _measureChar: function(_char, charStyle, previousChar, prevCharStyle) {\n // first i try to return from cache\n var fontCache = this.getFontCache(charStyle), fontDeclaration = this._getFontDeclaration(charStyle),\n previousFontDeclaration = this._getFontDeclaration(prevCharStyle), couple = previousChar + _char,\n stylesAreEqual = fontDeclaration === previousFontDeclaration, width, coupleWidth, previousWidth,\n fontMultiplier = charStyle.fontSize / this.CACHE_FONT_SIZE, kernedWidth;\n\n if (previousChar && fontCache[previousChar] !== undefined) {\n previousWidth = fontCache[previousChar];\n }\n if (fontCache[_char] !== undefined) {\n kernedWidth = width = fontCache[_char];\n }\n if (stylesAreEqual && fontCache[couple] !== undefined) {\n coupleWidth = fontCache[couple];\n kernedWidth = coupleWidth - previousWidth;\n }\n if (width === undefined || previousWidth === undefined || coupleWidth === undefined) {\n var ctx = this.getMeasuringContext();\n // send a TRUE to specify measuring font size CACHE_FONT_SIZE\n this._setTextStyles(ctx, charStyle, true);\n }\n if (width === undefined) {\n kernedWidth = width = ctx.measureText(_char).width;\n fontCache[_char] = width;\n }\n if (previousWidth === undefined && stylesAreEqual && previousChar) {\n previousWidth = ctx.measureText(previousChar).width;\n fontCache[previousChar] = previousWidth;\n }\n if (stylesAreEqual && coupleWidth === undefined) {\n // we can measure the kerning couple and subtract the width of the previous character\n coupleWidth = ctx.measureText(couple).width;\n fontCache[couple] = coupleWidth;\n kernedWidth = coupleWidth - previousWidth;\n }\n return { width: width * fontMultiplier, kernedWidth: kernedWidth * fontMultiplier };\n },\n\n /**\n * Computes height of character at given position\n * @param {Number} line the line index number\n * @param {Number} _char the character index number\n * @return {Number} fontSize of the character\n */\n getHeightOfChar: function(line, _char) {\n return this.getValueOfPropertyAt(line, _char, 'fontSize');\n },\n\n /**\n * measure a text line measuring all characters.\n * @param {Number} lineIndex line number\n * @return {Number} Line width\n */\n measureLine: function(lineIndex) {\n var lineInfo = this._measureLine(lineIndex);\n if (this.charSpacing !== 0) {\n lineInfo.width -= this._getWidthOfCharSpacing();\n }\n if (lineInfo.width < 0) {\n lineInfo.width = 0;\n }\n return lineInfo;\n },\n\n /**\n * measure every grapheme of a line, populating __charBounds\n * @param {Number} lineIndex\n * @return {Object} object.width total width of characters\n * @return {Object} object.widthOfSpaces length of chars that match this._reSpacesAndTabs\n */\n _measureLine: function(lineIndex) {\n var width = 0, i, grapheme, line = this._textLines[lineIndex], prevGrapheme,\n graphemeInfo, numOfSpaces = 0, lineBounds = new Array(line.length),\n positionInPath = 0, startingPoint, totalPathLength, path = this.path,\n reverse = this.pathSide === 'right';\n\n this.__charBounds[lineIndex] = lineBounds;\n for (i = 0; i < line.length; i++) {\n grapheme = line[i];\n graphemeInfo = this._getGraphemeBox(grapheme, lineIndex, i, prevGrapheme);\n lineBounds[i] = graphemeInfo;\n width += graphemeInfo.kernedWidth;\n prevGrapheme = grapheme;\n }\n // this latest bound box represent the last character of the line\n // to simplify cursor handling in interactive mode.\n lineBounds[i] = {\n left: graphemeInfo ? graphemeInfo.left + graphemeInfo.width : 0,\n width: 0,\n kernedWidth: 0,\n height: this.fontSize\n };\n if (path) {\n totalPathLength = path.segmentsInfo[path.segmentsInfo.length - 1].length;\n startingPoint = fabric.util.getPointOnPath(path.path, 0, path.segmentsInfo);\n startingPoint.x += path.pathOffset.x;\n startingPoint.y += path.pathOffset.y;\n switch (this.textAlign) {\n case 'left':\n positionInPath = reverse ? (totalPathLength - width) : 0;\n break;\n case 'center':\n positionInPath = (totalPathLength - width) / 2;\n break;\n case 'right':\n positionInPath = reverse ? 0 : (totalPathLength - width);\n break;\n //todo - add support for justify\n }\n positionInPath += this.pathStartOffset * (reverse ? -1 : 1);\n for (i = reverse ? line.length - 1 : 0;\n reverse ? i >= 0 : i < line.length;\n reverse ? i-- : i++) {\n graphemeInfo = lineBounds[i];\n if (positionInPath > totalPathLength) {\n positionInPath %= totalPathLength;\n }\n else if (positionInPath < 0) {\n positionInPath += totalPathLength;\n }\n // it would probably much faster to send all the grapheme position for a line\n // and calculate path position/angle at once.\n this._setGraphemeOnPath(positionInPath, graphemeInfo, startingPoint);\n positionInPath += graphemeInfo.kernedWidth;\n }\n }\n return { width: width, numOfSpaces: numOfSpaces };\n },\n\n /**\n * Calculate the angle and the left,top position of the char that follow a path.\n * It appends it to graphemeInfo to be reused later at rendering\n * @private\n * @param {Number} positionInPath to be measured\n * @param {Object} graphemeInfo current grapheme box information\n * @param {Object} startingPoint position of the point\n */\n _setGraphemeOnPath: function(positionInPath, graphemeInfo, startingPoint) {\n var centerPosition = positionInPath + graphemeInfo.kernedWidth / 2,\n path = this.path;\n\n // we are at currentPositionOnPath. we want to know what point on the path is.\n var info = fabric.util.getPointOnPath(path.path, centerPosition, path.segmentsInfo);\n graphemeInfo.renderLeft = info.x - startingPoint.x;\n graphemeInfo.renderTop = info.y - startingPoint.y;\n graphemeInfo.angle = info.angle + (this.pathSide === 'right' ? Math.PI : 0);\n },\n\n /**\n * Measure and return the info of a single grapheme.\n * needs the the info of previous graphemes already filled\n * @private\n * @param {String} grapheme to be measured\n * @param {Number} lineIndex index of the line where the char is\n * @param {Number} charIndex position in the line\n * @param {String} [prevGrapheme] character preceding the one to be measured\n */\n _getGraphemeBox: function(grapheme, lineIndex, charIndex, prevGrapheme, skipLeft) {\n var style = this.getCompleteStyleDeclaration(lineIndex, charIndex),\n prevStyle = prevGrapheme ? this.getCompleteStyleDeclaration(lineIndex, charIndex - 1) : { },\n info = this._measureChar(grapheme, style, prevGrapheme, prevStyle),\n kernedWidth = info.kernedWidth,\n width = info.width, charSpacing;\n\n if (this.charSpacing !== 0) {\n charSpacing = this._getWidthOfCharSpacing();\n width += charSpacing;\n kernedWidth += charSpacing;\n }\n\n var box = {\n width: width,\n left: 0,\n height: style.fontSize,\n kernedWidth: kernedWidth,\n deltaY: style.deltaY,\n };\n if (charIndex > 0 && !skipLeft) {\n var previousBox = this.__charBounds[lineIndex][charIndex - 1];\n box.left = previousBox.left + previousBox.width + info.kernedWidth - info.width;\n }\n return box;\n },\n\n /**\n * Calculate height of line at 'lineIndex'\n * @param {Number} lineIndex index of line to calculate\n * @return {Number}\n */\n getHeightOfLine: function(lineIndex) {\n if (this.__lineHeights[lineIndex]) {\n return this.__lineHeights[lineIndex];\n }\n\n var line = this._textLines[lineIndex],\n // char 0 is measured before the line cycle because it nneds to char\n // emptylines\n maxHeight = this.getHeightOfChar(lineIndex, 0);\n for (var i = 1, len = line.length; i < len; i++) {\n maxHeight = Math.max(this.getHeightOfChar(lineIndex, i), maxHeight);\n }\n\n return this.__lineHeights[lineIndex] = maxHeight * this.lineHeight * this._fontSizeMult;\n },\n\n /**\n * Calculate text box height\n */\n calcTextHeight: function() {\n var lineHeight, height = 0;\n for (var i = 0, len = this._textLines.length; i < len; i++) {\n lineHeight = this.getHeightOfLine(i);\n height += (i === len - 1 ? lineHeight / this.lineHeight : lineHeight);\n }\n return height;\n },\n\n /**\n * @private\n * @return {Number} Left offset\n */\n _getLeftOffset: function() {\n return this.direction === 'ltr' ? -this.width / 2 : this.width / 2;\n },\n\n /**\n * @private\n * @return {Number} Top offset\n */\n _getTopOffset: function() {\n return -this.height / 2;\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {String} method Method name (\"fillText\" or \"strokeText\")\n */\n _renderTextCommon: function(ctx, method) {\n ctx.save();\n var lineHeights = 0, left = this._getLeftOffset(), top = this._getTopOffset();\n for (var i = 0, len = this._textLines.length; i < len; i++) {\n var heightOfLine = this.getHeightOfLine(i),\n maxHeight = heightOfLine / this.lineHeight,\n leftOffset = this._getLineLeftOffset(i);\n this._renderTextLine(\n method,\n ctx,\n this._textLines[i],\n left + leftOffset,\n top + lineHeights + maxHeight,\n i\n );\n lineHeights += heightOfLine;\n }\n ctx.restore();\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderTextFill: function(ctx) {\n if (!this.fill && !this.styleHas('fill')) {\n return;\n }\n\n this._renderTextCommon(ctx, 'fillText');\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderTextStroke: function(ctx) {\n if ((!this.stroke || this.strokeWidth === 0) && this.isEmptyStyles()) {\n return;\n }\n\n if (this.shadow && !this.shadow.affectStroke) {\n this._removeShadow(ctx);\n }\n\n ctx.save();\n this._setLineDash(ctx, this.strokeDashArray);\n ctx.beginPath();\n this._renderTextCommon(ctx, 'strokeText');\n ctx.closePath();\n ctx.restore();\n },\n\n /**\n * @private\n * @param {String} method fillText or strokeText.\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {Array} line Content of the line, splitted in an array by grapheme\n * @param {Number} left\n * @param {Number} top\n * @param {Number} lineIndex\n */\n _renderChars: function(method, ctx, line, left, top, lineIndex) {\n // set proper line offset\n var lineHeight = this.getHeightOfLine(lineIndex),\n isJustify = this.textAlign.indexOf('justify') !== -1,\n actualStyle,\n nextStyle,\n charsToRender = '',\n charBox,\n boxWidth = 0,\n timeToRender,\n path = this.path,\n shortCut = !isJustify && this.charSpacing === 0 && this.isEmptyStyles(lineIndex) && !path,\n isLtr = this.direction === 'ltr', sign = this.direction === 'ltr' ? 1 : -1,\n drawingLeft, currentDirection = ctx.canvas.getAttribute('dir');\n ctx.save();\n if (currentDirection !== this.direction) {\n ctx.canvas.setAttribute('dir', isLtr ? 'ltr' : 'rtl');\n ctx.direction = isLtr ? 'ltr' : 'rtl';\n ctx.textAlign = isLtr ? 'left' : 'right';\n }\n top -= lineHeight * this._fontSizeFraction / this.lineHeight;\n if (shortCut) {\n // render all the line in one pass without checking\n // drawingLeft = isLtr ? left : left - this.getLineWidth(lineIndex);\n this._renderChar(method, ctx, lineIndex, 0, line.join(''), left, top, lineHeight);\n ctx.restore();\n return;\n }\n for (var i = 0, len = line.length - 1; i <= len; i++) {\n timeToRender = i === len || this.charSpacing || path;\n charsToRender += line[i];\n charBox = this.__charBounds[lineIndex][i];\n if (boxWidth === 0) {\n left += sign * (charBox.kernedWidth - charBox.width);\n boxWidth += charBox.width;\n }\n else {\n boxWidth += charBox.kernedWidth;\n }\n if (isJustify && !timeToRender) {\n if (this._reSpaceAndTab.test(line[i])) {\n timeToRender = true;\n }\n }\n if (!timeToRender) {\n // if we have charSpacing, we render char by char\n actualStyle = actualStyle || this.getCompleteStyleDeclaration(lineIndex, i);\n nextStyle = this.getCompleteStyleDeclaration(lineIndex, i + 1);\n timeToRender = fabric.util.hasStyleChanged(actualStyle, nextStyle, false);\n }\n if (timeToRender) {\n if (path) {\n ctx.save();\n ctx.translate(charBox.renderLeft, charBox.renderTop);\n ctx.rotate(charBox.angle);\n this._renderChar(method, ctx, lineIndex, i, charsToRender, -boxWidth / 2, 0, lineHeight);\n ctx.restore();\n }\n else {\n drawingLeft = left;\n this._renderChar(method, ctx, lineIndex, i, charsToRender, drawingLeft, top, lineHeight);\n }\n charsToRender = '';\n actualStyle = nextStyle;\n left += sign * boxWidth;\n boxWidth = 0;\n }\n }\n ctx.restore();\n },\n\n /**\n * This function try to patch the missing gradientTransform on canvas gradients.\n * transforming a context to transform the gradient, is going to transform the stroke too.\n * we want to transform the gradient but not the stroke operation, so we create\n * a transformed gradient on a pattern and then we use the pattern instead of the gradient.\n * this method has drawbacks: is slow, is in low resolution, needs a patch for when the size\n * is limited.\n * @private\n * @param {fabric.Gradient} filler a fabric gradient instance\n * @return {CanvasPattern} a pattern to use as fill/stroke style\n */\n _applyPatternGradientTransformText: function(filler) {\n var pCanvas = fabric.util.createCanvasElement(), pCtx,\n // TODO: verify compatibility with strokeUniform\n width = this.width + this.strokeWidth, height = this.height + this.strokeWidth;\n pCanvas.width = width;\n pCanvas.height = height;\n pCtx = pCanvas.getContext('2d');\n pCtx.beginPath(); pCtx.moveTo(0, 0); pCtx.lineTo(width, 0); pCtx.lineTo(width, height);\n pCtx.lineTo(0, height); pCtx.closePath();\n pCtx.translate(width / 2, height / 2);\n pCtx.fillStyle = filler.toLive(pCtx);\n this._applyPatternGradientTransform(pCtx, filler);\n pCtx.fill();\n return pCtx.createPattern(pCanvas, 'no-repeat');\n },\n\n handleFiller: function(ctx, property, filler) {\n var offsetX, offsetY;\n if (filler.toLive) {\n if (filler.gradientUnits === 'percentage' || filler.gradientTransform || filler.patternTransform) {\n // need to transform gradient in a pattern.\n // this is a slow process. If you are hitting this codepath, and the object\n // is not using caching, you should consider switching it on.\n // we need a canvas as big as the current object caching canvas.\n offsetX = -this.width / 2;\n offsetY = -this.height / 2;\n ctx.translate(offsetX, offsetY);\n ctx[property] = this._applyPatternGradientTransformText(filler);\n return { offsetX: offsetX, offsetY: offsetY };\n }\n else {\n // is a simple gradient or pattern\n ctx[property] = filler.toLive(ctx, this);\n return this._applyPatternGradientTransform(ctx, filler);\n }\n }\n else {\n // is a color\n ctx[property] = filler;\n }\n return { offsetX: 0, offsetY: 0 };\n },\n\n _setStrokeStyles: function(ctx, decl) {\n ctx.lineWidth = decl.strokeWidth;\n ctx.lineCap = this.strokeLineCap;\n ctx.lineDashOffset = this.strokeDashOffset;\n ctx.lineJoin = this.strokeLineJoin;\n ctx.miterLimit = this.strokeMiterLimit;\n return this.handleFiller(ctx, 'strokeStyle', decl.stroke);\n },\n\n _setFillStyles: function(ctx, decl) {\n return this.handleFiller(ctx, 'fillStyle', decl.fill);\n },\n\n /**\n * @private\n * @param {String} method\n * @param {CanvasRenderingContext2D} ctx Context to render on\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @param {String} _char\n * @param {Number} left Left coordinate\n * @param {Number} top Top coordinate\n * @param {Number} lineHeight Height of the line\n */\n _renderChar: function(method, ctx, lineIndex, charIndex, _char, left, top) {\n var decl = this._getStyleDeclaration(lineIndex, charIndex),\n fullDecl = this.getCompleteStyleDeclaration(lineIndex, charIndex),\n shouldFill = method === 'fillText' && fullDecl.fill,\n shouldStroke = method === 'strokeText' && fullDecl.stroke && fullDecl.strokeWidth,\n fillOffsets, strokeOffsets;\n\n if (!shouldStroke && !shouldFill) {\n return;\n }\n ctx.save();\n\n shouldFill && (fillOffsets = this._setFillStyles(ctx, fullDecl));\n shouldStroke && (strokeOffsets = this._setStrokeStyles(ctx, fullDecl));\n\n ctx.font = this._getFontDeclaration(fullDecl);\n\n\n if (decl && decl.textBackgroundColor) {\n this._removeShadow(ctx);\n }\n if (decl && decl.deltaY) {\n top += decl.deltaY;\n }\n shouldFill && ctx.fillText(_char, left - fillOffsets.offsetX, top - fillOffsets.offsetY);\n shouldStroke && ctx.strokeText(_char, left - strokeOffsets.offsetX, top - strokeOffsets.offsetY);\n ctx.restore();\n },\n\n /**\n * Turns the character into a 'superior figure' (i.e. 'superscript')\n * @param {Number} start selection start\n * @param {Number} end selection end\n * @returns {fabric.Text} thisArg\n * @chainable\n */\n setSuperscript: function(start, end) {\n return this._setScript(start, end, this.superscript);\n },\n\n /**\n * Turns the character into an 'inferior figure' (i.e. 'subscript')\n * @param {Number} start selection start\n * @param {Number} end selection end\n * @returns {fabric.Text} thisArg\n * @chainable\n */\n setSubscript: function(start, end) {\n return this._setScript(start, end, this.subscript);\n },\n\n /**\n * Applies 'schema' at given position\n * @private\n * @param {Number} start selection start\n * @param {Number} end selection end\n * @param {Number} schema\n * @returns {fabric.Text} thisArg\n * @chainable\n */\n _setScript: function(start, end, schema) {\n var loc = this.get2DCursorLocation(start, true),\n fontSize = this.getValueOfPropertyAt(loc.lineIndex, loc.charIndex, 'fontSize'),\n dy = this.getValueOfPropertyAt(loc.lineIndex, loc.charIndex, 'deltaY'),\n style = { fontSize: fontSize * schema.size, deltaY: dy + fontSize * schema.baseline };\n this.setSelectionStyles(style, start, end);\n return this;\n },\n\n /**\n * @private\n * @param {Number} lineIndex index text line\n * @return {Number} Line left offset\n */\n _getLineLeftOffset: function(lineIndex) {\n var lineWidth = this.getLineWidth(lineIndex),\n lineDiff = this.width - lineWidth, textAlign = this.textAlign, direction = this.direction,\n isEndOfWrapping, leftOffset = 0, isEndOfWrapping = this.isEndOfWrapping(lineIndex);\n if (textAlign === 'justify'\n || (textAlign === 'justify-center' && !isEndOfWrapping)\n || (textAlign === 'justify-right' && !isEndOfWrapping)\n || (textAlign === 'justify-left' && !isEndOfWrapping)\n ) {\n return 0;\n }\n if (textAlign === 'center') {\n leftOffset = lineDiff / 2;\n }\n if (textAlign === 'right') {\n leftOffset = lineDiff;\n }\n if (textAlign === 'justify-center') {\n leftOffset = lineDiff / 2;\n }\n if (textAlign === 'justify-right') {\n leftOffset = lineDiff;\n }\n if (direction === 'rtl') {\n leftOffset -= lineDiff;\n }\n return leftOffset;\n },\n\n /**\n * @private\n */\n _clearCache: function() {\n this.__lineWidths = [];\n this.__lineHeights = [];\n this.__charBounds = [];\n },\n\n /**\n * @private\n */\n _shouldClearDimensionCache: function() {\n var shouldClear = this._forceClearCache;\n shouldClear || (shouldClear = this.hasStateChanged('_dimensionAffectingProps'));\n if (shouldClear) {\n this.dirty = true;\n this._forceClearCache = false;\n }\n return shouldClear;\n },\n\n /**\n * Measure a single line given its index. Used to calculate the initial\n * text bounding box. The values are calculated and stored in __lineWidths cache.\n * @private\n * @param {Number} lineIndex line number\n * @return {Number} Line width\n */\n getLineWidth: function(lineIndex) {\n if (this.__lineWidths[lineIndex] !== undefined) {\n return this.__lineWidths[lineIndex];\n }\n\n var lineInfo = this.measureLine(lineIndex);\n var width = lineInfo.width;\n this.__lineWidths[lineIndex] = width;\n return width;\n },\n\n _getWidthOfCharSpacing: function() {\n if (this.charSpacing !== 0) {\n return this.fontSize * this.charSpacing / 1000;\n }\n return 0;\n },\n\n /**\n * Retrieves the value of property at given character position\n * @param {Number} lineIndex the line number\n * @param {Number} charIndex the character number\n * @param {String} property the property name\n * @returns the value of 'property'\n */\n getValueOfPropertyAt: function(lineIndex, charIndex, property) {\n var charStyle = this._getStyleDeclaration(lineIndex, charIndex);\n if (charStyle && typeof charStyle[property] !== 'undefined') {\n return charStyle[property];\n }\n return this[property];\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _renderTextDecoration: function(ctx, type) {\n if (!this[type] && !this.styleHas(type)) {\n return;\n }\n var heightOfLine, size, _size,\n lineLeftOffset, dy, _dy,\n line, lastDecoration,\n leftOffset = this._getLeftOffset(),\n topOffset = this._getTopOffset(), top,\n boxStart, boxWidth, charBox, currentDecoration,\n maxHeight, currentFill, lastFill, path = this.path,\n charSpacing = this._getWidthOfCharSpacing(),\n offsetY = this.offsets[type];\n\n for (var i = 0, len = this._textLines.length; i < len; i++) {\n heightOfLine = this.getHeightOfLine(i);\n if (!this[type] && !this.styleHas(type, i)) {\n topOffset += heightOfLine;\n continue;\n }\n line = this._textLines[i];\n maxHeight = heightOfLine / this.lineHeight;\n lineLeftOffset = this._getLineLeftOffset(i);\n boxStart = 0;\n boxWidth = 0;\n lastDecoration = this.getValueOfPropertyAt(i, 0, type);\n lastFill = this.getValueOfPropertyAt(i, 0, 'fill');\n top = topOffset + maxHeight * (1 - this._fontSizeFraction);\n size = this.getHeightOfChar(i, 0);\n dy = this.getValueOfPropertyAt(i, 0, 'deltaY');\n for (var j = 0, jlen = line.length; j < jlen; j++) {\n charBox = this.__charBounds[i][j];\n currentDecoration = this.getValueOfPropertyAt(i, j, type);\n currentFill = this.getValueOfPropertyAt(i, j, 'fill');\n _size = this.getHeightOfChar(i, j);\n _dy = this.getValueOfPropertyAt(i, j, 'deltaY');\n if (path && currentDecoration && currentFill) {\n ctx.save();\n ctx.fillStyle = lastFill;\n ctx.translate(charBox.renderLeft, charBox.renderTop);\n ctx.rotate(charBox.angle);\n ctx.fillRect(\n -charBox.kernedWidth / 2,\n offsetY * _size + _dy,\n charBox.kernedWidth,\n this.fontSize / 15\n );\n ctx.restore();\n }\n else if (\n (currentDecoration !== lastDecoration || currentFill !== lastFill || _size !== size || _dy !== dy)\n && boxWidth > 0\n ) {\n var drawStart = leftOffset + lineLeftOffset + boxStart;\n if (this.direction === 'rtl') {\n drawStart = this.width - drawStart - boxWidth;\n }\n if (lastDecoration && lastFill) {\n ctx.fillStyle = lastFill;\n ctx.fillRect(\n drawStart,\n top + offsetY * size + dy,\n boxWidth,\n this.fontSize / 15\n );\n }\n boxStart = charBox.left;\n boxWidth = charBox.width;\n lastDecoration = currentDecoration;\n lastFill = currentFill;\n size = _size;\n dy = _dy;\n }\n else {\n boxWidth += charBox.kernedWidth;\n }\n }\n var drawStart = leftOffset + lineLeftOffset + boxStart;\n if (this.direction === 'rtl') {\n drawStart = this.width - drawStart - boxWidth;\n }\n ctx.fillStyle = currentFill;\n currentDecoration && currentFill && ctx.fillRect(\n drawStart,\n top + offsetY * size + dy,\n boxWidth - charSpacing,\n this.fontSize / 15\n );\n topOffset += heightOfLine;\n }\n // if there is text background color no\n // other shadows should be casted\n this._removeShadow(ctx);\n },\n\n /**\n * return font declaration string for canvas context\n * @param {Object} [styleObject] object\n * @returns {String} font declaration formatted for canvas context.\n */\n _getFontDeclaration: function(styleObject, forMeasuring) {\n var style = styleObject || this, family = this.fontFamily,\n fontIsGeneric = fabric.Text.genericFonts.indexOf(family.toLowerCase()) > -1;\n var fontFamily = family === undefined ||\n family.indexOf('\\'') > -1 || family.indexOf(',') > -1 ||\n family.indexOf('\"') > -1 || fontIsGeneric\n ? style.fontFamily : '\"' + style.fontFamily + '\"';\n return [\n // node-canvas needs \"weight style\", while browsers need \"style weight\"\n // verify if this can be fixed in JSDOM\n (fabric.isLikelyNode ? style.fontWeight : style.fontStyle),\n (fabric.isLikelyNode ? style.fontStyle : style.fontWeight),\n forMeasuring ? this.CACHE_FONT_SIZE + 'px' : style.fontSize + 'px',\n fontFamily\n ].join(' ');\n },\n\n /**\n * Renders text instance on a specified context\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n render: function(ctx) {\n // do not render if object is not visible\n if (!this.visible) {\n return;\n }\n if (this.canvas && this.canvas.skipOffscreen && !this.group && !this.isOnScreen()) {\n return;\n }\n if (this._shouldClearDimensionCache()) {\n this.initDimensions();\n }\n this.callSuper('render', ctx);\n },\n\n /**\n * Returns the text as an array of lines.\n * @param {String} text text to split\n * @returns {Array} Lines in the text\n */\n _splitTextIntoLines: function(text) {\n var lines = text.split(this._reNewline),\n newLines = new Array(lines.length),\n newLine = ['\\n'],\n newText = [];\n for (var i = 0; i < lines.length; i++) {\n newLines[i] = fabric.util.string.graphemeSplit(lines[i]);\n newText = newText.concat(newLines[i], newLine);\n }\n newText.pop();\n return { _unwrappedLines: newLines, lines: lines, graphemeText: newText, graphemeLines: newLines };\n },\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} Object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n var allProperties = additionalProps.concat(propertiesToInclude);\n var obj = this.callSuper('toObject', allProperties);\n obj.styles = fabric.util.stylesToArray(this.styles, this.text);\n if (obj.path) {\n obj.path = this.path.toObject();\n }\n return obj;\n },\n\n /**\n * Sets property to a given value. When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. If you need to update those, call `setCoords()`.\n * @param {String|Object} key Property name or object (if object, iterate over the object properties)\n * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)\n * @return {fabric.Object} thisArg\n * @chainable\n */\n set: function(key, value) {\n this.callSuper('set', key, value);\n var needsDims = false;\n var isAddingPath = false;\n if (typeof key === 'object') {\n for (var _key in key) {\n if (_key === 'path') {\n this.setPathInfo();\n }\n needsDims = needsDims || this._dimensionAffectingProps.indexOf(_key) !== -1;\n isAddingPath = isAddingPath || _key === 'path';\n }\n }\n else {\n needsDims = this._dimensionAffectingProps.indexOf(key) !== -1;\n isAddingPath = key === 'path';\n }\n if (isAddingPath) {\n this.setPathInfo();\n }\n if (needsDims) {\n this.initDimensions();\n this.setCoords();\n }\n return this;\n },\n\n /**\n * Returns complexity of an instance\n * @return {Number} complexity\n */\n complexity: function() {\n return 1;\n }\n });\n\n /* _FROM_SVG_START_ */\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link fabric.Text.fromElement})\n * @static\n * @memberOf fabric.Text\n * @see: http://www.w3.org/TR/SVG/text.html#TextElement\n */\n fabric.Text.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat(\n 'x y dx dy font-family font-style font-weight font-size letter-spacing text-decoration text-anchor'.split(' '));\n\n /**\n * Default SVG font size\n * @static\n * @memberOf fabric.Text\n */\n fabric.Text.DEFAULT_SVG_FONT_SIZE = 16;\n\n /**\n * Returns fabric.Text instance from an SVG element (not yet implemented)\n * @static\n * @memberOf fabric.Text\n * @param {SVGElement} element Element to parse\n * @param {Function} callback callback function invoked after parsing\n * @param {Object} [options] Options object\n */\n fabric.Text.fromElement = function(element, callback, options) {\n if (!element) {\n return callback(null);\n }\n\n var parsedAttributes = fabric.parseAttributes(element, fabric.Text.ATTRIBUTE_NAMES),\n parsedAnchor = parsedAttributes.textAnchor || 'left';\n options = fabric.util.object.extend((options ? clone(options) : { }), parsedAttributes);\n\n options.top = options.top || 0;\n options.left = options.left || 0;\n if (parsedAttributes.textDecoration) {\n var textDecoration = parsedAttributes.textDecoration;\n if (textDecoration.indexOf('underline') !== -1) {\n options.underline = true;\n }\n if (textDecoration.indexOf('overline') !== -1) {\n options.overline = true;\n }\n if (textDecoration.indexOf('line-through') !== -1) {\n options.linethrough = true;\n }\n delete options.textDecoration;\n }\n if ('dx' in parsedAttributes) {\n options.left += parsedAttributes.dx;\n }\n if ('dy' in parsedAttributes) {\n options.top += parsedAttributes.dy;\n }\n if (!('fontSize' in options)) {\n options.fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;\n }\n\n var textContent = '';\n\n // The XML is not properly parsed in IE9 so a workaround to get\n // textContent is through firstChild.data. Another workaround would be\n // to convert XML loaded from a file to be converted using DOMParser (same way loadSVGFromString() does)\n if (!('textContent' in element)) {\n if ('firstChild' in element && element.firstChild !== null) {\n if ('data' in element.firstChild && element.firstChild.data !== null) {\n textContent = element.firstChild.data;\n }\n }\n }\n else {\n textContent = element.textContent;\n }\n\n textContent = textContent.replace(/^\\s+|\\s+$|\\n+/g, '').replace(/\\s+/g, ' ');\n var originalStrokeWidth = options.strokeWidth;\n options.strokeWidth = 0;\n\n var text = new fabric.Text(textContent, options),\n textHeightScaleFactor = text.getScaledHeight() / text.height,\n lineHeightDiff = (text.height + text.strokeWidth) * text.lineHeight - text.height,\n scaledDiff = lineHeightDiff * textHeightScaleFactor,\n textHeight = text.getScaledHeight() + scaledDiff,\n offX = 0;\n /*\n Adjust positioning:\n x/y attributes in SVG correspond to the bottom-left corner of text bounding box\n fabric output by default at top, left.\n */\n if (parsedAnchor === 'center') {\n offX = text.getScaledWidth() / 2;\n }\n if (parsedAnchor === 'right') {\n offX = text.getScaledWidth();\n }\n text.set({\n left: text.left - offX,\n top: text.top - (textHeight - text.fontSize * (0.07 + text._fontSizeFraction)) / text.lineHeight,\n strokeWidth: typeof originalStrokeWidth !== 'undefined' ? originalStrokeWidth : 1,\n });\n callback(text);\n };\n /* _FROM_SVG_END_ */\n\n /**\n * Returns fabric.Text instance from an object representation\n * @static\n * @memberOf fabric.Text\n * @param {Object} object plain js Object to create an instance from\n * @param {Function} [callback] Callback to invoke when an fabric.Text instance is created\n */\n fabric.Text.fromObject = function(object, callback) {\n var objectCopy = clone(object), path = object.path;\n delete objectCopy.path;\n return fabric.Object._fromObject('Text', objectCopy, function(textInstance) {\n textInstance.styles = fabric.util.stylesFromArray(object.styles, object.text);\n if (path) {\n fabric.Object._fromObject('Path', path, function(pathInstance) {\n textInstance.set('path', pathInstance);\n callback(textInstance);\n }, 'path');\n }\n else {\n callback(textInstance);\n }\n }, 'text');\n };\n\n fabric.Text.genericFonts = ['sans-serif', 'serif', 'cursive', 'fantasy', 'monospace'];\n\n fabric.util.createAccessors && fabric.util.createAccessors(fabric.Text);\n\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function() {\n fabric.util.object.extend(fabric.Text.prototype, /** @lends fabric.Text.prototype */ {\n /**\n * Returns true if object has no styling or no styling in a line\n * @param {Number} lineIndex , lineIndex is on wrapped lines.\n * @return {Boolean}\n */\n isEmptyStyles: function(lineIndex) {\n if (!this.styles) {\n return true;\n }\n if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {\n return true;\n }\n var obj = typeof lineIndex === 'undefined' ? this.styles : { line: this.styles[lineIndex] };\n for (var p1 in obj) {\n for (var p2 in obj[p1]) {\n // eslint-disable-next-line no-unused-vars\n for (var p3 in obj[p1][p2]) {\n return false;\n }\n }\n }\n return true;\n },\n\n /**\n * Returns true if object has a style property or has it ina specified line\n * This function is used to detect if a text will use a particular property or not.\n * @param {String} property to check for\n * @param {Number} lineIndex to check the style on\n * @return {Boolean}\n */\n styleHas: function(property, lineIndex) {\n if (!this.styles || !property || property === '') {\n return false;\n }\n if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {\n return false;\n }\n var obj = typeof lineIndex === 'undefined' ? this.styles : { 0: this.styles[lineIndex] };\n // eslint-disable-next-line\n for (var p1 in obj) {\n // eslint-disable-next-line\n for (var p2 in obj[p1]) {\n if (typeof obj[p1][p2][property] !== 'undefined') {\n return true;\n }\n }\n }\n return false;\n },\n\n /**\n * Check if characters in a text have a value for a property\n * whose value matches the textbox's value for that property. If so,\n * the character-level property is deleted. If the character\n * has no other properties, then it is also deleted. Finally,\n * if the line containing that character has no other characters\n * then it also is deleted.\n *\n * @param {string} property The property to compare between characters and text.\n */\n cleanStyle: function(property) {\n if (!this.styles || !property || property === '') {\n return false;\n }\n var obj = this.styles, stylesCount = 0, letterCount, stylePropertyValue,\n allStyleObjectPropertiesMatch = true, graphemeCount = 0, styleObject;\n // eslint-disable-next-line\n for (var p1 in obj) {\n letterCount = 0;\n // eslint-disable-next-line\n for (var p2 in obj[p1]) {\n var styleObject = obj[p1][p2],\n stylePropertyHasBeenSet = styleObject.hasOwnProperty(property);\n\n stylesCount++;\n\n if (stylePropertyHasBeenSet) {\n if (!stylePropertyValue) {\n stylePropertyValue = styleObject[property];\n }\n else if (styleObject[property] !== stylePropertyValue) {\n allStyleObjectPropertiesMatch = false;\n }\n\n if (styleObject[property] === this[property]) {\n delete styleObject[property];\n }\n }\n else {\n allStyleObjectPropertiesMatch = false;\n }\n\n if (Object.keys(styleObject).length !== 0) {\n letterCount++;\n }\n else {\n delete obj[p1][p2];\n }\n }\n\n if (letterCount === 0) {\n delete obj[p1];\n }\n }\n // if every grapheme has the same style set then\n // delete those styles and set it on the parent\n for (var i = 0; i < this._textLines.length; i++) {\n graphemeCount += this._textLines[i].length;\n }\n if (allStyleObjectPropertiesMatch && stylesCount === graphemeCount) {\n this[property] = stylePropertyValue;\n this.removeStyle(property);\n }\n },\n\n /**\n * Remove a style property or properties from all individual character styles\n * in a text object. Deletes the character style object if it contains no other style\n * props. Deletes a line style object if it contains no other character styles.\n *\n * @param {String} props The property to remove from character styles.\n */\n removeStyle: function(property) {\n if (!this.styles || !property || property === '') {\n return;\n }\n var obj = this.styles, line, lineNum, charNum;\n for (lineNum in obj) {\n line = obj[lineNum];\n for (charNum in line) {\n delete line[charNum][property];\n if (Object.keys(line[charNum]).length === 0) {\n delete line[charNum];\n }\n }\n if (Object.keys(line).length === 0) {\n delete obj[lineNum];\n }\n }\n },\n\n /**\n * @private\n */\n _extendStyles: function(index, styles) {\n var loc = this.get2DCursorLocation(index);\n\n if (!this._getLineStyle(loc.lineIndex)) {\n this._setLineStyle(loc.lineIndex);\n }\n\n if (!this._getStyleDeclaration(loc.lineIndex, loc.charIndex)) {\n this._setStyleDeclaration(loc.lineIndex, loc.charIndex, {});\n }\n\n fabric.util.object.extend(this._getStyleDeclaration(loc.lineIndex, loc.charIndex), styles);\n },\n\n /**\n * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start)\n * @param {Number} [selectionStart] Optional index. When not given, current selectionStart is used.\n * @param {Boolean} [skipWrapping] consider the location for unwrapped lines. useful to manage styles.\n */\n get2DCursorLocation: function(selectionStart, skipWrapping) {\n if (typeof selectionStart === 'undefined') {\n selectionStart = this.selectionStart;\n }\n var lines = skipWrapping ? this._unwrappedTextLines : this._textLines,\n len = lines.length;\n for (var i = 0; i < len; i++) {\n if (selectionStart <= lines[i].length) {\n return {\n lineIndex: i,\n charIndex: selectionStart\n };\n }\n selectionStart -= lines[i].length + this.missingNewlineOffset(i);\n }\n return {\n lineIndex: i - 1,\n charIndex: lines[i - 1].length < selectionStart ? lines[i - 1].length : selectionStart\n };\n },\n\n /**\n * Gets style of a current selection/cursor (at the start position)\n * if startIndex or endIndex are not provided, selectionStart or selectionEnd will be used.\n * @param {Number} [startIndex] Start index to get styles at\n * @param {Number} [endIndex] End index to get styles at, if not specified selectionEnd or startIndex + 1\n * @param {Boolean} [complete] get full style or not\n * @return {Array} styles an array with one, zero or more Style objects\n */\n getSelectionStyles: function(startIndex, endIndex, complete) {\n if (typeof startIndex === 'undefined') {\n startIndex = this.selectionStart || 0;\n }\n if (typeof endIndex === 'undefined') {\n endIndex = this.selectionEnd || startIndex;\n }\n var styles = [];\n for (var i = startIndex; i < endIndex; i++) {\n styles.push(this.getStyleAtPosition(i, complete));\n }\n return styles;\n },\n\n /**\n * Gets style of a current selection/cursor position\n * @param {Number} position to get styles at\n * @param {Boolean} [complete] full style if true\n * @return {Object} style Style object at a specified index\n * @private\n */\n getStyleAtPosition: function(position, complete) {\n var loc = this.get2DCursorLocation(position),\n style = complete ? this.getCompleteStyleDeclaration(loc.lineIndex, loc.charIndex) :\n this._getStyleDeclaration(loc.lineIndex, loc.charIndex);\n return style || {};\n },\n\n /**\n * Sets style of a current selection, if no selection exist, do not set anything.\n * @param {Object} [styles] Styles object\n * @param {Number} [startIndex] Start index to get styles at\n * @param {Number} [endIndex] End index to get styles at, if not specified selectionEnd or startIndex + 1\n * @return {fabric.IText} thisArg\n * @chainable\n */\n setSelectionStyles: function(styles, startIndex, endIndex) {\n if (typeof startIndex === 'undefined') {\n startIndex = this.selectionStart || 0;\n }\n if (typeof endIndex === 'undefined') {\n endIndex = this.selectionEnd || startIndex;\n }\n for (var i = startIndex; i < endIndex; i++) {\n this._extendStyles(i, styles);\n }\n /* not included in _extendStyles to avoid clearing cache more than once */\n this._forceClearCache = true;\n return this;\n },\n\n /**\n * get the reference, not a clone, of the style object for a given character\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @return {Object} style object\n */\n _getStyleDeclaration: function(lineIndex, charIndex) {\n var lineStyle = this.styles && this.styles[lineIndex];\n if (!lineStyle) {\n return null;\n }\n return lineStyle[charIndex];\n },\n\n /**\n * return a new object that contains all the style property for a character\n * the object returned is newly created\n * @param {Number} lineIndex of the line where the character is\n * @param {Number} charIndex position of the character on the line\n * @return {Object} style object\n */\n getCompleteStyleDeclaration: function(lineIndex, charIndex) {\n var style = this._getStyleDeclaration(lineIndex, charIndex) || { },\n styleObject = { }, prop;\n for (var i = 0; i < this._styleProperties.length; i++) {\n prop = this._styleProperties[i];\n styleObject[prop] = typeof style[prop] === 'undefined' ? this[prop] : style[prop];\n }\n return styleObject;\n },\n\n /**\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @param {Object} style\n * @private\n */\n _setStyleDeclaration: function(lineIndex, charIndex, style) {\n this.styles[lineIndex][charIndex] = style;\n },\n\n /**\n *\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @private\n */\n _deleteStyleDeclaration: function(lineIndex, charIndex) {\n delete this.styles[lineIndex][charIndex];\n },\n\n /**\n * @param {Number} lineIndex\n * @return {Boolean} if the line exists or not\n * @private\n */\n _getLineStyle: function(lineIndex) {\n return !!this.styles[lineIndex];\n },\n\n /**\n * Set the line style to an empty object so that is initialized\n * @param {Number} lineIndex\n * @private\n */\n _setLineStyle: function(lineIndex) {\n this.styles[lineIndex] = {};\n },\n\n /**\n * @param {Number} lineIndex\n * @private\n */\n _deleteLineStyle: function(lineIndex) {\n delete this.styles[lineIndex];\n }\n });\n})();\n\n\n(function() {\n\n function parseDecoration(object) {\n if (object.textDecoration) {\n object.textDecoration.indexOf('underline') > -1 && (object.underline = true);\n object.textDecoration.indexOf('line-through') > -1 && (object.linethrough = true);\n object.textDecoration.indexOf('overline') > -1 && (object.overline = true);\n delete object.textDecoration;\n }\n }\n\n /**\n * IText class (introduced in v1.4) Events are also fired with \"text:\"\n * prefix when observing canvas.\n * @class fabric.IText\n * @extends fabric.Text\n * @mixes fabric.Observable\n *\n * @fires changed\n * @fires selection:changed\n * @fires editing:entered\n * @fires editing:exited\n *\n * @return {fabric.IText} thisArg\n * @see {@link fabric.IText#initialize} for constructor definition\n *\n *

Supported key combinations:

\n *
\n   *   Move cursor:                    left, right, up, down\n   *   Select character:               shift + left, shift + right\n   *   Select text vertically:         shift + up, shift + down\n   *   Move cursor by word:            alt + left, alt + right\n   *   Select words:                   shift + alt + left, shift + alt + right\n   *   Move cursor to line start/end:  cmd + left, cmd + right or home, end\n   *   Select till start/end of line:  cmd + shift + left, cmd + shift + right or shift + home, shift + end\n   *   Jump to start/end of text:      cmd + up, cmd + down\n   *   Select till start/end of text:  cmd + shift + up, cmd + shift + down or shift + pgUp, shift + pgDown\n   *   Delete character:               backspace\n   *   Delete word:                    alt + backspace\n   *   Delete line:                    cmd + backspace\n   *   Forward delete:                 delete\n   *   Copy text:                      ctrl/cmd + c\n   *   Paste text:                     ctrl/cmd + v\n   *   Cut text:                       ctrl/cmd + x\n   *   Select entire text:             ctrl/cmd + a\n   *   Quit editing                    tab or esc\n   * 
\n *\n *

Supported mouse/touch combination

\n *
\n   *   Position cursor:                click/touch\n   *   Create selection:               click/touch & drag\n   *   Create selection:               click & shift + click\n   *   Select word:                    double click\n   *   Select line:                    triple click\n   * 
\n */\n fabric.IText = fabric.util.createClass(fabric.Text, fabric.Observable, /** @lends fabric.IText.prototype */ {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'i-text',\n\n /**\n * Index where text selection starts (or where cursor is when there is no selection)\n * @type Number\n * @default\n */\n selectionStart: 0,\n\n /**\n * Index where text selection ends\n * @type Number\n * @default\n */\n selectionEnd: 0,\n\n /**\n * Color of text selection\n * @type String\n * @default\n */\n selectionColor: 'rgba(17,119,255,0.3)',\n\n /**\n * Indicates whether text is in editing mode\n * @type Boolean\n * @default\n */\n isEditing: false,\n\n /**\n * Indicates whether a text can be edited\n * @type Boolean\n * @default\n */\n editable: true,\n\n /**\n * Border color of text object while it's in editing mode\n * @type String\n * @default\n */\n editingBorderColor: 'rgba(102,153,255,0.25)',\n\n /**\n * Width of cursor (in px)\n * @type Number\n * @default\n */\n cursorWidth: 2,\n\n /**\n * Color of text cursor color in editing mode.\n * if not set (default) will take color from the text.\n * if set to a color value that fabric can understand, it will\n * be used instead of the color of the text at the current position.\n * @type String\n * @default\n */\n cursorColor: '',\n\n /**\n * Delay between cursor blink (in ms)\n * @type Number\n * @default\n */\n cursorDelay: 1000,\n\n /**\n * Duration of cursor fadein (in ms)\n * @type Number\n * @default\n */\n cursorDuration: 600,\n\n /**\n * Indicates whether internal text char widths can be cached\n * @type Boolean\n * @default\n */\n caching: true,\n\n /**\n * DOM container to append the hiddenTextarea.\n * An alternative to attaching to the document.body.\n * Useful to reduce laggish redraw of the full document.body tree and\n * also with modals event capturing that won't let the textarea take focus.\n * @type HTMLElement\n * @default\n */\n hiddenTextareaContainer: null,\n\n /**\n * @private\n */\n _reSpace: /\\s|\\n/,\n\n /**\n * @private\n */\n _currentCursorOpacity: 0,\n\n /**\n * @private\n */\n _selectionDirection: null,\n\n /**\n * @private\n */\n _abortCursorAnimation: false,\n\n /**\n * @private\n */\n __widthOfSpace: [],\n\n /**\n * Helps determining when the text is in composition, so that the cursor\n * rendering is altered.\n */\n inCompositionMode: false,\n\n /**\n * Constructor\n * @param {String} text Text string\n * @param {Object} [options] Options object\n * @return {fabric.IText} thisArg\n */\n initialize: function(text, options) {\n this.callSuper('initialize', text, options);\n this.initBehavior();\n },\n\n /**\n * Sets selection start (left boundary of a selection)\n * @param {Number} index Index to set selection start to\n */\n setSelectionStart: function(index) {\n index = Math.max(index, 0);\n this._updateAndFire('selectionStart', index);\n },\n\n /**\n * Sets selection end (right boundary of a selection)\n * @param {Number} index Index to set selection end to\n */\n setSelectionEnd: function(index) {\n index = Math.min(index, this.text.length);\n this._updateAndFire('selectionEnd', index);\n },\n\n /**\n * @private\n * @param {String} property 'selectionStart' or 'selectionEnd'\n * @param {Number} index new position of property\n */\n _updateAndFire: function(property, index) {\n if (this[property] !== index) {\n this._fireSelectionChanged();\n this[property] = index;\n }\n this._updateTextarea();\n },\n\n /**\n * Fires the even of selection changed\n * @private\n */\n _fireSelectionChanged: function() {\n this.fire('selection:changed');\n this.canvas && this.canvas.fire('text:selection:changed', { target: this });\n },\n\n /**\n * Initialize text dimensions. Render all text on given context\n * or on a offscreen canvas to get the text width with measureText.\n * Updates this.width and this.height with the proper values.\n * Does not return dimensions.\n * @private\n */\n initDimensions: function() {\n this.isEditing && this.initDelayedCursor();\n this.clearContextTop();\n this.callSuper('initDimensions');\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n render: function(ctx) {\n this.clearContextTop();\n this.callSuper('render', ctx);\n // clear the cursorOffsetCache, so we ensure to calculate once per renderCursor\n // the correct position but not at every cursor animation.\n this.cursorOffsetCache = { };\n this.renderCursorOrSelection();\n },\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render: function(ctx) {\n this.callSuper('_render', ctx);\n },\n\n /**\n * Prepare and clean the contextTop\n */\n clearContextTop: function(skipRestore) {\n if (!this.isEditing || !this.canvas || !this.canvas.contextTop) {\n return;\n }\n var ctx = this.canvas.contextTop, v = this.canvas.viewportTransform;\n ctx.save();\n ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);\n this.transform(ctx);\n this._clearTextArea(ctx);\n skipRestore || ctx.restore();\n },\n /**\n * Renders cursor or selection (depending on what exists)\n * it does on the contextTop. If contextTop is not available, do nothing.\n */\n renderCursorOrSelection: function() {\n if (!this.isEditing || !this.canvas || !this.canvas.contextTop) {\n return;\n }\n var boundaries = this._getCursorBoundaries(),\n ctx = this.canvas.contextTop;\n this.clearContextTop(true);\n if (this.selectionStart === this.selectionEnd) {\n this.renderCursor(boundaries, ctx);\n }\n else {\n this.renderSelection(boundaries, ctx);\n }\n ctx.restore();\n },\n\n _clearTextArea: function(ctx) {\n // we add 4 pixel, to be sure to do not leave any pixel out\n var width = this.width + 4, height = this.height + 4;\n ctx.clearRect(-width / 2, -height / 2, width, height);\n },\n\n /**\n * Returns cursor boundaries (left, top, leftOffset, topOffset)\n * @private\n * @param {Array} chars Array of characters\n * @param {String} typeOfBoundaries\n */\n _getCursorBoundaries: function(position) {\n\n // left/top are left/top of entire text box\n // leftOffset/topOffset are offset from that left/top point of a text box\n\n if (typeof position === 'undefined') {\n position = this.selectionStart;\n }\n\n var left = this._getLeftOffset(),\n top = this._getTopOffset(),\n offsets = this._getCursorBoundariesOffsets(position);\n return {\n left: left,\n top: top,\n leftOffset: offsets.left,\n topOffset: offsets.top\n };\n },\n\n /**\n * @private\n */\n _getCursorBoundariesOffsets: function(position) {\n if (this.cursorOffsetCache && 'top' in this.cursorOffsetCache) {\n return this.cursorOffsetCache;\n }\n var lineLeftOffset,\n lineIndex,\n charIndex,\n topOffset = 0,\n leftOffset = 0,\n boundaries,\n cursorPosition = this.get2DCursorLocation(position);\n charIndex = cursorPosition.charIndex;\n lineIndex = cursorPosition.lineIndex;\n for (var i = 0; i < lineIndex; i++) {\n topOffset += this.getHeightOfLine(i);\n }\n lineLeftOffset = this._getLineLeftOffset(lineIndex);\n var bound = this.__charBounds[lineIndex][charIndex];\n bound && (leftOffset = bound.left);\n if (this.charSpacing !== 0 && charIndex === this._textLines[lineIndex].length) {\n leftOffset -= this._getWidthOfCharSpacing();\n }\n boundaries = {\n top: topOffset,\n left: lineLeftOffset + (leftOffset > 0 ? leftOffset : 0),\n };\n if (this.direction === 'rtl') {\n boundaries.left *= -1;\n }\n this.cursorOffsetCache = boundaries;\n return this.cursorOffsetCache;\n },\n\n /**\n * Renders cursor\n * @param {Object} boundaries\n * @param {CanvasRenderingContext2D} ctx transformed context to draw on\n */\n renderCursor: function(boundaries, ctx) {\n var cursorLocation = this.get2DCursorLocation(),\n lineIndex = cursorLocation.lineIndex,\n charIndex = cursorLocation.charIndex > 0 ? cursorLocation.charIndex - 1 : 0,\n charHeight = this.getValueOfPropertyAt(lineIndex, charIndex, 'fontSize'),\n multiplier = this.scaleX * this.canvas.getZoom(),\n cursorWidth = this.cursorWidth / multiplier,\n topOffset = boundaries.topOffset,\n dy = this.getValueOfPropertyAt(lineIndex, charIndex, 'deltaY');\n topOffset += (1 - this._fontSizeFraction) * this.getHeightOfLine(lineIndex) / this.lineHeight\n - charHeight * (1 - this._fontSizeFraction);\n\n if (this.inCompositionMode) {\n this.renderSelection(boundaries, ctx);\n }\n ctx.fillStyle = this.cursorColor || this.getValueOfPropertyAt(lineIndex, charIndex, 'fill');\n ctx.globalAlpha = this.__isMousedown ? 1 : this._currentCursorOpacity;\n ctx.fillRect(\n boundaries.left + boundaries.leftOffset - cursorWidth / 2,\n topOffset + boundaries.top + dy,\n cursorWidth,\n charHeight);\n },\n\n /**\n * Renders text selection\n * @param {Object} boundaries Object with left/top/leftOffset/topOffset\n * @param {CanvasRenderingContext2D} ctx transformed context to draw on\n */\n renderSelection: function(boundaries, ctx) {\n\n var selectionStart = this.inCompositionMode ? this.hiddenTextarea.selectionStart : this.selectionStart,\n selectionEnd = this.inCompositionMode ? this.hiddenTextarea.selectionEnd : this.selectionEnd,\n isJustify = this.textAlign.indexOf('justify') !== -1,\n start = this.get2DCursorLocation(selectionStart),\n end = this.get2DCursorLocation(selectionEnd),\n startLine = start.lineIndex,\n endLine = end.lineIndex,\n startChar = start.charIndex < 0 ? 0 : start.charIndex,\n endChar = end.charIndex < 0 ? 0 : end.charIndex;\n\n for (var i = startLine; i <= endLine; i++) {\n var lineOffset = this._getLineLeftOffset(i) || 0,\n lineHeight = this.getHeightOfLine(i),\n realLineHeight = 0, boxStart = 0, boxEnd = 0;\n\n if (i === startLine) {\n boxStart = this.__charBounds[startLine][startChar].left;\n }\n if (i >= startLine && i < endLine) {\n boxEnd = isJustify && !this.isEndOfWrapping(i) ? this.width : this.getLineWidth(i) || 5; // WTF is this 5?\n }\n else if (i === endLine) {\n if (endChar === 0) {\n boxEnd = this.__charBounds[endLine][endChar].left;\n }\n else {\n var charSpacing = this._getWidthOfCharSpacing();\n boxEnd = this.__charBounds[endLine][endChar - 1].left\n + this.__charBounds[endLine][endChar - 1].width - charSpacing;\n }\n }\n realLineHeight = lineHeight;\n if (this.lineHeight < 1 || (i === endLine && this.lineHeight > 1)) {\n lineHeight /= this.lineHeight;\n }\n var drawStart = boundaries.left + lineOffset + boxStart,\n drawWidth = boxEnd - boxStart,\n drawHeight = lineHeight, extraTop = 0;\n if (this.inCompositionMode) {\n ctx.fillStyle = this.compositionColor || 'black';\n drawHeight = 1;\n extraTop = lineHeight;\n }\n else {\n ctx.fillStyle = this.selectionColor;\n }\n if (this.direction === 'rtl') {\n drawStart = this.width - drawStart - drawWidth;\n }\n ctx.fillRect(\n drawStart,\n boundaries.top + boundaries.topOffset + extraTop,\n drawWidth,\n drawHeight);\n boundaries.topOffset += realLineHeight;\n }\n },\n\n /**\n * High level function to know the height of the cursor.\n * the currentChar is the one that precedes the cursor\n * Returns fontSize of char at the current cursor\n * Unused from the library, is for the end user\n * @return {Number} Character font size\n */\n getCurrentCharFontSize: function() {\n var cp = this._getCurrentCharIndex();\n return this.getValueOfPropertyAt(cp.l, cp.c, 'fontSize');\n },\n\n /**\n * High level function to know the color of the cursor.\n * the currentChar is the one that precedes the cursor\n * Returns color (fill) of char at the current cursor\n * if the text object has a pattern or gradient for filler, it will return that.\n * Unused by the library, is for the end user\n * @return {String | fabric.Gradient | fabric.Pattern} Character color (fill)\n */\n getCurrentCharColor: function() {\n var cp = this._getCurrentCharIndex();\n return this.getValueOfPropertyAt(cp.l, cp.c, 'fill');\n },\n\n /**\n * Returns the cursor position for the getCurrent.. functions\n * @private\n */\n _getCurrentCharIndex: function() {\n var cursorPosition = this.get2DCursorLocation(this.selectionStart, true),\n charIndex = cursorPosition.charIndex > 0 ? cursorPosition.charIndex - 1 : 0;\n return { l: cursorPosition.lineIndex, c: charIndex };\n }\n });\n\n /**\n * Returns fabric.IText instance from an object representation\n * @static\n * @memberOf fabric.IText\n * @param {Object} object Object to create an instance from\n * @param {function} [callback] invoked with new instance as argument\n */\n fabric.IText.fromObject = function(object, callback) {\n var styles = fabric.util.stylesFromArray(object.styles, object.text);\n //copy object to prevent mutation\n var objCopy = Object.assign({}, object, { styles: styles });\n parseDecoration(objCopy);\n if (objCopy.styles) {\n for (var i in objCopy.styles) {\n for (var j in objCopy.styles[i]) {\n parseDecoration(objCopy.styles[i][j]);\n }\n }\n }\n fabric.Object._fromObject('IText', objCopy, callback, 'text');\n };\n})();\n\n\n(function() {\n\n var clone = fabric.util.object.clone;\n\n fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {\n\n /**\n * Initializes all the interactive behavior of IText\n */\n initBehavior: function() {\n this.initAddedHandler();\n this.initRemovedHandler();\n this.initCursorSelectionHandlers();\n this.initDoubleClickSimulation();\n this.mouseMoveHandler = this.mouseMoveHandler.bind(this);\n },\n\n onDeselect: function() {\n this.isEditing && this.exitEditing();\n this.selected = false;\n },\n\n /**\n * Initializes \"added\" event handler\n */\n initAddedHandler: function() {\n var _this = this;\n this.on('added', function() {\n var canvas = _this.canvas;\n if (canvas) {\n if (!canvas._hasITextHandlers) {\n canvas._hasITextHandlers = true;\n _this._initCanvasHandlers(canvas);\n }\n canvas._iTextInstances = canvas._iTextInstances || [];\n canvas._iTextInstances.push(_this);\n }\n });\n },\n\n initRemovedHandler: function() {\n var _this = this;\n this.on('removed', function() {\n var canvas = _this.canvas;\n if (canvas) {\n canvas._iTextInstances = canvas._iTextInstances || [];\n fabric.util.removeFromArray(canvas._iTextInstances, _this);\n if (canvas._iTextInstances.length === 0) {\n canvas._hasITextHandlers = false;\n _this._removeCanvasHandlers(canvas);\n }\n }\n });\n },\n\n /**\n * register canvas event to manage exiting on other instances\n * @private\n */\n _initCanvasHandlers: function(canvas) {\n canvas._mouseUpITextHandler = function() {\n if (canvas._iTextInstances) {\n canvas._iTextInstances.forEach(function(obj) {\n obj.__isMousedown = false;\n });\n }\n };\n canvas.on('mouse:up', canvas._mouseUpITextHandler);\n },\n\n /**\n * remove canvas event to manage exiting on other instances\n * @private\n */\n _removeCanvasHandlers: function(canvas) {\n canvas.off('mouse:up', canvas._mouseUpITextHandler);\n },\n\n /**\n * @private\n */\n _tick: function() {\n this._currentTickState = this._animateCursor(this, 1, this.cursorDuration, '_onTickComplete');\n },\n\n /**\n * @private\n */\n _animateCursor: function(obj, targetOpacity, duration, completeMethod) {\n\n var tickState;\n\n tickState = {\n isAborted: false,\n abort: function() {\n this.isAborted = true;\n },\n };\n\n obj.animate('_currentCursorOpacity', targetOpacity, {\n duration: duration,\n onComplete: function() {\n if (!tickState.isAborted) {\n obj[completeMethod]();\n }\n },\n onChange: function() {\n // we do not want to animate a selection, only cursor\n if (obj.canvas && obj.selectionStart === obj.selectionEnd) {\n obj.renderCursorOrSelection();\n }\n },\n abort: function() {\n return tickState.isAborted;\n }\n });\n return tickState;\n },\n\n /**\n * @private\n */\n _onTickComplete: function() {\n\n var _this = this;\n\n if (this._cursorTimeout1) {\n clearTimeout(this._cursorTimeout1);\n }\n this._cursorTimeout1 = setTimeout(function() {\n _this._currentTickCompleteState = _this._animateCursor(_this, 0, this.cursorDuration / 2, '_tick');\n }, 100);\n },\n\n /**\n * Initializes delayed cursor\n */\n initDelayedCursor: function(restart) {\n var _this = this,\n delay = restart ? 0 : this.cursorDelay;\n\n this.abortCursorAnimation();\n this._currentCursorOpacity = 1;\n this._cursorTimeout2 = setTimeout(function() {\n _this._tick();\n }, delay);\n },\n\n /**\n * Aborts cursor animation and clears all timeouts\n */\n abortCursorAnimation: function() {\n var shouldClear = this._currentTickState || this._currentTickCompleteState,\n canvas = this.canvas;\n this._currentTickState && this._currentTickState.abort();\n this._currentTickCompleteState && this._currentTickCompleteState.abort();\n\n clearTimeout(this._cursorTimeout1);\n clearTimeout(this._cursorTimeout2);\n\n this._currentCursorOpacity = 0;\n // to clear just itext area we need to transform the context\n // it may not be worth it\n if (shouldClear && canvas) {\n canvas.clearContext(canvas.contextTop || canvas.contextContainer);\n }\n\n },\n\n /**\n * Selects entire text\n * @return {fabric.IText} thisArg\n * @chainable\n */\n selectAll: function() {\n this.selectionStart = 0;\n this.selectionEnd = this._text.length;\n this._fireSelectionChanged();\n this._updateTextarea();\n return this;\n },\n\n /**\n * Returns selected text\n * @return {String}\n */\n getSelectedText: function() {\n return this._text.slice(this.selectionStart, this.selectionEnd).join('');\n },\n\n /**\n * Find new selection index representing start of current word according to current selection index\n * @param {Number} startFrom Current selection index\n * @return {Number} New selection index\n */\n findWordBoundaryLeft: function(startFrom) {\n var offset = 0, index = startFrom - 1;\n\n // remove space before cursor first\n if (this._reSpace.test(this._text[index])) {\n while (this._reSpace.test(this._text[index])) {\n offset++;\n index--;\n }\n }\n while (/\\S/.test(this._text[index]) && index > -1) {\n offset++;\n index--;\n }\n\n return startFrom - offset;\n },\n\n /**\n * Find new selection index representing end of current word according to current selection index\n * @param {Number} startFrom Current selection index\n * @return {Number} New selection index\n */\n findWordBoundaryRight: function(startFrom) {\n var offset = 0, index = startFrom;\n\n // remove space after cursor first\n if (this._reSpace.test(this._text[index])) {\n while (this._reSpace.test(this._text[index])) {\n offset++;\n index++;\n }\n }\n while (/\\S/.test(this._text[index]) && index < this._text.length) {\n offset++;\n index++;\n }\n\n return startFrom + offset;\n },\n\n /**\n * Find new selection index representing start of current line according to current selection index\n * @param {Number} startFrom Current selection index\n * @return {Number} New selection index\n */\n findLineBoundaryLeft: function(startFrom) {\n var offset = 0, index = startFrom - 1;\n\n while (!/\\n/.test(this._text[index]) && index > -1) {\n offset++;\n index--;\n }\n\n return startFrom - offset;\n },\n\n /**\n * Find new selection index representing end of current line according to current selection index\n * @param {Number} startFrom Current selection index\n * @return {Number} New selection index\n */\n findLineBoundaryRight: function(startFrom) {\n var offset = 0, index = startFrom;\n\n while (!/\\n/.test(this._text[index]) && index < this._text.length) {\n offset++;\n index++;\n }\n\n return startFrom + offset;\n },\n\n /**\n * Finds index corresponding to beginning or end of a word\n * @param {Number} selectionStart Index of a character\n * @param {Number} direction 1 or -1\n * @return {Number} Index of the beginning or end of a word\n */\n searchWordBoundary: function(selectionStart, direction) {\n var text = this._text,\n index = this._reSpace.test(text[selectionStart]) ? selectionStart - 1 : selectionStart,\n _char = text[index],\n // wrong\n reNonWord = fabric.reNonWord;\n\n while (!reNonWord.test(_char) && index > 0 && index < text.length) {\n index += direction;\n _char = text[index];\n }\n if (reNonWord.test(_char)) {\n index += direction === 1 ? 0 : 1;\n }\n return index;\n },\n\n /**\n * Selects a word based on the index\n * @param {Number} selectionStart Index of a character\n */\n selectWord: function(selectionStart) {\n selectionStart = selectionStart || this.selectionStart;\n var newSelectionStart = this.searchWordBoundary(selectionStart, -1), /* search backwards */\n newSelectionEnd = this.searchWordBoundary(selectionStart, 1); /* search forward */\n\n this.selectionStart = newSelectionStart;\n this.selectionEnd = newSelectionEnd;\n this._fireSelectionChanged();\n this._updateTextarea();\n this.renderCursorOrSelection();\n },\n\n /**\n * Selects a line based on the index\n * @param {Number} selectionStart Index of a character\n * @return {fabric.IText} thisArg\n * @chainable\n */\n selectLine: function(selectionStart) {\n selectionStart = selectionStart || this.selectionStart;\n var newSelectionStart = this.findLineBoundaryLeft(selectionStart),\n newSelectionEnd = this.findLineBoundaryRight(selectionStart);\n\n this.selectionStart = newSelectionStart;\n this.selectionEnd = newSelectionEnd;\n this._fireSelectionChanged();\n this._updateTextarea();\n return this;\n },\n\n /**\n * Enters editing state\n * @return {fabric.IText} thisArg\n * @chainable\n */\n enterEditing: function(e) {\n if (this.isEditing || !this.editable) {\n return;\n }\n\n if (this.canvas) {\n this.canvas.calcOffset();\n this.exitEditingOnOthers(this.canvas);\n }\n\n this.isEditing = true;\n\n this.initHiddenTextarea(e);\n this.hiddenTextarea.focus();\n this.hiddenTextarea.value = this.text;\n this._updateTextarea();\n this._saveEditingProps();\n this._setEditingProps();\n this._textBeforeEdit = this.text;\n\n this._tick();\n this.fire('editing:entered');\n this._fireSelectionChanged();\n if (!this.canvas) {\n return this;\n }\n this.canvas.fire('text:editing:entered', { target: this });\n this.initMouseMoveHandler();\n this.canvas.requestRenderAll();\n return this;\n },\n\n exitEditingOnOthers: function(canvas) {\n if (canvas._iTextInstances) {\n canvas._iTextInstances.forEach(function(obj) {\n obj.selected = false;\n if (obj.isEditing) {\n obj.exitEditing();\n }\n });\n }\n },\n\n /**\n * Initializes \"mousemove\" event handler\n */\n initMouseMoveHandler: function() {\n this.canvas.on('mouse:move', this.mouseMoveHandler);\n },\n\n /**\n * @private\n */\n mouseMoveHandler: function(options) {\n if (!this.__isMousedown || !this.isEditing) {\n return;\n }\n\n // regain focus\n document.activeElement !== this.hiddenTextarea && this.hiddenTextarea.focus();\n\n var newSelectionStart = this.getSelectionStartFromPointer(options.e),\n currentStart = this.selectionStart,\n currentEnd = this.selectionEnd;\n if (\n (newSelectionStart !== this.__selectionStartOnMouseDown || currentStart === currentEnd)\n &&\n (currentStart === newSelectionStart || currentEnd === newSelectionStart)\n ) {\n return;\n }\n if (newSelectionStart > this.__selectionStartOnMouseDown) {\n this.selectionStart = this.__selectionStartOnMouseDown;\n this.selectionEnd = newSelectionStart;\n }\n else {\n this.selectionStart = newSelectionStart;\n this.selectionEnd = this.__selectionStartOnMouseDown;\n }\n if (this.selectionStart !== currentStart || this.selectionEnd !== currentEnd) {\n this.restartCursorIfNeeded();\n this._fireSelectionChanged();\n this._updateTextarea();\n this.renderCursorOrSelection();\n }\n },\n\n /**\n * @private\n */\n _setEditingProps: function() {\n this.hoverCursor = 'text';\n\n if (this.canvas) {\n this.canvas.defaultCursor = this.canvas.moveCursor = 'text';\n }\n\n this.borderColor = this.editingBorderColor;\n this.hasControls = this.selectable = false;\n this.lockMovementX = this.lockMovementY = true;\n },\n\n /**\n * convert from textarea to grapheme indexes\n */\n fromStringToGraphemeSelection: function(start, end, text) {\n var smallerTextStart = text.slice(0, start),\n graphemeStart = fabric.util.string.graphemeSplit(smallerTextStart).length;\n if (start === end) {\n return { selectionStart: graphemeStart, selectionEnd: graphemeStart };\n }\n var smallerTextEnd = text.slice(start, end),\n graphemeEnd = fabric.util.string.graphemeSplit(smallerTextEnd).length;\n return { selectionStart: graphemeStart, selectionEnd: graphemeStart + graphemeEnd };\n },\n\n /**\n * convert from fabric to textarea values\n */\n fromGraphemeToStringSelection: function(start, end, _text) {\n var smallerTextStart = _text.slice(0, start),\n graphemeStart = smallerTextStart.join('').length;\n if (start === end) {\n return { selectionStart: graphemeStart, selectionEnd: graphemeStart };\n }\n var smallerTextEnd = _text.slice(start, end),\n graphemeEnd = smallerTextEnd.join('').length;\n return { selectionStart: graphemeStart, selectionEnd: graphemeStart + graphemeEnd };\n },\n\n /**\n * @private\n */\n _updateTextarea: function() {\n this.cursorOffsetCache = { };\n if (!this.hiddenTextarea) {\n return;\n }\n if (!this.inCompositionMode) {\n var newSelection = this.fromGraphemeToStringSelection(this.selectionStart, this.selectionEnd, this._text);\n this.hiddenTextarea.selectionStart = newSelection.selectionStart;\n this.hiddenTextarea.selectionEnd = newSelection.selectionEnd;\n }\n this.updateTextareaPosition();\n },\n\n /**\n * @private\n */\n updateFromTextArea: function() {\n if (!this.hiddenTextarea) {\n return;\n }\n this.cursorOffsetCache = { };\n this.text = this.hiddenTextarea.value;\n if (this._shouldClearDimensionCache()) {\n this.initDimensions();\n this.setCoords();\n }\n var newSelection = this.fromStringToGraphemeSelection(\n this.hiddenTextarea.selectionStart, this.hiddenTextarea.selectionEnd, this.hiddenTextarea.value);\n this.selectionEnd = this.selectionStart = newSelection.selectionEnd;\n if (!this.inCompositionMode) {\n this.selectionStart = newSelection.selectionStart;\n }\n this.updateTextareaPosition();\n },\n\n /**\n * @private\n */\n updateTextareaPosition: function() {\n if (this.selectionStart === this.selectionEnd) {\n var style = this._calcTextareaPosition();\n this.hiddenTextarea.style.left = style.left;\n this.hiddenTextarea.style.top = style.top;\n }\n },\n\n /**\n * @private\n * @return {Object} style contains style for hiddenTextarea\n */\n _calcTextareaPosition: function() {\n if (!this.canvas) {\n return { x: 1, y: 1 };\n }\n var desiredPosition = this.inCompositionMode ? this.compositionStart : this.selectionStart,\n boundaries = this._getCursorBoundaries(desiredPosition),\n cursorLocation = this.get2DCursorLocation(desiredPosition),\n lineIndex = cursorLocation.lineIndex,\n charIndex = cursorLocation.charIndex,\n charHeight = this.getValueOfPropertyAt(lineIndex, charIndex, 'fontSize') * this.lineHeight,\n leftOffset = boundaries.leftOffset,\n m = this.calcTransformMatrix(),\n p = {\n x: boundaries.left + leftOffset,\n y: boundaries.top + boundaries.topOffset + charHeight\n },\n retinaScaling = this.canvas.getRetinaScaling(),\n upperCanvas = this.canvas.upperCanvasEl,\n upperCanvasWidth = upperCanvas.width / retinaScaling,\n upperCanvasHeight = upperCanvas.height / retinaScaling,\n maxWidth = upperCanvasWidth - charHeight,\n maxHeight = upperCanvasHeight - charHeight,\n scaleX = upperCanvas.clientWidth / upperCanvasWidth,\n scaleY = upperCanvas.clientHeight / upperCanvasHeight;\n\n p = fabric.util.transformPoint(p, m);\n p = fabric.util.transformPoint(p, this.canvas.viewportTransform);\n p.x *= scaleX;\n p.y *= scaleY;\n if (p.x < 0) {\n p.x = 0;\n }\n if (p.x > maxWidth) {\n p.x = maxWidth;\n }\n if (p.y < 0) {\n p.y = 0;\n }\n if (p.y > maxHeight) {\n p.y = maxHeight;\n }\n\n // add canvas offset on document\n p.x += this.canvas._offset.left;\n p.y += this.canvas._offset.top;\n\n return { left: p.x + 'px', top: p.y + 'px', fontSize: charHeight + 'px', charHeight: charHeight };\n },\n\n /**\n * @private\n */\n _saveEditingProps: function() {\n this._savedProps = {\n hasControls: this.hasControls,\n borderColor: this.borderColor,\n lockMovementX: this.lockMovementX,\n lockMovementY: this.lockMovementY,\n hoverCursor: this.hoverCursor,\n selectable: this.selectable,\n defaultCursor: this.canvas && this.canvas.defaultCursor,\n moveCursor: this.canvas && this.canvas.moveCursor\n };\n },\n\n /**\n * @private\n */\n _restoreEditingProps: function() {\n if (!this._savedProps) {\n return;\n }\n\n this.hoverCursor = this._savedProps.hoverCursor;\n this.hasControls = this._savedProps.hasControls;\n this.borderColor = this._savedProps.borderColor;\n this.selectable = this._savedProps.selectable;\n this.lockMovementX = this._savedProps.lockMovementX;\n this.lockMovementY = this._savedProps.lockMovementY;\n\n if (this.canvas) {\n this.canvas.defaultCursor = this._savedProps.defaultCursor;\n this.canvas.moveCursor = this._savedProps.moveCursor;\n }\n },\n\n /**\n * Exits from editing state\n * @return {fabric.IText} thisArg\n * @chainable\n */\n exitEditing: function() {\n var isTextChanged = (this._textBeforeEdit !== this.text);\n var hiddenTextarea = this.hiddenTextarea;\n this.selected = false;\n this.isEditing = false;\n\n this.selectionEnd = this.selectionStart;\n\n if (hiddenTextarea) {\n hiddenTextarea.blur && hiddenTextarea.blur();\n hiddenTextarea.parentNode && hiddenTextarea.parentNode.removeChild(hiddenTextarea);\n }\n this.hiddenTextarea = null;\n this.abortCursorAnimation();\n this._restoreEditingProps();\n this._currentCursorOpacity = 0;\n if (this._shouldClearDimensionCache()) {\n this.initDimensions();\n this.setCoords();\n }\n this.fire('editing:exited');\n isTextChanged && this.fire('modified');\n if (this.canvas) {\n this.canvas.off('mouse:move', this.mouseMoveHandler);\n this.canvas.fire('text:editing:exited', { target: this });\n isTextChanged && this.canvas.fire('object:modified', { target: this });\n }\n return this;\n },\n\n /**\n * @private\n */\n _removeExtraneousStyles: function() {\n for (var prop in this.styles) {\n if (!this._textLines[prop]) {\n delete this.styles[prop];\n }\n }\n },\n\n /**\n * remove and reflow a style block from start to end.\n * @param {Number} start linear start position for removal (included in removal)\n * @param {Number} end linear end position for removal ( excluded from removal )\n */\n removeStyleFromTo: function(start, end) {\n var cursorStart = this.get2DCursorLocation(start, true),\n cursorEnd = this.get2DCursorLocation(end, true),\n lineStart = cursorStart.lineIndex,\n charStart = cursorStart.charIndex,\n lineEnd = cursorEnd.lineIndex,\n charEnd = cursorEnd.charIndex,\n i, styleObj;\n if (lineStart !== lineEnd) {\n // step1 remove the trailing of lineStart\n if (this.styles[lineStart]) {\n for (i = charStart; i < this._unwrappedTextLines[lineStart].length; i++) {\n delete this.styles[lineStart][i];\n }\n }\n // step2 move the trailing of lineEnd to lineStart if needed\n if (this.styles[lineEnd]) {\n for (i = charEnd; i < this._unwrappedTextLines[lineEnd].length; i++) {\n styleObj = this.styles[lineEnd][i];\n if (styleObj) {\n this.styles[lineStart] || (this.styles[lineStart] = { });\n this.styles[lineStart][charStart + i - charEnd] = styleObj;\n }\n }\n }\n // step3 detects lines will be completely removed.\n for (i = lineStart + 1; i <= lineEnd; i++) {\n delete this.styles[i];\n }\n // step4 shift remaining lines.\n this.shiftLineStyles(lineEnd, lineStart - lineEnd);\n }\n else {\n // remove and shift left on the same line\n if (this.styles[lineStart]) {\n styleObj = this.styles[lineStart];\n var diff = charEnd - charStart, numericChar, _char;\n for (i = charStart; i < charEnd; i++) {\n delete styleObj[i];\n }\n for (_char in this.styles[lineStart]) {\n numericChar = parseInt(_char, 10);\n if (numericChar >= charEnd) {\n styleObj[numericChar - diff] = styleObj[_char];\n delete styleObj[_char];\n }\n }\n }\n }\n },\n\n /**\n * Shifts line styles up or down\n * @param {Number} lineIndex Index of a line\n * @param {Number} offset Can any number?\n */\n shiftLineStyles: function(lineIndex, offset) {\n // shift all line styles by offset upward or downward\n // do not clone deep. we need new array, not new style objects\n var clonedStyles = clone(this.styles);\n for (var line in this.styles) {\n var numericLine = parseInt(line, 10);\n if (numericLine > lineIndex) {\n this.styles[numericLine + offset] = clonedStyles[numericLine];\n if (!clonedStyles[numericLine - offset]) {\n delete this.styles[numericLine];\n }\n }\n }\n },\n\n restartCursorIfNeeded: function() {\n if (!this._currentTickState || this._currentTickState.isAborted\n || !this._currentTickCompleteState || this._currentTickCompleteState.isAborted\n ) {\n this.initDelayedCursor();\n }\n },\n\n /**\n * Handle insertion of more consecutive style lines for when one or more\n * newlines gets added to the text. Since current style needs to be shifted\n * first we shift the current style of the number lines needed, then we add\n * new lines from the last to the first.\n * @param {Number} lineIndex Index of a line\n * @param {Number} charIndex Index of a char\n * @param {Number} qty number of lines to add\n * @param {Array} copiedStyle Array of objects styles\n */\n insertNewlineStyleObject: function(lineIndex, charIndex, qty, copiedStyle) {\n var currentCharStyle,\n newLineStyles = {},\n somethingAdded = false,\n isEndOfLine = this._unwrappedTextLines[lineIndex].length === charIndex;\n\n qty || (qty = 1);\n this.shiftLineStyles(lineIndex, qty);\n if (this.styles[lineIndex]) {\n currentCharStyle = this.styles[lineIndex][charIndex === 0 ? charIndex : charIndex - 1];\n }\n // we clone styles of all chars\n // after cursor onto the current line\n for (var index in this.styles[lineIndex]) {\n var numIndex = parseInt(index, 10);\n if (numIndex >= charIndex) {\n somethingAdded = true;\n newLineStyles[numIndex - charIndex] = this.styles[lineIndex][index];\n // remove lines from the previous line since they're on a new line now\n if (!(isEndOfLine && charIndex === 0)) {\n delete this.styles[lineIndex][index];\n }\n }\n }\n var styleCarriedOver = false;\n if (somethingAdded && !isEndOfLine) {\n // if is end of line, the extra style we copied\n // is probably not something we want\n this.styles[lineIndex + qty] = newLineStyles;\n styleCarriedOver = true;\n }\n if (styleCarriedOver) {\n // skip the last line of since we already prepared it.\n qty--;\n }\n // for the all the lines or all the other lines\n // we clone current char style onto the next (otherwise empty) line\n while (qty > 0) {\n if (copiedStyle && copiedStyle[qty - 1]) {\n this.styles[lineIndex + qty] = { 0: clone(copiedStyle[qty - 1]) };\n }\n else if (currentCharStyle) {\n this.styles[lineIndex + qty] = { 0: clone(currentCharStyle) };\n }\n else {\n delete this.styles[lineIndex + qty];\n }\n qty--;\n }\n this._forceClearCache = true;\n },\n\n /**\n * Inserts style object for a given line/char index\n * @param {Number} lineIndex Index of a line\n * @param {Number} charIndex Index of a char\n * @param {Number} quantity number Style object to insert, if given\n * @param {Array} copiedStyle array of style objects\n */\n insertCharStyleObject: function(lineIndex, charIndex, quantity, copiedStyle) {\n if (!this.styles) {\n this.styles = {};\n }\n var currentLineStyles = this.styles[lineIndex],\n currentLineStylesCloned = currentLineStyles ? clone(currentLineStyles) : {};\n\n quantity || (quantity = 1);\n // shift all char styles by quantity forward\n // 0,1,2,3 -> (charIndex=2) -> 0,1,3,4 -> (insert 2) -> 0,1,2,3,4\n for (var index in currentLineStylesCloned) {\n var numericIndex = parseInt(index, 10);\n if (numericIndex >= charIndex) {\n currentLineStyles[numericIndex + quantity] = currentLineStylesCloned[numericIndex];\n // only delete the style if there was nothing moved there\n if (!currentLineStylesCloned[numericIndex - quantity]) {\n delete currentLineStyles[numericIndex];\n }\n }\n }\n this._forceClearCache = true;\n if (copiedStyle) {\n while (quantity--) {\n if (!Object.keys(copiedStyle[quantity]).length) {\n continue;\n }\n if (!this.styles[lineIndex]) {\n this.styles[lineIndex] = {};\n }\n this.styles[lineIndex][charIndex + quantity] = clone(copiedStyle[quantity]);\n }\n return;\n }\n if (!currentLineStyles) {\n return;\n }\n var newStyle = currentLineStyles[charIndex ? charIndex - 1 : 1];\n while (newStyle && quantity--) {\n this.styles[lineIndex][charIndex + quantity] = clone(newStyle);\n }\n },\n\n /**\n * Inserts style object(s)\n * @param {Array} insertedText Characters at the location where style is inserted\n * @param {Number} start cursor index for inserting style\n * @param {Array} [copiedStyle] array of style objects to insert.\n */\n insertNewStyleBlock: function(insertedText, start, copiedStyle) {\n var cursorLoc = this.get2DCursorLocation(start, true),\n addedLines = [0], linesLength = 0;\n // get an array of how many char per lines are being added.\n for (var i = 0; i < insertedText.length; i++) {\n if (insertedText[i] === '\\n') {\n linesLength++;\n addedLines[linesLength] = 0;\n }\n else {\n addedLines[linesLength]++;\n }\n }\n // for the first line copy the style from the current char position.\n if (addedLines[0] > 0) {\n this.insertCharStyleObject(cursorLoc.lineIndex, cursorLoc.charIndex, addedLines[0], copiedStyle);\n copiedStyle = copiedStyle && copiedStyle.slice(addedLines[0] + 1);\n }\n linesLength && this.insertNewlineStyleObject(\n cursorLoc.lineIndex, cursorLoc.charIndex + addedLines[0], linesLength);\n for (var i = 1; i < linesLength; i++) {\n if (addedLines[i] > 0) {\n this.insertCharStyleObject(cursorLoc.lineIndex + i, 0, addedLines[i], copiedStyle);\n }\n else if (copiedStyle) {\n // this test is required in order to close #6841\n // when a pasted buffer begins with a newline then\n // this.styles[cursorLoc.lineIndex + i] and copiedStyle[0]\n // may be undefined for some reason\n if (this.styles[cursorLoc.lineIndex + i] && copiedStyle[0]) {\n this.styles[cursorLoc.lineIndex + i][0] = copiedStyle[0];\n }\n }\n copiedStyle = copiedStyle && copiedStyle.slice(addedLines[i] + 1);\n }\n // we use i outside the loop to get it like linesLength\n if (addedLines[i] > 0) {\n this.insertCharStyleObject(cursorLoc.lineIndex + i, 0, addedLines[i], copiedStyle);\n }\n },\n\n /**\n * Set the selectionStart and selectionEnd according to the new position of cursor\n * mimic the key - mouse navigation when shift is pressed.\n */\n setSelectionStartEndWithShift: function(start, end, newSelection) {\n if (newSelection <= start) {\n if (end === start) {\n this._selectionDirection = 'left';\n }\n else if (this._selectionDirection === 'right') {\n this._selectionDirection = 'left';\n this.selectionEnd = start;\n }\n this.selectionStart = newSelection;\n }\n else if (newSelection > start && newSelection < end) {\n if (this._selectionDirection === 'right') {\n this.selectionEnd = newSelection;\n }\n else {\n this.selectionStart = newSelection;\n }\n }\n else {\n // newSelection is > selection start and end\n if (end === start) {\n this._selectionDirection = 'right';\n }\n else if (this._selectionDirection === 'left') {\n this._selectionDirection = 'right';\n this.selectionStart = end;\n }\n this.selectionEnd = newSelection;\n }\n },\n\n setSelectionInBoundaries: function() {\n var length = this.text.length;\n if (this.selectionStart > length) {\n this.selectionStart = length;\n }\n else if (this.selectionStart < 0) {\n this.selectionStart = 0;\n }\n if (this.selectionEnd > length) {\n this.selectionEnd = length;\n }\n else if (this.selectionEnd < 0) {\n this.selectionEnd = 0;\n }\n }\n });\n})();\n\n\nfabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {\n /**\n * Initializes \"dbclick\" event handler\n */\n initDoubleClickSimulation: function() {\n\n // for double click\n this.__lastClickTime = +new Date();\n\n // for triple click\n this.__lastLastClickTime = +new Date();\n\n this.__lastPointer = { };\n\n this.on('mousedown', this.onMouseDown);\n },\n\n /**\n * Default event handler to simulate triple click\n * @private\n */\n onMouseDown: function(options) {\n if (!this.canvas) {\n return;\n }\n this.__newClickTime = +new Date();\n var newPointer = options.pointer;\n if (this.isTripleClick(newPointer)) {\n this.fire('tripleclick', options);\n this._stopEvent(options.e);\n }\n this.__lastLastClickTime = this.__lastClickTime;\n this.__lastClickTime = this.__newClickTime;\n this.__lastPointer = newPointer;\n this.__lastIsEditing = this.isEditing;\n this.__lastSelected = this.selected;\n },\n\n isTripleClick: function(newPointer) {\n return this.__newClickTime - this.__lastClickTime < 500 &&\n this.__lastClickTime - this.__lastLastClickTime < 500 &&\n this.__lastPointer.x === newPointer.x &&\n this.__lastPointer.y === newPointer.y;\n },\n\n /**\n * @private\n */\n _stopEvent: function(e) {\n e.preventDefault && e.preventDefault();\n e.stopPropagation && e.stopPropagation();\n },\n\n /**\n * Initializes event handlers related to cursor or selection\n */\n initCursorSelectionHandlers: function() {\n this.initMousedownHandler();\n this.initMouseupHandler();\n this.initClicks();\n },\n\n /**\n * Default handler for double click, select a word\n */\n doubleClickHandler: function(options) {\n if (!this.isEditing) {\n return;\n }\n this.selectWord(this.getSelectionStartFromPointer(options.e));\n },\n\n /**\n * Default handler for triple click, select a line\n */\n tripleClickHandler: function(options) {\n if (!this.isEditing) {\n return;\n }\n this.selectLine(this.getSelectionStartFromPointer(options.e));\n },\n\n /**\n * Initializes double and triple click event handlers\n */\n initClicks: function() {\n this.on('mousedblclick', this.doubleClickHandler);\n this.on('tripleclick', this.tripleClickHandler);\n },\n\n /**\n * Default event handler for the basic functionalities needed on _mouseDown\n * can be overridden to do something different.\n * Scope of this implementation is: find the click position, set selectionStart\n * find selectionEnd, initialize the drawing of either cursor or selection area\n * initializing a mousedDown on a text area will cancel fabricjs knowledge of\n * current compositionMode. It will be set to false.\n */\n _mouseDownHandler: function(options) {\n if (!this.canvas || !this.editable || (options.e.button && options.e.button !== 1)) {\n return;\n }\n\n this.__isMousedown = true;\n\n if (this.selected) {\n this.inCompositionMode = false;\n this.setCursorByClick(options.e);\n }\n\n if (this.isEditing) {\n this.__selectionStartOnMouseDown = this.selectionStart;\n if (this.selectionStart === this.selectionEnd) {\n this.abortCursorAnimation();\n }\n this.renderCursorOrSelection();\n }\n },\n\n /**\n * Default event handler for the basic functionalities needed on mousedown:before\n * can be overridden to do something different.\n * Scope of this implementation is: verify the object is already selected when mousing down\n */\n _mouseDownHandlerBefore: function(options) {\n if (!this.canvas || !this.editable || (options.e.button && options.e.button !== 1)) {\n return;\n }\n // we want to avoid that an object that was selected and then becomes unselectable,\n // may trigger editing mode in some way.\n this.selected = this === this.canvas._activeObject;\n },\n\n /**\n * Initializes \"mousedown\" event handler\n */\n initMousedownHandler: function() {\n this.on('mousedown', this._mouseDownHandler);\n this.on('mousedown:before', this._mouseDownHandlerBefore);\n },\n\n /**\n * Initializes \"mouseup\" event handler\n */\n initMouseupHandler: function() {\n this.on('mouseup', this.mouseUpHandler);\n },\n\n /**\n * standard handler for mouse up, overridable\n * @private\n */\n mouseUpHandler: function(options) {\n this.__isMousedown = false;\n if (!this.editable || this.group ||\n (options.transform && options.transform.actionPerformed) ||\n (options.e.button && options.e.button !== 1)) {\n return;\n }\n\n if (this.canvas) {\n var currentActive = this.canvas._activeObject;\n if (currentActive && currentActive !== this) {\n // avoid running this logic when there is an active object\n // this because is possible with shift click and fast clicks,\n // to rapidly deselect and reselect this object and trigger an enterEdit\n return;\n }\n }\n\n if (this.__lastSelected && !this.__corner) {\n this.selected = false;\n this.__lastSelected = false;\n this.enterEditing(options.e);\n if (this.selectionStart === this.selectionEnd) {\n this.initDelayedCursor(true);\n }\n else {\n this.renderCursorOrSelection();\n }\n }\n else {\n this.selected = true;\n }\n },\n\n /**\n * Changes cursor location in a text depending on passed pointer (x/y) object\n * @param {Event} e Event object\n */\n setCursorByClick: function(e) {\n var newSelection = this.getSelectionStartFromPointer(e),\n start = this.selectionStart, end = this.selectionEnd;\n if (e.shiftKey) {\n this.setSelectionStartEndWithShift(start, end, newSelection);\n }\n else {\n this.selectionStart = newSelection;\n this.selectionEnd = newSelection;\n }\n if (this.isEditing) {\n this._fireSelectionChanged();\n this._updateTextarea();\n }\n },\n\n /**\n * Returns index of a character corresponding to where an object was clicked\n * @param {Event} e Event object\n * @return {Number} Index of a character\n */\n getSelectionStartFromPointer: function(e) {\n var mouseOffset = this.getLocalPointer(e),\n prevWidth = 0,\n width = 0,\n height = 0,\n charIndex = 0,\n lineIndex = 0,\n lineLeftOffset,\n line;\n for (var i = 0, len = this._textLines.length; i < len; i++) {\n if (height <= mouseOffset.y) {\n height += this.getHeightOfLine(i) * this.scaleY;\n lineIndex = i;\n if (i > 0) {\n charIndex += this._textLines[i - 1].length + this.missingNewlineOffset(i - 1);\n }\n }\n else {\n break;\n }\n }\n lineLeftOffset = this._getLineLeftOffset(lineIndex);\n width = lineLeftOffset * this.scaleX;\n line = this._textLines[lineIndex];\n // handling of RTL: in order to get things work correctly,\n // we assume RTL writing is mirrored compared to LTR writing.\n // so in position detection we mirror the X offset, and when is time\n // of rendering it, we mirror it again.\n if (this.direction === 'rtl') {\n mouseOffset.x = this.width * this.scaleX - mouseOffset.x + width;\n }\n for (var j = 0, jlen = line.length; j < jlen; j++) {\n prevWidth = width;\n // i removed something about flipX here, check.\n width += this.__charBounds[lineIndex][j].kernedWidth * this.scaleX;\n if (width <= mouseOffset.x) {\n charIndex++;\n }\n else {\n break;\n }\n }\n return this._getNewSelectionStartFromOffset(mouseOffset, prevWidth, width, charIndex, jlen);\n },\n\n /**\n * @private\n */\n _getNewSelectionStartFromOffset: function(mouseOffset, prevWidth, width, index, jlen) {\n // we need Math.abs because when width is after the last char, the offset is given as 1, while is 0\n var distanceBtwLastCharAndCursor = mouseOffset.x - prevWidth,\n distanceBtwNextCharAndCursor = width - mouseOffset.x,\n offset = distanceBtwNextCharAndCursor > distanceBtwLastCharAndCursor ||\n distanceBtwNextCharAndCursor < 0 ? 0 : 1,\n newSelectionStart = index + offset;\n // if object is horizontally flipped, mirror cursor location from the end\n if (this.flipX) {\n newSelectionStart = jlen - newSelectionStart;\n }\n\n if (newSelectionStart > this._text.length) {\n newSelectionStart = this._text.length;\n }\n\n return newSelectionStart;\n }\n});\n\n\nfabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {\n\n /**\n * Initializes hidden textarea (needed to bring up keyboard in iOS)\n */\n initHiddenTextarea: function() {\n this.hiddenTextarea = fabric.document.createElement('textarea');\n this.hiddenTextarea.setAttribute('autocapitalize', 'off');\n this.hiddenTextarea.setAttribute('autocorrect', 'off');\n this.hiddenTextarea.setAttribute('autocomplete', 'off');\n this.hiddenTextarea.setAttribute('spellcheck', 'false');\n this.hiddenTextarea.setAttribute('data-fabric-hiddentextarea', '');\n this.hiddenTextarea.setAttribute('wrap', 'off');\n var style = this._calcTextareaPosition();\n // line-height: 1px; was removed from the style to fix this:\n // https://bugs.chromium.org/p/chromium/issues/detail?id=870966\n this.hiddenTextarea.style.cssText = 'position: absolute; top: ' + style.top +\n '; left: ' + style.left + '; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px;' +\n ' padding-top: ' + style.fontSize + ';';\n\n if (this.hiddenTextareaContainer) {\n this.hiddenTextareaContainer.appendChild(this.hiddenTextarea);\n }\n else {\n fabric.document.body.appendChild(this.hiddenTextarea);\n }\n\n fabric.util.addListener(this.hiddenTextarea, 'keydown', this.onKeyDown.bind(this));\n fabric.util.addListener(this.hiddenTextarea, 'keyup', this.onKeyUp.bind(this));\n fabric.util.addListener(this.hiddenTextarea, 'input', this.onInput.bind(this));\n fabric.util.addListener(this.hiddenTextarea, 'copy', this.copy.bind(this));\n fabric.util.addListener(this.hiddenTextarea, 'cut', this.copy.bind(this));\n fabric.util.addListener(this.hiddenTextarea, 'paste', this.paste.bind(this));\n fabric.util.addListener(this.hiddenTextarea, 'compositionstart', this.onCompositionStart.bind(this));\n fabric.util.addListener(this.hiddenTextarea, 'compositionupdate', this.onCompositionUpdate.bind(this));\n fabric.util.addListener(this.hiddenTextarea, 'compositionend', this.onCompositionEnd.bind(this));\n\n if (!this._clickHandlerInitialized && this.canvas) {\n fabric.util.addListener(this.canvas.upperCanvasEl, 'click', this.onClick.bind(this));\n this._clickHandlerInitialized = true;\n }\n },\n\n /**\n * For functionalities on keyDown\n * Map a special key to a function of the instance/prototype\n * If you need different behaviour for ESC or TAB or arrows, you have to change\n * this map setting the name of a function that you build on the fabric.Itext or\n * your prototype.\n * the map change will affect all Instances unless you need for only some text Instances\n * in that case you have to clone this object and assign your Instance.\n * this.keysMap = fabric.util.object.clone(this.keysMap);\n * The function must be in fabric.Itext.prototype.myFunction And will receive event as args[0]\n */\n keysMap: {\n 9: 'exitEditing',\n 27: 'exitEditing',\n 33: 'moveCursorUp',\n 34: 'moveCursorDown',\n 35: 'moveCursorRight',\n 36: 'moveCursorLeft',\n 37: 'moveCursorLeft',\n 38: 'moveCursorUp',\n 39: 'moveCursorRight',\n 40: 'moveCursorDown',\n },\n\n keysMapRtl: {\n 9: 'exitEditing',\n 27: 'exitEditing',\n 33: 'moveCursorUp',\n 34: 'moveCursorDown',\n 35: 'moveCursorLeft',\n 36: 'moveCursorRight',\n 37: 'moveCursorRight',\n 38: 'moveCursorUp',\n 39: 'moveCursorLeft',\n 40: 'moveCursorDown',\n },\n\n /**\n * For functionalities on keyUp + ctrl || cmd\n */\n ctrlKeysMapUp: {\n 67: 'copy',\n 88: 'cut'\n },\n\n /**\n * For functionalities on keyDown + ctrl || cmd\n */\n ctrlKeysMapDown: {\n 65: 'selectAll'\n },\n\n onClick: function() {\n // No need to trigger click event here, focus is enough to have the keyboard appear on Android\n this.hiddenTextarea && this.hiddenTextarea.focus();\n },\n\n /**\n * Handles keydown event\n * only used for arrows and combination of modifier keys.\n * @param {Event} e Event object\n */\n onKeyDown: function(e) {\n if (!this.isEditing) {\n return;\n }\n var keyMap = this.direction === 'rtl' ? this.keysMapRtl : this.keysMap;\n if (e.keyCode in keyMap) {\n this[keyMap[e.keyCode]](e);\n }\n else if ((e.keyCode in this.ctrlKeysMapDown) && (e.ctrlKey || e.metaKey)) {\n this[this.ctrlKeysMapDown[e.keyCode]](e);\n }\n else {\n return;\n }\n e.stopImmediatePropagation();\n e.preventDefault();\n if (e.keyCode >= 33 && e.keyCode <= 40) {\n // if i press an arrow key just update selection\n this.inCompositionMode = false;\n this.clearContextTop();\n this.renderCursorOrSelection();\n }\n else {\n this.canvas && this.canvas.requestRenderAll();\n }\n },\n\n /**\n * Handles keyup event\n * We handle KeyUp because ie11 and edge have difficulties copy/pasting\n * if a copy/cut event fired, keyup is dismissed\n * @param {Event} e Event object\n */\n onKeyUp: function(e) {\n if (!this.isEditing || this._copyDone || this.inCompositionMode) {\n this._copyDone = false;\n return;\n }\n if ((e.keyCode in this.ctrlKeysMapUp) && (e.ctrlKey || e.metaKey)) {\n this[this.ctrlKeysMapUp[e.keyCode]](e);\n }\n else {\n return;\n }\n e.stopImmediatePropagation();\n e.preventDefault();\n this.canvas && this.canvas.requestRenderAll();\n },\n\n /**\n * Handles onInput event\n * @param {Event} e Event object\n */\n onInput: function(e) {\n var fromPaste = this.fromPaste;\n this.fromPaste = false;\n e && e.stopPropagation();\n if (!this.isEditing) {\n return;\n }\n // decisions about style changes.\n var nextText = this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,\n charCount = this._text.length,\n nextCharCount = nextText.length,\n removedText, insertedText,\n charDiff = nextCharCount - charCount,\n selectionStart = this.selectionStart, selectionEnd = this.selectionEnd,\n selection = selectionStart !== selectionEnd,\n copiedStyle, removeFrom, removeTo;\n if (this.hiddenTextarea.value === '') {\n this.styles = { };\n this.updateFromTextArea();\n this.fire('changed');\n if (this.canvas) {\n this.canvas.fire('text:changed', { target: this });\n this.canvas.requestRenderAll();\n }\n return;\n }\n\n var textareaSelection = this.fromStringToGraphemeSelection(\n this.hiddenTextarea.selectionStart,\n this.hiddenTextarea.selectionEnd,\n this.hiddenTextarea.value\n );\n var backDelete = selectionStart > textareaSelection.selectionStart;\n\n if (selection) {\n removedText = this._text.slice(selectionStart, selectionEnd);\n charDiff += selectionEnd - selectionStart;\n }\n else if (nextCharCount < charCount) {\n if (backDelete) {\n removedText = this._text.slice(selectionEnd + charDiff, selectionEnd);\n }\n else {\n removedText = this._text.slice(selectionStart, selectionStart - charDiff);\n }\n }\n insertedText = nextText.slice(textareaSelection.selectionEnd - charDiff, textareaSelection.selectionEnd);\n if (removedText && removedText.length) {\n if (insertedText.length) {\n // let's copy some style before deleting.\n // we want to copy the style before the cursor OR the style at the cursor if selection\n // is bigger than 0.\n copiedStyle = this.getSelectionStyles(selectionStart, selectionStart + 1, false);\n // now duplicate the style one for each inserted text.\n copiedStyle = insertedText.map(function() {\n // this return an array of references, but that is fine since we are\n // copying the style later.\n return copiedStyle[0];\n });\n }\n if (selection) {\n removeFrom = selectionStart;\n removeTo = selectionEnd;\n }\n else if (backDelete) {\n // detect differences between forwardDelete and backDelete\n removeFrom = selectionEnd - removedText.length;\n removeTo = selectionEnd;\n }\n else {\n removeFrom = selectionEnd;\n removeTo = selectionEnd + removedText.length;\n }\n this.removeStyleFromTo(removeFrom, removeTo);\n }\n if (insertedText.length) {\n if (fromPaste && insertedText.join('') === fabric.copiedText && !fabric.disableStyleCopyPaste) {\n copiedStyle = fabric.copiedTextStyle;\n }\n this.insertNewStyleBlock(insertedText, selectionStart, copiedStyle);\n }\n this.updateFromTextArea();\n this.fire('changed');\n if (this.canvas) {\n this.canvas.fire('text:changed', { target: this });\n this.canvas.requestRenderAll();\n }\n },\n /**\n * Composition start\n */\n onCompositionStart: function() {\n this.inCompositionMode = true;\n },\n\n /**\n * Composition end\n */\n onCompositionEnd: function() {\n this.inCompositionMode = false;\n },\n\n // /**\n // * Composition update\n // */\n onCompositionUpdate: function(e) {\n this.compositionStart = e.target.selectionStart;\n this.compositionEnd = e.target.selectionEnd;\n this.updateTextareaPosition();\n },\n\n /**\n * Copies selected text\n * @param {Event} e Event object\n */\n copy: function() {\n if (this.selectionStart === this.selectionEnd) {\n //do not cut-copy if no selection\n return;\n }\n\n fabric.copiedText = this.getSelectedText();\n if (!fabric.disableStyleCopyPaste) {\n fabric.copiedTextStyle = this.getSelectionStyles(this.selectionStart, this.selectionEnd, true);\n }\n else {\n fabric.copiedTextStyle = null;\n }\n this._copyDone = true;\n },\n\n /**\n * Pastes text\n * @param {Event} e Event object\n */\n paste: function() {\n this.fromPaste = true;\n },\n\n /**\n * @private\n * @param {Event} e Event object\n * @return {Object} Clipboard data object\n */\n _getClipboardData: function(e) {\n return (e && e.clipboardData) || fabric.window.clipboardData;\n },\n\n /**\n * Finds the width in pixels before the cursor on the same line\n * @private\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @return {Number} widthBeforeCursor width before cursor\n */\n _getWidthBeforeCursor: function(lineIndex, charIndex) {\n var widthBeforeCursor = this._getLineLeftOffset(lineIndex), bound;\n\n if (charIndex > 0) {\n bound = this.__charBounds[lineIndex][charIndex - 1];\n widthBeforeCursor += bound.left + bound.width;\n }\n return widthBeforeCursor;\n },\n\n /**\n * Gets start offset of a selection\n * @param {Event} e Event object\n * @param {Boolean} isRight\n * @return {Number}\n */\n getDownCursorOffset: function(e, isRight) {\n var selectionProp = this._getSelectionForOffset(e, isRight),\n cursorLocation = this.get2DCursorLocation(selectionProp),\n lineIndex = cursorLocation.lineIndex;\n // if on last line, down cursor goes to end of line\n if (lineIndex === this._textLines.length - 1 || e.metaKey || e.keyCode === 34) {\n // move to the end of a text\n return this._text.length - selectionProp;\n }\n var charIndex = cursorLocation.charIndex,\n widthBeforeCursor = this._getWidthBeforeCursor(lineIndex, charIndex),\n indexOnOtherLine = this._getIndexOnLine(lineIndex + 1, widthBeforeCursor),\n textAfterCursor = this._textLines[lineIndex].slice(charIndex);\n return textAfterCursor.length + indexOnOtherLine + 1 + this.missingNewlineOffset(lineIndex);\n },\n\n /**\n * private\n * Helps finding if the offset should be counted from Start or End\n * @param {Event} e Event object\n * @param {Boolean} isRight\n * @return {Number}\n */\n _getSelectionForOffset: function(e, isRight) {\n if (e.shiftKey && this.selectionStart !== this.selectionEnd && isRight) {\n return this.selectionEnd;\n }\n else {\n return this.selectionStart;\n }\n },\n\n /**\n * @param {Event} e Event object\n * @param {Boolean} isRight\n * @return {Number}\n */\n getUpCursorOffset: function(e, isRight) {\n var selectionProp = this._getSelectionForOffset(e, isRight),\n cursorLocation = this.get2DCursorLocation(selectionProp),\n lineIndex = cursorLocation.lineIndex;\n if (lineIndex === 0 || e.metaKey || e.keyCode === 33) {\n // if on first line, up cursor goes to start of line\n return -selectionProp;\n }\n var charIndex = cursorLocation.charIndex,\n widthBeforeCursor = this._getWidthBeforeCursor(lineIndex, charIndex),\n indexOnOtherLine = this._getIndexOnLine(lineIndex - 1, widthBeforeCursor),\n textBeforeCursor = this._textLines[lineIndex].slice(0, charIndex),\n missingNewlineOffset = this.missingNewlineOffset(lineIndex - 1);\n // return a negative offset\n return -this._textLines[lineIndex - 1].length\n + indexOnOtherLine - textBeforeCursor.length + (1 - missingNewlineOffset);\n },\n\n /**\n * for a given width it founds the matching character.\n * @private\n */\n _getIndexOnLine: function(lineIndex, width) {\n\n var line = this._textLines[lineIndex],\n lineLeftOffset = this._getLineLeftOffset(lineIndex),\n widthOfCharsOnLine = lineLeftOffset,\n indexOnLine = 0, charWidth, foundMatch;\n\n for (var j = 0, jlen = line.length; j < jlen; j++) {\n charWidth = this.__charBounds[lineIndex][j].width;\n widthOfCharsOnLine += charWidth;\n if (widthOfCharsOnLine > width) {\n foundMatch = true;\n var leftEdge = widthOfCharsOnLine - charWidth,\n rightEdge = widthOfCharsOnLine,\n offsetFromLeftEdge = Math.abs(leftEdge - width),\n offsetFromRightEdge = Math.abs(rightEdge - width);\n\n indexOnLine = offsetFromRightEdge < offsetFromLeftEdge ? j : (j - 1);\n break;\n }\n }\n\n // reached end\n if (!foundMatch) {\n indexOnLine = line.length - 1;\n }\n\n return indexOnLine;\n },\n\n\n /**\n * Moves cursor down\n * @param {Event} e Event object\n */\n moveCursorDown: function(e) {\n if (this.selectionStart >= this._text.length && this.selectionEnd >= this._text.length) {\n return;\n }\n this._moveCursorUpOrDown('Down', e);\n },\n\n /**\n * Moves cursor up\n * @param {Event} e Event object\n */\n moveCursorUp: function(e) {\n if (this.selectionStart === 0 && this.selectionEnd === 0) {\n return;\n }\n this._moveCursorUpOrDown('Up', e);\n },\n\n /**\n * Moves cursor up or down, fires the events\n * @param {String} direction 'Up' or 'Down'\n * @param {Event} e Event object\n */\n _moveCursorUpOrDown: function(direction, e) {\n // getUpCursorOffset\n // getDownCursorOffset\n var action = 'get' + direction + 'CursorOffset',\n offset = this[action](e, this._selectionDirection === 'right');\n if (e.shiftKey) {\n this.moveCursorWithShift(offset);\n }\n else {\n this.moveCursorWithoutShift(offset);\n }\n if (offset !== 0) {\n this.setSelectionInBoundaries();\n this.abortCursorAnimation();\n this._currentCursorOpacity = 1;\n this.initDelayedCursor();\n this._fireSelectionChanged();\n this._updateTextarea();\n }\n },\n\n /**\n * Moves cursor with shift\n * @param {Number} offset\n */\n moveCursorWithShift: function(offset) {\n var newSelection = this._selectionDirection === 'left'\n ? this.selectionStart + offset\n : this.selectionEnd + offset;\n this.setSelectionStartEndWithShift(this.selectionStart, this.selectionEnd, newSelection);\n return offset !== 0;\n },\n\n /**\n * Moves cursor up without shift\n * @param {Number} offset\n */\n moveCursorWithoutShift: function(offset) {\n if (offset < 0) {\n this.selectionStart += offset;\n this.selectionEnd = this.selectionStart;\n }\n else {\n this.selectionEnd += offset;\n this.selectionStart = this.selectionEnd;\n }\n return offset !== 0;\n },\n\n /**\n * Moves cursor left\n * @param {Event} e Event object\n */\n moveCursorLeft: function(e) {\n if (this.selectionStart === 0 && this.selectionEnd === 0) {\n return;\n }\n this._moveCursorLeftOrRight('Left', e);\n },\n\n /**\n * @private\n * @return {Boolean} true if a change happened\n */\n _move: function(e, prop, direction) {\n var newValue;\n if (e.altKey) {\n newValue = this['findWordBoundary' + direction](this[prop]);\n }\n else if (e.metaKey || e.keyCode === 35 || e.keyCode === 36 ) {\n newValue = this['findLineBoundary' + direction](this[prop]);\n }\n else {\n this[prop] += direction === 'Left' ? -1 : 1;\n return true;\n }\n if (typeof newValue !== 'undefined' && this[prop] !== newValue) {\n this[prop] = newValue;\n return true;\n }\n },\n\n /**\n * @private\n */\n _moveLeft: function(e, prop) {\n return this._move(e, prop, 'Left');\n },\n\n /**\n * @private\n */\n _moveRight: function(e, prop) {\n return this._move(e, prop, 'Right');\n },\n\n /**\n * Moves cursor left without keeping selection\n * @param {Event} e\n */\n moveCursorLeftWithoutShift: function(e) {\n var change = true;\n this._selectionDirection = 'left';\n\n // only move cursor when there is no selection,\n // otherwise we discard it, and leave cursor on same place\n if (this.selectionEnd === this.selectionStart && this.selectionStart !== 0) {\n change = this._moveLeft(e, 'selectionStart');\n\n }\n this.selectionEnd = this.selectionStart;\n return change;\n },\n\n /**\n * Moves cursor left while keeping selection\n * @param {Event} e\n */\n moveCursorLeftWithShift: function(e) {\n if (this._selectionDirection === 'right' && this.selectionStart !== this.selectionEnd) {\n return this._moveLeft(e, 'selectionEnd');\n }\n else if (this.selectionStart !== 0){\n this._selectionDirection = 'left';\n return this._moveLeft(e, 'selectionStart');\n }\n },\n\n /**\n * Moves cursor right\n * @param {Event} e Event object\n */\n moveCursorRight: function(e) {\n if (this.selectionStart >= this._text.length && this.selectionEnd >= this._text.length) {\n return;\n }\n this._moveCursorLeftOrRight('Right', e);\n },\n\n /**\n * Moves cursor right or Left, fires event\n * @param {String} direction 'Left', 'Right'\n * @param {Event} e Event object\n */\n _moveCursorLeftOrRight: function(direction, e) {\n var actionName = 'moveCursor' + direction + 'With';\n this._currentCursorOpacity = 1;\n\n if (e.shiftKey) {\n actionName += 'Shift';\n }\n else {\n actionName += 'outShift';\n }\n if (this[actionName](e)) {\n this.abortCursorAnimation();\n this.initDelayedCursor();\n this._fireSelectionChanged();\n this._updateTextarea();\n }\n },\n\n /**\n * Moves cursor right while keeping selection\n * @param {Event} e\n */\n moveCursorRightWithShift: function(e) {\n if (this._selectionDirection === 'left' && this.selectionStart !== this.selectionEnd) {\n return this._moveRight(e, 'selectionStart');\n }\n else if (this.selectionEnd !== this._text.length) {\n this._selectionDirection = 'right';\n return this._moveRight(e, 'selectionEnd');\n }\n },\n\n /**\n * Moves cursor right without keeping selection\n * @param {Event} e Event object\n */\n moveCursorRightWithoutShift: function(e) {\n var changed = true;\n this._selectionDirection = 'right';\n\n if (this.selectionStart === this.selectionEnd) {\n changed = this._moveRight(e, 'selectionStart');\n this.selectionEnd = this.selectionStart;\n }\n else {\n this.selectionStart = this.selectionEnd;\n }\n return changed;\n },\n\n /**\n * Removes characters from start/end\n * start/end ar per grapheme position in _text array.\n *\n * @param {Number} start\n * @param {Number} end default to start + 1\n */\n removeChars: function(start, end) {\n if (typeof end === 'undefined') {\n end = start + 1;\n }\n this.removeStyleFromTo(start, end);\n this._text.splice(start, end - start);\n this.text = this._text.join('');\n this.set('dirty', true);\n if (this._shouldClearDimensionCache()) {\n this.initDimensions();\n this.setCoords();\n }\n this._removeExtraneousStyles();\n },\n\n /**\n * insert characters at start position, before start position.\n * start equal 1 it means the text get inserted between actual grapheme 0 and 1\n * if style array is provided, it must be as the same length of text in graphemes\n * if end is provided and is bigger than start, old text is replaced.\n * start/end ar per grapheme position in _text array.\n *\n * @param {String} text text to insert\n * @param {Array} style array of style objects\n * @param {Number} start\n * @param {Number} end default to start + 1\n */\n insertChars: function(text, style, start, end) {\n if (typeof end === 'undefined') {\n end = start;\n }\n if (end > start) {\n this.removeStyleFromTo(start, end);\n }\n var graphemes = fabric.util.string.graphemeSplit(text);\n this.insertNewStyleBlock(graphemes, start, style);\n this._text = [].concat(this._text.slice(0, start), graphemes, this._text.slice(end));\n this.text = this._text.join('');\n this.set('dirty', true);\n if (this._shouldClearDimensionCache()) {\n this.initDimensions();\n this.setCoords();\n }\n this._removeExtraneousStyles();\n },\n\n});\n\n\n/* _TO_SVG_START_ */\n(function() {\n var toFixed = fabric.util.toFixed,\n multipleSpacesRegex = / +/g;\n\n fabric.util.object.extend(fabric.Text.prototype, /** @lends fabric.Text.prototype */ {\n\n /**\n * Returns SVG representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {String} svg representation of an instance\n */\n _toSVG: function() {\n var offsets = this._getSVGLeftTopOffsets(),\n textAndBg = this._getSVGTextAndBg(offsets.textTop, offsets.textLeft);\n return this._wrapSVGTextAndBg(textAndBg);\n },\n\n /**\n * Returns svg representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {String} svg representation of an instance\n */\n toSVG: function(reviver) {\n return this._createBaseSVGMarkup(\n this._toSVG(),\n { reviver: reviver, noStyle: true, withShadow: true }\n );\n },\n\n /**\n * @private\n */\n _getSVGLeftTopOffsets: function() {\n return {\n textLeft: -this.width / 2,\n textTop: -this.height / 2,\n lineTop: this.getHeightOfLine(0)\n };\n },\n\n /**\n * @private\n */\n _wrapSVGTextAndBg: function(textAndBg) {\n var noShadow = true,\n textDecoration = this.getSvgTextDecoration(this);\n return [\n textAndBg.textBgRects.join(''),\n '\\t\\t',\n textAndBg.textSpans.join(''),\n '\\n'\n ];\n },\n\n /**\n * @private\n * @param {Number} textTopOffset Text top offset\n * @param {Number} textLeftOffset Text left offset\n * @return {Object}\n */\n _getSVGTextAndBg: function(textTopOffset, textLeftOffset) {\n var textSpans = [],\n textBgRects = [],\n height = textTopOffset, lineOffset;\n // bounding-box background\n this._setSVGBg(textBgRects);\n\n // text and text-background\n for (var i = 0, len = this._textLines.length; i < len; i++) {\n lineOffset = this._getLineLeftOffset(i);\n if (this.textBackgroundColor || this.styleHas('textBackgroundColor', i)) {\n this._setSVGTextLineBg(textBgRects, i, textLeftOffset + lineOffset, height);\n }\n this._setSVGTextLineText(textSpans, i, textLeftOffset + lineOffset, height);\n height += this.getHeightOfLine(i);\n }\n\n return {\n textSpans: textSpans,\n textBgRects: textBgRects\n };\n },\n\n /**\n * @private\n */\n _createTextCharSpan: function(_char, styleDecl, left, top) {\n var shouldUseWhitespace = _char !== _char.trim() || _char.match(multipleSpacesRegex),\n styleProps = this.getSvgSpanStyles(styleDecl, shouldUseWhitespace),\n fillStyles = styleProps ? 'style=\"' + styleProps + '\"' : '',\n dy = styleDecl.deltaY, dySpan = '',\n NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;\n if (dy) {\n dySpan = ' dy=\"' + toFixed(dy, NUM_FRACTION_DIGITS) + '\" ';\n }\n return [\n '',\n fabric.util.string.escapeXml(_char),\n ''\n ].join('');\n },\n\n _setSVGTextLineText: function(textSpans, lineIndex, textLeftOffset, textTopOffset) {\n // set proper line offset\n var lineHeight = this.getHeightOfLine(lineIndex),\n isJustify = this.textAlign.indexOf('justify') !== -1,\n actualStyle,\n nextStyle,\n charsToRender = '',\n charBox, style,\n boxWidth = 0,\n line = this._textLines[lineIndex],\n timeToRender;\n\n textTopOffset += lineHeight * (1 - this._fontSizeFraction) / this.lineHeight;\n for (var i = 0, len = line.length - 1; i <= len; i++) {\n timeToRender = i === len || this.charSpacing;\n charsToRender += line[i];\n charBox = this.__charBounds[lineIndex][i];\n if (boxWidth === 0) {\n textLeftOffset += charBox.kernedWidth - charBox.width;\n boxWidth += charBox.width;\n }\n else {\n boxWidth += charBox.kernedWidth;\n }\n if (isJustify && !timeToRender) {\n if (this._reSpaceAndTab.test(line[i])) {\n timeToRender = true;\n }\n }\n if (!timeToRender) {\n // if we have charSpacing, we render char by char\n actualStyle = actualStyle || this.getCompleteStyleDeclaration(lineIndex, i);\n nextStyle = this.getCompleteStyleDeclaration(lineIndex, i + 1);\n timeToRender = fabric.util.hasStyleChanged(actualStyle, nextStyle, true);\n }\n if (timeToRender) {\n style = this._getStyleDeclaration(lineIndex, i) || { };\n textSpans.push(this._createTextCharSpan(charsToRender, style, textLeftOffset, textTopOffset));\n charsToRender = '';\n actualStyle = nextStyle;\n textLeftOffset += boxWidth;\n boxWidth = 0;\n }\n }\n },\n\n _pushTextBgRect: function(textBgRects, color, left, top, width, height) {\n var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;\n textBgRects.push(\n '\\t\\t\\n');\n },\n\n _setSVGTextLineBg: function(textBgRects, i, leftOffset, textTopOffset) {\n var line = this._textLines[i],\n heightOfLine = this.getHeightOfLine(i) / this.lineHeight,\n boxWidth = 0,\n boxStart = 0,\n charBox, currentColor,\n lastColor = this.getValueOfPropertyAt(i, 0, 'textBackgroundColor');\n for (var j = 0, jlen = line.length; j < jlen; j++) {\n charBox = this.__charBounds[i][j];\n currentColor = this.getValueOfPropertyAt(i, j, 'textBackgroundColor');\n if (currentColor !== lastColor) {\n lastColor && this._pushTextBgRect(textBgRects, lastColor, leftOffset + boxStart,\n textTopOffset, boxWidth, heightOfLine);\n boxStart = charBox.left;\n boxWidth = charBox.width;\n lastColor = currentColor;\n }\n else {\n boxWidth += charBox.kernedWidth;\n }\n }\n currentColor && this._pushTextBgRect(textBgRects, currentColor, leftOffset + boxStart,\n textTopOffset, boxWidth, heightOfLine);\n },\n\n /**\n * Adobe Illustrator (at least CS5) is unable to render rgba()-based fill values\n * we work around it by \"moving\" alpha channel into opacity attribute and setting fill's alpha to 1\n *\n * @private\n * @param {*} value\n * @return {String}\n */\n _getFillAttributes: function(value) {\n var fillColor = (value && typeof value === 'string') ? new fabric.Color(value) : '';\n if (!fillColor || !fillColor.getSource() || fillColor.getAlpha() === 1) {\n return 'fill=\"' + value + '\"';\n }\n return 'opacity=\"' + fillColor.getAlpha() + '\" fill=\"' + fillColor.setAlpha(1).toRgb() + '\"';\n },\n\n /**\n * @private\n */\n _getSVGLineTopOffset: function(lineIndex) {\n var lineTopOffset = 0, lastHeight = 0;\n for (var j = 0; j < lineIndex; j++) {\n lineTopOffset += this.getHeightOfLine(j);\n }\n lastHeight = this.getHeightOfLine(j);\n return {\n lineTop: lineTopOffset,\n offset: (this._fontSizeMult - this._fontSizeFraction) * lastHeight / (this.lineHeight * this._fontSizeMult)\n };\n },\n\n /**\n * Returns styles-string for svg-export\n * @param {Boolean} skipShadow a boolean to skip shadow filter output\n * @return {String}\n */\n getSvgStyles: function(skipShadow) {\n var svgStyle = fabric.Object.prototype.getSvgStyles.call(this, skipShadow);\n return svgStyle + ' white-space: pre;';\n },\n });\n})();\n/* _TO_SVG_END_ */\n\n\n(function(global) {\n\n 'use strict';\n\n var fabric = global.fabric || (global.fabric = {});\n\n /**\n * Textbox class, based on IText, allows the user to resize the text rectangle\n * and wraps lines automatically. Textboxes have their Y scaling locked, the\n * user can only change width. Height is adjusted automatically based on the\n * wrapping of lines.\n * @class fabric.Textbox\n * @extends fabric.IText\n * @mixes fabric.Observable\n * @return {fabric.Textbox} thisArg\n * @see {@link fabric.Textbox#initialize} for constructor definition\n */\n fabric.Textbox = fabric.util.createClass(fabric.IText, fabric.Observable, {\n\n /**\n * Type of an object\n * @type String\n * @default\n */\n type: 'textbox',\n\n /**\n * Minimum width of textbox, in pixels.\n * @type Number\n * @default\n */\n minWidth: 20,\n\n /**\n * Minimum calculated width of a textbox, in pixels.\n * fixed to 2 so that an empty textbox cannot go to 0\n * and is still selectable without text.\n * @type Number\n * @default\n */\n dynamicMinWidth: 2,\n\n /**\n * Cached array of text wrapping.\n * @type Array\n */\n __cachedLines: null,\n\n /**\n * Override standard Object class values\n */\n lockScalingFlip: true,\n\n /**\n * Override standard Object class values\n * Textbox needs this on false\n */\n noScaleCache: false,\n\n /**\n * Properties which when set cause object to change dimensions\n * @type Object\n * @private\n */\n _dimensionAffectingProps: fabric.Text.prototype._dimensionAffectingProps.concat('width'),\n\n /**\n * Use this regular expression to split strings in breakable lines\n * @private\n */\n _wordJoiners: /[ \\t\\r]/,\n\n /**\n * Use this boolean property in order to split strings that have no white space concept.\n * this is a cheap way to help with chinese/japanese\n * @type Boolean\n * @since 2.6.0\n */\n splitByGrapheme: false,\n\n /**\n * Unlike superclass's version of this function, Textbox does not update\n * its width.\n * @private\n * @override\n */\n initDimensions: function() {\n if (this.__skipDimension) {\n return;\n }\n this.isEditing && this.initDelayedCursor();\n this.clearContextTop();\n this._clearCache();\n // clear dynamicMinWidth as it will be different after we re-wrap line\n this.dynamicMinWidth = 0;\n // wrap lines\n this._styleMap = this._generateStyleMap(this._splitText());\n // if after wrapping, the width is smaller than dynamicMinWidth, change the width and re-wrap\n if (this.dynamicMinWidth > this.width) {\n this._set('width', this.dynamicMinWidth);\n }\n if (this.textAlign.indexOf('justify') !== -1) {\n // once text is measured we need to make space fatter to make justified text.\n this.enlargeSpaces();\n }\n // clear cache and re-calculate height\n this.height = this.calcTextHeight();\n this.saveState({ propertySet: '_dimensionAffectingProps' });\n },\n\n /**\n * Generate an object that translates the style object so that it is\n * broken up by visual lines (new lines and automatic wrapping).\n * The original text styles object is broken up by actual lines (new lines only),\n * which is only sufficient for Text / IText\n * @private\n */\n _generateStyleMap: function(textInfo) {\n var realLineCount = 0,\n realLineCharCount = 0,\n charCount = 0,\n map = {};\n\n for (var i = 0; i < textInfo.graphemeLines.length; i++) {\n if (textInfo.graphemeText[charCount] === '\\n' && i > 0) {\n realLineCharCount = 0;\n charCount++;\n realLineCount++;\n }\n else if (!this.splitByGrapheme && this._reSpaceAndTab.test(textInfo.graphemeText[charCount]) && i > 0) {\n // this case deals with space's that are removed from end of lines when wrapping\n realLineCharCount++;\n charCount++;\n }\n\n map[i] = { line: realLineCount, offset: realLineCharCount };\n\n charCount += textInfo.graphemeLines[i].length;\n realLineCharCount += textInfo.graphemeLines[i].length;\n }\n\n return map;\n },\n\n /**\n * Returns true if object has a style property or has it on a specified line\n * @param {Number} lineIndex\n * @return {Boolean}\n */\n styleHas: function(property, lineIndex) {\n if (this._styleMap && !this.isWrapping) {\n var map = this._styleMap[lineIndex];\n if (map) {\n lineIndex = map.line;\n }\n }\n return fabric.Text.prototype.styleHas.call(this, property, lineIndex);\n },\n\n /**\n * Returns true if object has no styling or no styling in a line\n * @param {Number} lineIndex , lineIndex is on wrapped lines.\n * @return {Boolean}\n */\n isEmptyStyles: function(lineIndex) {\n if (!this.styles) {\n return true;\n }\n var offset = 0, nextLineIndex = lineIndex + 1, nextOffset, obj, shouldLimit = false,\n map = this._styleMap[lineIndex], mapNextLine = this._styleMap[lineIndex + 1];\n if (map) {\n lineIndex = map.line;\n offset = map.offset;\n }\n if (mapNextLine) {\n nextLineIndex = mapNextLine.line;\n shouldLimit = nextLineIndex === lineIndex;\n nextOffset = mapNextLine.offset;\n }\n obj = typeof lineIndex === 'undefined' ? this.styles : { line: this.styles[lineIndex] };\n for (var p1 in obj) {\n for (var p2 in obj[p1]) {\n if (p2 >= offset && (!shouldLimit || p2 < nextOffset)) {\n // eslint-disable-next-line no-unused-vars\n for (var p3 in obj[p1][p2]) {\n return false;\n }\n }\n }\n }\n return true;\n },\n\n /**\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @private\n */\n _getStyleDeclaration: function(lineIndex, charIndex) {\n if (this._styleMap && !this.isWrapping) {\n var map = this._styleMap[lineIndex];\n if (!map) {\n return null;\n }\n lineIndex = map.line;\n charIndex = map.offset + charIndex;\n }\n return this.callSuper('_getStyleDeclaration', lineIndex, charIndex);\n },\n\n /**\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @param {Object} style\n * @private\n */\n _setStyleDeclaration: function(lineIndex, charIndex, style) {\n var map = this._styleMap[lineIndex];\n lineIndex = map.line;\n charIndex = map.offset + charIndex;\n\n this.styles[lineIndex][charIndex] = style;\n },\n\n /**\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @private\n */\n _deleteStyleDeclaration: function(lineIndex, charIndex) {\n var map = this._styleMap[lineIndex];\n lineIndex = map.line;\n charIndex = map.offset + charIndex;\n delete this.styles[lineIndex][charIndex];\n },\n\n /**\n * probably broken need a fix\n * Returns the real style line that correspond to the wrapped lineIndex line\n * Used just to verify if the line does exist or not.\n * @param {Number} lineIndex\n * @returns {Boolean} if the line exists or not\n * @private\n */\n _getLineStyle: function(lineIndex) {\n var map = this._styleMap[lineIndex];\n return !!this.styles[map.line];\n },\n\n /**\n * Set the line style to an empty object so that is initialized\n * @param {Number} lineIndex\n * @param {Object} style\n * @private\n */\n _setLineStyle: function(lineIndex) {\n var map = this._styleMap[lineIndex];\n this.styles[map.line] = {};\n },\n\n /**\n * Wraps text using the 'width' property of Textbox. First this function\n * splits text on newlines, so we preserve newlines entered by the user.\n * Then it wraps each line using the width of the Textbox by calling\n * _wrapLine().\n * @param {Array} lines The string array of text that is split into lines\n * @param {Number} desiredWidth width you want to wrap to\n * @returns {Array} Array of lines\n */\n _wrapText: function(lines, desiredWidth) {\n var wrapped = [], i;\n this.isWrapping = true;\n for (i = 0; i < lines.length; i++) {\n wrapped = wrapped.concat(this._wrapLine(lines[i], i, desiredWidth));\n }\n this.isWrapping = false;\n return wrapped;\n },\n\n /**\n * Helper function to measure a string of text, given its lineIndex and charIndex offset\n * it gets called when charBounds are not available yet.\n * @param {CanvasRenderingContext2D} ctx\n * @param {String} text\n * @param {number} lineIndex\n * @param {number} charOffset\n * @returns {number}\n * @private\n */\n _measureWord: function(word, lineIndex, charOffset) {\n var width = 0, prevGrapheme, skipLeft = true;\n charOffset = charOffset || 0;\n for (var i = 0, len = word.length; i < len; i++) {\n var box = this._getGraphemeBox(word[i], lineIndex, i + charOffset, prevGrapheme, skipLeft);\n width += box.kernedWidth;\n prevGrapheme = word[i];\n }\n return width;\n },\n\n /**\n * Wraps a line of text using the width of the Textbox and a context.\n * @param {Array} line The grapheme array that represent the line\n * @param {Number} lineIndex\n * @param {Number} desiredWidth width you want to wrap the line to\n * @param {Number} reservedSpace space to remove from wrapping for custom functionalities\n * @returns {Array} Array of line(s) into which the given text is wrapped\n * to.\n */\n _wrapLine: function(_line, lineIndex, desiredWidth, reservedSpace) {\n var lineWidth = 0,\n splitByGrapheme = this.splitByGrapheme,\n graphemeLines = [],\n line = [],\n // spaces in different languages?\n words = splitByGrapheme ? fabric.util.string.graphemeSplit(_line) : _line.split(this._wordJoiners),\n word = '',\n offset = 0,\n infix = splitByGrapheme ? '' : ' ',\n wordWidth = 0,\n infixWidth = 0,\n largestWordWidth = 0,\n lineJustStarted = true,\n additionalSpace = this._getWidthOfCharSpacing(),\n reservedSpace = reservedSpace || 0;\n // fix a difference between split and graphemeSplit\n if (words.length === 0) {\n words.push([]);\n }\n desiredWidth -= reservedSpace;\n for (var i = 0; i < words.length; i++) {\n // if using splitByGrapheme words are already in graphemes.\n word = splitByGrapheme ? words[i] : fabric.util.string.graphemeSplit(words[i]);\n wordWidth = this._measureWord(word, lineIndex, offset);\n offset += word.length;\n\n lineWidth += infixWidth + wordWidth - additionalSpace;\n if (lineWidth > desiredWidth && !lineJustStarted) {\n graphemeLines.push(line);\n line = [];\n lineWidth = wordWidth;\n lineJustStarted = true;\n }\n else {\n lineWidth += additionalSpace;\n }\n\n if (!lineJustStarted && !splitByGrapheme) {\n line.push(infix);\n }\n line = line.concat(word);\n\n infixWidth = splitByGrapheme ? 0 : this._measureWord([infix], lineIndex, offset);\n offset++;\n lineJustStarted = false;\n // keep track of largest word\n if (wordWidth > largestWordWidth) {\n largestWordWidth = wordWidth;\n }\n }\n\n i && graphemeLines.push(line);\n\n if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {\n this.dynamicMinWidth = largestWordWidth - additionalSpace + reservedSpace;\n }\n return graphemeLines;\n },\n\n /**\n * Detect if the text line is ended with an hard break\n * text and itext do not have wrapping, return false\n * @param {Number} lineIndex text to split\n * @return {Boolean}\n */\n isEndOfWrapping: function(lineIndex) {\n if (!this._styleMap[lineIndex + 1]) {\n // is last line, return true;\n return true;\n }\n if (this._styleMap[lineIndex + 1].line !== this._styleMap[lineIndex].line) {\n // this is last line before a line break, return true;\n return true;\n }\n return false;\n },\n\n /**\n * Detect if a line has a linebreak and so we need to account for it when moving\n * and counting style.\n * @return Number\n */\n missingNewlineOffset: function(lineIndex) {\n if (this.splitByGrapheme) {\n return this.isEndOfWrapping(lineIndex) ? 1 : 0;\n }\n return 1;\n },\n\n /**\n * Gets lines of text to render in the Textbox. This function calculates\n * text wrapping on the fly every time it is called.\n * @param {String} text text to split\n * @returns {Array} Array of lines in the Textbox.\n * @override\n */\n _splitTextIntoLines: function(text) {\n var newText = fabric.Text.prototype._splitTextIntoLines.call(this, text),\n graphemeLines = this._wrapText(newText.lines, this.width),\n lines = new Array(graphemeLines.length);\n for (var i = 0; i < graphemeLines.length; i++) {\n lines[i] = graphemeLines[i].join('');\n }\n newText.lines = lines;\n newText.graphemeLines = graphemeLines;\n return newText;\n },\n\n getMinWidth: function() {\n return Math.max(this.minWidth, this.dynamicMinWidth);\n },\n\n _removeExtraneousStyles: function() {\n var linesToKeep = {};\n for (var prop in this._styleMap) {\n if (this._textLines[prop]) {\n linesToKeep[this._styleMap[prop].line] = 1;\n }\n }\n for (var prop in this.styles) {\n if (!linesToKeep[prop]) {\n delete this.styles[prop];\n }\n }\n },\n\n /**\n * Returns object representation of an instance\n * @method toObject\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject: function(propertiesToInclude) {\n return this.callSuper('toObject', ['minWidth', 'splitByGrapheme'].concat(propertiesToInclude));\n }\n });\n\n /**\n * Returns fabric.Textbox instance from an object representation\n * @static\n * @memberOf fabric.Textbox\n * @param {Object} object Object to create an instance from\n * @param {Function} [callback] Callback to invoke when an fabric.Textbox instance is created\n */\n fabric.Textbox.fromObject = function(object, callback) {\n var styles = fabric.util.stylesFromArray(object.styles, object.text);\n //copy object to prevent mutation\n var objCopy = Object.assign({}, object, { styles: styles });\n return fabric.Object._fromObject('Textbox', objCopy, callback, 'text');\n };\n})(typeof exports !== 'undefined' ? exports : this);\n\n\n(function() {\n\n var controlsUtils = fabric.controlsUtils,\n scaleSkewStyleHandler = controlsUtils.scaleSkewCursorStyleHandler,\n scaleStyleHandler = controlsUtils.scaleCursorStyleHandler,\n scalingEqually = controlsUtils.scalingEqually,\n scalingYOrSkewingX = controlsUtils.scalingYOrSkewingX,\n scalingXOrSkewingY = controlsUtils.scalingXOrSkewingY,\n scaleOrSkewActionName = controlsUtils.scaleOrSkewActionName,\n objectControls = fabric.Object.prototype.controls;\n\n objectControls.ml = new fabric.Control({\n x: -0.5,\n y: 0,\n cursorStyleHandler: scaleSkewStyleHandler,\n actionHandler: scalingXOrSkewingY,\n getActionName: scaleOrSkewActionName,\n });\n\n objectControls.mr = new fabric.Control({\n x: 0.5,\n y: 0,\n cursorStyleHandler: scaleSkewStyleHandler,\n actionHandler: scalingXOrSkewingY,\n getActionName: scaleOrSkewActionName,\n });\n\n objectControls.mb = new fabric.Control({\n x: 0,\n y: 0.5,\n cursorStyleHandler: scaleSkewStyleHandler,\n actionHandler: scalingYOrSkewingX,\n getActionName: scaleOrSkewActionName,\n });\n\n objectControls.mt = new fabric.Control({\n x: 0,\n y: -0.5,\n cursorStyleHandler: scaleSkewStyleHandler,\n actionHandler: scalingYOrSkewingX,\n getActionName: scaleOrSkewActionName,\n });\n\n objectControls.tl = new fabric.Control({\n x: -0.5,\n y: -0.5,\n cursorStyleHandler: scaleStyleHandler,\n actionHandler: scalingEqually\n });\n\n objectControls.tr = new fabric.Control({\n x: 0.5,\n y: -0.5,\n cursorStyleHandler: scaleStyleHandler,\n actionHandler: scalingEqually\n });\n\n objectControls.bl = new fabric.Control({\n x: -0.5,\n y: 0.5,\n cursorStyleHandler: scaleStyleHandler,\n actionHandler: scalingEqually\n });\n\n objectControls.br = new fabric.Control({\n x: 0.5,\n y: 0.5,\n cursorStyleHandler: scaleStyleHandler,\n actionHandler: scalingEqually\n });\n\n objectControls.mtr = new fabric.Control({\n x: 0,\n y: -0.5,\n actionHandler: controlsUtils.rotationWithSnapping,\n cursorStyleHandler: controlsUtils.rotationStyleHandler,\n offsetY: -40,\n withConnection: true,\n actionName: 'rotate',\n });\n\n if (fabric.Textbox) {\n // this is breaking the prototype inheritance, no time / ideas to fix it.\n // is important to document that if you want to have all objects to have a\n // specific custom control, you have to add it to Object prototype and to Textbox\n // prototype. The controls are shared as references. So changes to control `tr`\n // can still apply to all objects if needed.\n var textBoxControls = fabric.Textbox.prototype.controls = { };\n\n textBoxControls.mtr = objectControls.mtr;\n textBoxControls.tr = objectControls.tr;\n textBoxControls.br = objectControls.br;\n textBoxControls.tl = objectControls.tl;\n textBoxControls.bl = objectControls.bl;\n textBoxControls.mt = objectControls.mt;\n textBoxControls.mb = objectControls.mb;\n\n textBoxControls.mr = new fabric.Control({\n x: 0.5,\n y: 0,\n actionHandler: controlsUtils.changeWidth,\n cursorStyleHandler: scaleSkewStyleHandler,\n actionName: 'resizing',\n });\n\n textBoxControls.ml = new fabric.Control({\n x: -0.5,\n y: 0,\n actionHandler: controlsUtils.changeWidth,\n cursorStyleHandler: scaleSkewStyleHandler,\n actionName: 'resizing',\n });\n }\n})();\n\n","import { fabric } from 'fabric'\n\nfabric.Canvas.prototype.selectionColor = 'rgba(0, 191, 255, .3)'\nfabric.Canvas.prototype.selectionBorderColor = 'rgba(0, 191, 255, .5)'\nfabric.Canvas.prototype.selectionLineWidth = 2\nfabric.Object.prototype.borderColor = '#FFFFFF'\nfabric.Object.prototype.transparentCorners = false\nfabric.Object.prototype.cornerColor = '#FFFFFF'\nfabric.Object.prototype.cornerStyle = 'circle'\nfabric.Object.prototype.cornerSize = 10\n","import { fabric } from 'fabric';\n\n\nfabric.Sprite = fabric.util.createClass(fabric.Image, {\n\n type: 'sprite',\n spriteIndex: 0,\n frameTime: 100,\n\n initialize: function (element: any, options: any) {\n // console.log(element, options)\n options || (options = {});\n\n const { height, width } = options;\n\n this.spriteWidth = width;\n this.spriteHeight = height;\n this.column = 0;\n this.row = 0;\n\n this.callSuper('initialize', element, options);\n },\n _render: function (ctx: any) {\n ctx.drawImage(this._element, this.column * this.spriteWidth, this.row * this.spriteHeight, this.spriteWidth, this.spriteHeight, -this.spriteWidth / 2, -this.spriteHeight / 2, this.spriteWidth, this.spriteHeight)\n },\n play: function () {\n var _this = this;\n let direction = \"forward\";\n\n let row = Math.round(_this._element.height / _this.spriteHeight - 1)\n let column = Math.round(_this._element.width / _this.spriteWidth - 1);\n _this.onPlay && _this.onPlay(),\n _this.dirty = !0,\n this.animInterval = setInterval(function () {\n direction === \"forward\" && (_this.column === column ? _this.row === row ? direction = \"reverse\" : (_this.row += 1,\n _this.column = 0) : _this.column += 1),\n direction === \"reverse\" && (_this.column === 0 ? _this.row === 0 ? direction = \"forward\" : (_this.row -= 1,\n _this.column = column) : _this.column -= 1)\n }, this.frameTime)\n },\n stop: function () {\n clearInterval(this.animInterval);\n }\n});\n\nfabric.Sprite.fromURL = function (url: any, callback: any, imgOptions: any) {\n fabric.util.loadImage(url, function (img) {\n callback(new fabric.Sprite(img, imgOptions));\n });\n};\n\nfabric.Sprite.fromURLAsync = async (url, imgOptions) => {\n return new Promise((resolve, reject) => {\n fabric.util.loadImage(url, function (img) {\n resolve(new fabric.Sprite(img, imgOptions))\n });\n })\n}\n\nfabric.Sprite.async = true;","import { fabric } from 'fabric';\n\nfabric.CustomVideo = fabric.util.createClass(fabric.Image, {\n type: 'customvideo',\n cropRect: null,\n\n initialize: function (video: any, options: any) {\n const defaultOpts = {\n lockRotation: true,\n objectCaching: true,\n cacheProperties: ['time']\n }\n options = options || {}\n\n this.callSuper('initialize', video,\n Object.assign({}, defaultOpts, options))\n },\n _draw: function (video: any, ctx: any, w: any, h: any) {\n const c = this.cropRect\n const d = {\n x: -this.width / 2,\n y: -this.height / 2,\n w: this.width,\n h: this.height\n }\n if (c) {\n ctx.drawImage(video, c.x, c.y, c.w, c.h, d.x, d.y, d.w, d.h)\n } else {\n\n // d.x = -415/2 = -207.5\n // d.y = -518.75/2 = -259.375\n // d.w = 415\n // d.h = 518.75 \n ctx.drawImage(video, d.x, d.y, d.w, d.h)\n }\n },\n // _draw: function (video: any, ctx: any, w: any, h: any) {\n // const c = this.cropRect\n // const d = {\n // x: -this.width / 2,\n // y: -this.height / 2,\n // w: this.width,\n // h: this.height\n // }\n // if (c) {\n // ctx.drawImage(video, c.x, c.y, c.w, c.h, d.x, d.y, d.w, d.h)\n // } else {\n // ctx.drawImage(video, d.x, d.y, d.w, d.h)\n // }\n // let factor = this.width / img.naturalWidth * img.naturalHeight > window.innerHeight ? can.height / img.naturalHeight : can.width / img.naturalWidth;\n // },\n\n // let factor = can.width / img.naturalWidth * img.naturalHeight > window.innerHeight ? can.height / img.naturalHeight : can.width / img.naturalWidth;\n // ctx.drawImage(img, 0, 0, img.naturalWidth * factor, img.naturalHeight * factor);\n\n _render: function (ctx: any) {\n // console.log('rendered', this.cropLeft)\n this._draw(this.getElement(), ctx)\n }\n})\n\n","import { fabric } from 'fabric';\nimport type { Canvas } from 'fabric/fabric-impl';\nimport { useDesignStore } from '../stores/design';\nimport './initFabricPrototype.ts';\nimport './fabricSprite.ts';\nimport './fabricCustomVideo.ts';\n\nlet canvas: null | Canvas = null\n\nconst initCanvas = (settings: { width: number, height: number }) => {\n const design = useDesignStore()\n canvas = new fabric.Canvas(design.canvasRef, {\n width: settings.width,\n height: settings.height,\n // preserveObjectStacking: true,\n selection: false,\n allowTouchScrolling: true,\n controlsAboveOverlay:true,\n })\n\n canvas.setBackgroundColor('#FFFFFF', () => { console.log('initCanvas(): completed initial canvas.') });\n canvas.renderAll();\n}\n\ntype TUseCanvas = [Canvas, typeof initCanvas]\nexport default (): TUseCanvas => [canvas as Canvas, initCanvas]\n","export default {\n MODALS_TELEPORT_TARGET: '#teleportModals',\n GRECAPTCHA_DISABLED: false,\n GRECAPTCHA_SITE_KEY: '6LftCzElAAAAAL7FwnHQCJZTQKwXkvLrGxpQbwPV',\n CANVAS_FABRIC_ID: 'fabricCanvas',\n CARD_SIZE: {\n WIDTH: 428,\n HEIGHT: 535,\n },\n CAMERA_CONSTRAINT :{\n WIDTH: 480,\n HEIGHT: 640\n }\n}","import { defineStore, storeToRefs } from \"pinia\";\nimport useFabricCanvas from \"../composables/use-fabric-canvas\";\nimport { fabric } from \"fabric\";\nimport appConstants from \"../app.constants\";\n\nexport interface IPostCardSettings {\n width: number,\n height: number,\n}\n\nexport interface IDesignState {\n wrapperRef: null | HTMLDivElement;\n canvasRef: null | HTMLCanvasElement;\n canvasId: null | string;\n history: Array;\n selectedTheme: number;\n postCardDimensionSettings: IPostCardSettings,\n isBusy: boolean,\n countDown: number,\n isCountingDown: boolean,\n}\n\nexport const useDesignStore = defineStore('design', {\n state: (): IDesignState => ({\n wrapperRef: null,\n canvasRef: null,\n canvasId: appConstants.CANVAS_FABRIC_ID,\n history: [],\n selectedTheme: 1,\n postCardDimensionSettings: {\n width: 0,\n height: 0,\n },\n isBusy: false,\n countDown: 3,\n isCountingDown: false,\n }),\n getters: {\n postCardDimensionSettings() {\n // height / width * 100% \n // 535 / 428 * 100% = 125%\n // ? / 316 * 100% = 125%\n // 125 / 100 * 316% = 395px\n const html = document.documentElement;\n const width = window.innerWidth || html.clientWidth;\n const height = 125 / 100 * width;\n\n if (window.screen.width > 428) {\n console.log(`setHeightWidthFromRatio(): set canvas width : ${appConstants.CARD_SIZE.WIDTH} / height : ${appConstants.CARD_SIZE.HEIGHT}.`);\n const { HEIGHT, WIDTH } = appConstants.CARD_SIZE;\n return { height: HEIGHT, width: WIDTH };\n }\n\n console.log(`setHeightWidthFromRatio(): Set Canvas width : ${width} / height : ${height}.`);\n return { height, width };\n }\n\n },\n actions: {\n undo() {\n const [canvas] = useFabricCanvas();\n\n if (canvas._objects.length > 0) {\n const canvasObj = canvas._objects.pop();\n if (!canvasObj) return;\n this.history.push(canvasObj);\n canvas?.renderAll();\n }\n },\n redo() {\n const [canvas] = useFabricCanvas();\n\n if (this.history.length > 0) {\n const canvasObj = this.history.pop()\n if (!canvasObj) return;\n canvas.add(canvasObj);\n }\n },\n removeFabricCanvasElement(elementName: string) {\n const [canvas] = useFabricCanvas();\n\n canvas._objects.find(item => {\n if (!item) return;\n\n if (item.name === elementName) {\n canvas.remove(item);\n canvas.discardActiveObject();\n canvas.requestRenderAll();\n\n }\n })\n },\n countDownTimer(callback: () => void) {\n this.isCountingDown = true;\n if (this.countDown > 0) {\n setTimeout(() => {\n this.countDown -= 1\n console.log('countDownTimer(): countdown to start recording', new Date().getSeconds())\n this.countDownTimer(callback);\n }, 1000)\n } else {\n this.isCountingDown = false;\n callback && callback();\n }\n },\n seeCanvas() {\n const [canvas] = useFabricCanvas();\n console.log('canvas._objects', canvas._objects);\n const objectXY = canvas._objects.map((item) => {\n\n return {\n id: item.name,\n top: Number(((item.top ?? 0) * 100 / this.postCardDimensionSettings.height).toFixed(2)),\n left: Number(((item.left ?? 0) * 100 / this.postCardDimensionSettings.width).toFixed(2)),\n scale: Number((item.scaleX)?.toFixed(2)),\n flipX: false,\n }\n })\n\n console.log('objectXY', objectXY);\n console.log('objectXY in Json', JSON.stringify(objectXY));\n }\n }\n})\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","var root = require('./_root');\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\nmodule.exports = now;\n","/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nmodule.exports = trimmedEndIndex;\n","var trimmedEndIndex = require('./_trimmedEndIndex');\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nmodule.exports = baseTrim;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var baseTrim = require('./_baseTrim'),\n isObject = require('./isObject'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = toNumber;\n","var isObject = require('./isObject'),\n now = require('./now'),\n toNumber = require('./toNumber');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\nmodule.exports = debounce;\n","import debounce from 'lodash/debounce';\n\nexport function setCssHelperVars() {\n const run = () => {\n const contentMinFullHeight = (window.innerHeight ?? 0);\n document.documentElement.style.setProperty('--content-min-full-height', contentMinFullHeight + 'px');\n setScrollbarWidthCssVar()\n }\n\n window.addEventListener('resize', debounce(run, 300));\n run();\n}\n\nexport function setScrollbarWidthCssVar() {\n // Creating invisible container\n const outer = document.createElement('div');\n outer.style.visibility = 'hidden';\n outer.style.overflow = 'scroll'; // forcing scrollbar to appear\n document.body.appendChild(outer);\n\n // Creating inner element and placing it in the container\n const inner = document.createElement('div');\n outer.appendChild(inner);\n\n // Calculating difference between container's full width and the child width\n const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);\n\n // Removing temporary elements from the DOM\n if (outer.parentNode) {\n outer.parentNode.removeChild(outer);\n }\n\n document.documentElement.style.setProperty('--scrollbar-width', scrollbarWidth + 'px');\n}\n\nexport function remToPixels(value: number) {\n return value * parseFloat(getComputedStyle(document.documentElement).fontSize);\n}\n\nexport function isInViewport(element: HTMLElement) {\n var rect = element.getBoundingClientRect();\n var html = document.documentElement;\n return (\n rect.top >= 0 &&\n rect.left >= 0 &&\n rect.bottom <= (window.innerHeight || html.clientHeight) &&\n rect.right <= (window.innerWidth || html.clientWidth)\n );\n}\n\nexport const scrollToTop = () => {\n document.body.scrollTop = 0; // For Safari\n document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera\n}\n","!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_plugin_advancedFormat=t()}(this,(function(){\"use strict\";return function(e,t){var r=t.prototype,n=r.format;r.format=function(e){var t=this,r=this.$locale();if(!this.isValid())return n.bind(this)(e);var s=this.$utils(),a=(e||\"YYYY-MM-DDTHH:mm:ssZ\").replace(/\\[([^\\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(e){switch(e){case\"Q\":return Math.ceil((t.$M+1)/3);case\"Do\":return r.ordinal(t.$D);case\"gggg\":return t.weekYear();case\"GGGG\":return t.isoWeekYear();case\"wo\":return r.ordinal(t.week(),\"W\");case\"w\":case\"ww\":return s.s(t.week(),\"w\"===e?1:2,\"0\");case\"W\":case\"WW\":return s.s(t.isoWeek(),\"W\"===e?1:2,\"0\");case\"k\":case\"kk\":return s.s(String(0===t.$H?24:t.$H),\"k\"===e?1:2,\"0\");case\"X\":return Math.floor(t.$d.getTime()/1e3);case\"x\":return t.$d.getTime();case\"z\":return\"[\"+t.offsetName()+\"]\";case\"zzz\":return\"[\"+t.offsetName(\"long\")+\"]\";default:return e}}));return n.bind(this)(a)}}}));","import dayjs from 'dayjs';\nimport local from 'dayjs/plugin/utc';\nimport AdvancedFormat from 'dayjs/plugin/advancedFormat';\ndayjs.extend(local);\ndayjs.extend(AdvancedFormat);\n\nexport function formatDateAsString (date: string|Date|undefined|null, formattingToken: string, isUTC = true) {\n if (isUTC) {\n if (typeof date === 'string') {\n if (!date.endsWith('Z')) {\n date = date + 'Z';\n }\n }\n return dayjs(date).local().format(formattingToken)\n }\n return dayjs(date).format(formattingToken)\n}\n","import { v4 as uuid } from 'uuid';\n\nexport function canAcceptFile(file: File, acceptAttributeValue: string, maxFileSize?: number) {\n const fileExtension = file.name.split('.').reverse()[0];\n const acceptedTypes = acceptAttributeValue.split(',').map(x => x.trim().toLowerCase());\n const isWithinSize = maxFileSize ? (file.size <= maxFileSize) : true;\n const isAcceptedType = acceptedTypes.includes('.' + fileExtension.toLowerCase());\n return {\n fileName: file.name,\n isValid: isWithinSize && isAcceptedType,\n reasons: [\n !isWithinSize ? `exceeds the maximum allowed file size of ${formatBytes(maxFileSize || 0)} by ${formatBytes(file.size - (maxFileSize || 0))}` : '',\n !isAcceptedType ? 'not valid file type' : ''\n ].filter(Boolean)\n };\n}\n\nexport function urltoFile(url: string, filename: string, mimeType: string) {\n return (fetch(url)\n .then(function (res) { return res.arrayBuffer(); })\n .then(function (buf) { return new File([buf], filename, { type: mimeType }); })\n );\n}\n\nexport function formatBytes(bytes: number, decimals = 2) {\n if (bytes === 0) return '0 Bytes';\n\n const k = 1024;\n const dm = decimals < 0 ? 0 : decimals;\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n\n return (\n parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + \" \" + sizes[i]\n );\n}\n\nexport function downFile(fileStr: any, fileType: any) {\n const anchorEl = document.createElement('a')\n anchorEl.href = fileStr\n anchorEl.download = `${uuid()}.${fileType}`\n document.body.appendChild(anchorEl) // required for firefox\n anchorEl.click()\n anchorEl.remove()\n}","export const delay = (ms: number) => new Promise((resolve, reject) => {\n setTimeout(resolve, ms);\n }).catch((err) => {\n console.error(`Delay error: ${err}`);\n });","/**\n * Determine the mobile operating system.\n * This function returns one of 'iOS', 'Android', 'Windows Phone', or 'unknown'.\n *\n * @returns {String}\n */\nexport const getMobileOperatingSystem = () => {\n let userAgent = navigator.userAgent || navigator.vendor || window.opera;\n let currentOS = 'unknown';\n\n // Windows Phone must come first because its UA also contains \"Android\"\n if (/windows phone/i.test(userAgent)) {\n currentOS = 'Windows Phone';\n }\n\n if (/android/i.test(userAgent)) {\n currentOS = 'Android';\n }\n\n // iOS detection from: http://stackoverflow.com/a/9039885/177710\n if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {\n currentOS = 'iOS';\n }\n\n console.log('currentOS', currentOS);\n return currentOS;\n}\n\nexport const checkIosVersion = () => {\n var agent = window.navigator.userAgent,\n start = agent.indexOf('OS ');\n\n console.log('agent : ', agent);\n if ((agent.indexOf('iPhone') > -1 || agent.indexOf('iPad') > -1) && start > -1) {\n return window.Number(agent.substr(start + 3, 4).replace('_', '.'));\n }\n return 0;\n}","\nexport default {\n INTEREST_FORM: `/api/online-postgrad-programme-submissions`,\n VIDEO_GENERATE: '/api/v1/video-conversions',\n}","\nexport function useMediaRecorder() {\n\n let mediaRecorderInstance: MediaRecorder | null = null;\n let options: MediaRecorderOptions = {\n audioBitsPerSecond: 128000,\n videoBitsPerSecond: 2500000,\n };\n\n const getMediaRecorderInstance = () => {\n return mediaRecorderInstance;\n }\n\n const loadMediaRecorder = (stream: MediaStream) => {\n console.log(`mobile device support${MediaRecorder.isTypeSupported('video/webm') ? 'video/webm' : 'video/mp4'}`);\n const mimeType = MediaRecorder.isTypeSupported('video/webm') ? 'video/webm' : 'video/mp4';\n options.mimeType = mimeType;\n\n mediaRecorderInstance = new MediaRecorder(stream, options);\n }\n\n const start = () => {\n console.log('mediaRecorderInstance', mediaRecorderInstance?.state);\n if (!mediaRecorderInstance) return;\n mediaRecorderInstance.start();\n console.log('mediaRecorder', mediaRecorderInstance?.state);\n console.log('mediaRecorder(): start recording');\n }\n\n const stop = () => {\n return new Promise((resolve, reject) => {\n if (mediaRecorderInstance) {\n mediaRecorderInstance.addEventListener('dataavailable', ({ data }) => {\n console.log(`dataavailable return : file type: ${data.type} | file size: ${data.size}`);\n return resolve(data)\n });\n\n console.log('mediaRecorder state:' + mediaRecorderInstance.state);\n if (mediaRecorderInstance.state === 'recording') {\n mediaRecorderInstance.stop();\n mediaRecorderInstance = null;\n console.log('mediaRecorder(): stop recording');\n return;\n }\n\n console.log('mediaRecorder(): stop recording not found / stop');\n\n } else {\n reject()\n }\n });\n }\n\n const isTypeSupported = (format: string) => {\n return MediaRecorder.isTypeSupported(format);\n }\n\n return {\n getMediaRecorderInstance,\n loadMediaRecorder,\n isTypeSupported,\n start,\n stop,\n }\n}\n","import { defineStore } from \"pinia\";\nimport useFabricCanvas from \"../composables/use-fabric-canvas\";\nimport { delay } from \"@/modules/core/utilities\";\nimport endpoints from \"@/modules/website/endpoints\";\nimport { useMediaRecorder } from \"../composables\";\nimport { useDesignStore } from \"./design\";\n\nexport interface IPreviewState {\n videoBlob: null | Blob;\n imageString: null | string;\n recordStreamCamRef: null | HTMLVideoElement;\n audioRayaTheme1Ref: null | HTMLAudioElement;\n audioRayaTheme2Ref: null | HTMLAudioElement;\n videoFileType: 'mp4' | 'webm';\n selectedRecordPeriod: number;\n selectedMediaType: 'video' | 'picture' | null,\n isRecordingWebCam: boolean,\n}\n\nexport const usePreviewStore = defineStore('preview', {\n state: (): IPreviewState => ({\n videoBlob: null,\n imageString: null,\n videoFileType: 'webm',\n recordStreamCamRef: null,\n audioRayaTheme1Ref: null,\n audioRayaTheme2Ref: null,\n selectedRecordPeriod: 7,\n selectedMediaType: null,\n isRecordingWebCam: false,\n }),\n getters: {\n },\n actions: {\n mergeAudioFromVideo() {\n console.log('mergeAudioFromVideo(): starting merging audio');\n if (!this.audioRayaTheme1Ref || !this.audioRayaTheme2Ref || !this.recordStreamCamRef) return;\n\n const selectedTheme = useDesignStore().selectedTheme;\n const audioFromSong = selectedTheme === 2 ? this.audioRayaTheme1Ref : this.audioRayaTheme2Ref;\n const audioFromWebCam = this.recordStreamCamRef;\n const audioTouse = this.selectedMediaType === 'video' ? audioFromWebCam : audioFromSong;\n\n // @ts-expect-error\n let AudioContext = window.AudioContext || window.webkitAudioContext;\n if (!AudioContext) return alert(\"Sorry, but the Web Audio API is not supported by your browser. Please, consider upgrading to the latest version or downloading Google Chrome or Mozilla Firefox\");\n\n const audioCtx = new AudioContext();\n const audioSourceNode = audioCtx.createMediaElementSource(audioTouse);\n const destination = audioCtx.createMediaStreamDestination();\n\n audioSourceNode.connect(destination);\n\n console.log('mergeAudioFromVideo(): completed merging audio');\n return destination.stream.getAudioTracks()[0];\n },\n async generateVideoPreviewTry2() {\n if (!this.audioRayaTheme1Ref || !this.audioRayaTheme2Ref || !this.recordStreamCamRef) return;\n \n const selectedTheme = useDesignStore().selectedTheme;\n const audioFromSong = selectedTheme === 2 ? this.audioRayaTheme1Ref : this.audioRayaTheme2Ref;\n const audioFromWebCam = this.recordStreamCamRef;\n const audioToUse = this.selectedMediaType === 'video' ? audioFromWebCam : audioFromSong;\n\n const audioContext = new AudioContext();\n \n // Create two MediaElementAudioSourceNodes, one for the video and one for the audio\n const audioToUseSource = audioContext.createMediaElementSource(audioToUse);\n \n // Create a GainNode to control the volume of the audio sources\n const gainNode = audioContext.createGain();\n // const gainNode2 = audioContext.createGain();\n \n // Set the gain values for the audio sources (between 0 and 1)\n gainNode.gain.value = 1; // Set the volume of the video audio to full\n // gainNode2.gain.value = 0.5; // Set the volume of the song audio to half\n \n // Create a ChannelMergerNode to merge the audio sources\n const mergerNode = audioContext.createChannelMerger(2); // Merge into a stereo output\n \n // Connect the audio sources and gain nodes to the merger node\n audioToUseSource.connect(gainNode).connect(mergerNode, 0, 0); // Connect the video audio to the left channel\n \n // Create a MediaStreamDestination node to capture the audio output\n const mediaStreamDestination = audioContext.createMediaStreamDestination();\n \n // Connect the merger node to the MediaStreamDestination node\n mergerNode.connect(mediaStreamDestination);\n \n // Create a MediaStreamAudioSourceNode from the MediaStreamDestination node\n const audioStreamSource = audioContext.createMediaStreamSource(mediaStreamDestination.stream);\n \n // Create a canvas stream\n let canvasEl = document.getElementById(\"fabricCanvas\") as HTMLCanvasElement;\n const canvasStream = canvasEl.captureStream(60);\n \n // Add the audio context destination to the canvas stream\n canvasStream.addTrack(mediaStreamDestination.stream.getAudioTracks()[0]);\n \n const mediaRecorder = useMediaRecorder();\n mediaRecorder.loadMediaRecorder(canvasStream);\n \n this.videoFileType = mediaRecorder.isTypeSupported('video/webm') ? 'webm' : 'mp4';\n\n try {\n if(this.selectedMediaType !== 'video') {\n selectedTheme === 2 ? this.audioRayaTheme1Ref?.play() : this.audioRayaTheme2Ref?.play();\n } else {\n this.recordStreamCamRef?.play();\n }\n\n mediaRecorder?.start();\n await delay(7000);\n selectedTheme === 2 ? this.audioRayaTheme1Ref?.pause() : this.audioRayaTheme2Ref?.pause();\n\n if ((this.recordStreamCamRef as HTMLVideoElement).currentTime !== 0) {\n this.recordStreamCamRef?.pause();\n }\n\n this.videoBlob = await mediaRecorder.stop();\n \n console.log('completed', this.videoBlob );\n } catch (error) {\n console.log('hidden error', error);\n }\n \n },\n async generateImagePreview() {\n console.log('generateImagePreview(): start generating preview');\n\n let canvasEl = document.getElementById(\"fabricCanvas\") as HTMLCanvasElement;\n this.imageString = canvasEl.toDataURL('image/png');\n\n console.log('generateImagePreview(): complete generating preview');\n },\n async transcodeVideo(recaptchaResponse?: string) {\n if (!this.videoBlob) return;\n console.log('transcodeVideo(): start transcoding video');\n\n const startTime = performance.now(); // get start time\n let blob = new Blob([this.videoBlob]);\n\n let formData = new FormData();\n let file = new File([blob], 'Selamat-Hari-Raya.webm');\n formData.append('File', file, 'Selamat-Hari-Raya.webm');\n\n const config: RequestInit = {\n method: 'POST',\n body: formData,\n }\n\n if (recaptchaResponse) {\n config.headers = { 'x-g-recaptcha-response': recaptchaResponse };\n }\n\n const request = await fetch(endpoints.VIDEO_GENERATE, config);\n this.videoBlob = await request.blob();\n\n const endTime = performance.now(); // get end time\n const totalTime = endTime - startTime; // calculate total time\n\n console.log(`transcodeVideo(): completed transcoding video in ${totalTime} milliseconds`);\n },\n\n }\n})\n","import { createPinia } from 'pinia';\n\nconst pinia = createPinia()\n\nexport * from './design';\nexport * from './preview';\n\nexport default pinia;","import { defineComponent, computed, ref, openBlock, createBlock, TransitionGroup, mergeProps, withCtx, renderSlot, Transition, resolveComponent } from 'vue';\n\nvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nfunction createCommonjsModule(fn, basedir, module) {\n\treturn module = {\n\t\tpath: basedir,\n\t\texports: {},\n\t\trequire: function (path, base) {\n\t\t\treturn commonjsRequire(path, (base === undefined || base === null) ? module.path : base);\n\t\t}\n\t}, fn(module, module.exports), module.exports;\n}\n\nfunction getDefaultExportFromNamespaceIfPresent (n) {\n\treturn n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;\n}\n\nfunction getDefaultExportFromNamespaceIfNotNamed (n) {\n\treturn n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;\n}\n\nfunction getAugmentedNamespace(n) {\n\tif (n.__esModule) return n;\n\tvar a = Object.defineProperty({}, '__esModule', {value: true});\n\tObject.keys(n).forEach(function (k) {\n\t\tvar d = Object.getOwnPropertyDescriptor(n, k);\n\t\tObject.defineProperty(a, k, d.get ? d : {\n\t\t\tenumerable: true,\n\t\t\tget: function () {\n\t\t\t\treturn n[k];\n\t\t\t}\n\t\t});\n\t});\n\treturn a;\n}\n\nfunction commonjsRequire () {\n\tthrow new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');\n}\n\nvar check = function (it) {\n return it && it.Math == Math && it;\n};\n\n// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nvar global_1 =\n // eslint-disable-next-line es/no-global-this -- safe\n check(typeof globalThis == 'object' && globalThis) ||\n check(typeof window == 'object' && window) ||\n // eslint-disable-next-line no-restricted-globals -- safe\n check(typeof self == 'object' && self) ||\n check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||\n // eslint-disable-next-line no-new-func -- fallback\n (function () { return this; })() || Function('return this')();\n\nvar fails = function (exec) {\n try {\n return !!exec();\n } catch (error) {\n return true;\n }\n};\n\n// Detect IE8's incomplete defineProperty implementation\nvar descriptors = !fails(function () {\n // eslint-disable-next-line es/no-object-defineproperty -- required for testing\n return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;\n});\n\n'use strict';\nvar $propertyIsEnumerable = {}.propertyIsEnumerable;\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar getOwnPropertyDescriptor$2 = Object.getOwnPropertyDescriptor;\n\n// Nashorn ~ JDK8 bug\nvar NASHORN_BUG = getOwnPropertyDescriptor$2 && !$propertyIsEnumerable.call({ 1: 2 }, 1);\n\n// `Object.prototype.propertyIsEnumerable` method implementation\n// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable\nvar f$4 = NASHORN_BUG ? function propertyIsEnumerable(V) {\n var descriptor = getOwnPropertyDescriptor$2(this, V);\n return !!descriptor && descriptor.enumerable;\n} : $propertyIsEnumerable;\n\nvar objectPropertyIsEnumerable = {\n\tf: f$4\n};\n\nvar createPropertyDescriptor = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n\nvar toString = {}.toString;\n\nvar classofRaw = function (it) {\n return toString.call(it).slice(8, -1);\n};\n\nvar split = ''.split;\n\n// fallback for non-array-like ES3 and non-enumerable old V8 strings\nvar indexedObject = fails(function () {\n // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346\n // eslint-disable-next-line no-prototype-builtins -- safe\n return !Object('z').propertyIsEnumerable(0);\n}) ? function (it) {\n return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);\n} : Object;\n\n// `RequireObjectCoercible` abstract operation\n// https://tc39.es/ecma262/#sec-requireobjectcoercible\nvar requireObjectCoercible = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n\n// toObject with fallback for non-array-like ES3 strings\n\n\n\nvar toIndexedObject = function (it) {\n return indexedObject(requireObjectCoercible(it));\n};\n\nvar isObject = function (it) {\n return typeof it === 'object' ? it !== null : typeof it === 'function';\n};\n\n// `ToPrimitive` abstract operation\n// https://tc39.es/ecma262/#sec-toprimitive\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nvar toPrimitive = function (input, PREFERRED_STRING) {\n if (!isObject(input)) return input;\n var fn, val;\n if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;\n if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;\n if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n\n// `ToObject` abstract operation\n// https://tc39.es/ecma262/#sec-toobject\nvar toObject = function (argument) {\n return Object(requireObjectCoercible(argument));\n};\n\nvar hasOwnProperty = {}.hasOwnProperty;\n\nvar has$1 = function hasOwn(it, key) {\n return hasOwnProperty.call(toObject(it), key);\n};\n\nvar document$1 = global_1.document;\n// typeof document.createElement is 'object' in old IE\nvar EXISTS = isObject(document$1) && isObject(document$1.createElement);\n\nvar documentCreateElement = function (it) {\n return EXISTS ? document$1.createElement(it) : {};\n};\n\n// Thank's IE8 for his funny defineProperty\nvar ie8DomDefine = !descriptors && !fails(function () {\n // eslint-disable-next-line es/no-object-defineproperty -- requied for testing\n return Object.defineProperty(documentCreateElement('div'), 'a', {\n get: function () { return 7; }\n }).a != 7;\n});\n\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// `Object.getOwnPropertyDescriptor` method\n// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor\nvar f$3 = descriptors ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {\n O = toIndexedObject(O);\n P = toPrimitive(P, true);\n if (ie8DomDefine) try {\n return $getOwnPropertyDescriptor(O, P);\n } catch (error) { /* empty */ }\n if (has$1(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]);\n};\n\nvar objectGetOwnPropertyDescriptor = {\n\tf: f$3\n};\n\nvar anObject = function (it) {\n if (!isObject(it)) {\n throw TypeError(String(it) + ' is not an object');\n } return it;\n};\n\n// eslint-disable-next-line es/no-object-defineproperty -- safe\nvar $defineProperty = Object.defineProperty;\n\n// `Object.defineProperty` method\n// https://tc39.es/ecma262/#sec-object.defineproperty\nvar f$2 = descriptors ? $defineProperty : function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPrimitive(P, true);\n anObject(Attributes);\n if (ie8DomDefine) try {\n return $defineProperty(O, P, Attributes);\n } catch (error) { /* empty */ }\n if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');\n if ('value' in Attributes) O[P] = Attributes.value;\n return O;\n};\n\nvar objectDefineProperty = {\n\tf: f$2\n};\n\nvar createNonEnumerableProperty = descriptors ? function (object, key, value) {\n return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n\nvar setGlobal = function (key, value) {\n try {\n createNonEnumerableProperty(global_1, key, value);\n } catch (error) {\n global_1[key] = value;\n } return value;\n};\n\nvar SHARED = '__core-js_shared__';\nvar store$1 = global_1[SHARED] || setGlobal(SHARED, {});\n\nvar sharedStore = store$1;\n\nvar functionToString = Function.toString;\n\n// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper\nif (typeof sharedStore.inspectSource != 'function') {\n sharedStore.inspectSource = function (it) {\n return functionToString.call(it);\n };\n}\n\nvar inspectSource = sharedStore.inspectSource;\n\nvar WeakMap$1 = global_1.WeakMap;\n\nvar nativeWeakMap = typeof WeakMap$1 === 'function' && /native code/.test(inspectSource(WeakMap$1));\n\nvar isPure = false;\n\nvar shared = createCommonjsModule(function (module) {\n(module.exports = function (key, value) {\n return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {});\n})('versions', []).push({\n version: '3.12.1',\n mode: isPure ? 'pure' : 'global',\n copyright: '© 2021 Denis Pushkarev (zloirock.ru)'\n});\n});\n\nvar id = 0;\nvar postfix = Math.random();\n\nvar uid = function (key) {\n return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);\n};\n\nvar keys$1 = shared('keys');\n\nvar sharedKey = function (key) {\n return keys$1[key] || (keys$1[key] = uid(key));\n};\n\nvar hiddenKeys$1 = {};\n\nvar OBJECT_ALREADY_INITIALIZED = 'Object already initialized';\nvar WeakMap = global_1.WeakMap;\nvar set, get, has;\n\nvar enforce = function (it) {\n return has(it) ? get(it) : set(it, {});\n};\n\nvar getterFor = function (TYPE) {\n return function (it) {\n var state;\n if (!isObject(it) || (state = get(it)).type !== TYPE) {\n throw TypeError('Incompatible receiver, ' + TYPE + ' required');\n } return state;\n };\n};\n\nif (nativeWeakMap || sharedStore.state) {\n var store = sharedStore.state || (sharedStore.state = new WeakMap());\n var wmget = store.get;\n var wmhas = store.has;\n var wmset = store.set;\n set = function (it, metadata) {\n if (wmhas.call(store, it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);\n metadata.facade = it;\n wmset.call(store, it, metadata);\n return metadata;\n };\n get = function (it) {\n return wmget.call(store, it) || {};\n };\n has = function (it) {\n return wmhas.call(store, it);\n };\n} else {\n var STATE = sharedKey('state');\n hiddenKeys$1[STATE] = true;\n set = function (it, metadata) {\n if (has$1(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);\n metadata.facade = it;\n createNonEnumerableProperty(it, STATE, metadata);\n return metadata;\n };\n get = function (it) {\n return has$1(it, STATE) ? it[STATE] : {};\n };\n has = function (it) {\n return has$1(it, STATE);\n };\n}\n\nvar internalState = {\n set: set,\n get: get,\n has: has,\n enforce: enforce,\n getterFor: getterFor\n};\n\nvar redefine = createCommonjsModule(function (module) {\nvar getInternalState = internalState.get;\nvar enforceInternalState = internalState.enforce;\nvar TEMPLATE = String(String).split('String');\n\n(module.exports = function (O, key, value, options) {\n var unsafe = options ? !!options.unsafe : false;\n var simple = options ? !!options.enumerable : false;\n var noTargetGet = options ? !!options.noTargetGet : false;\n var state;\n if (typeof value == 'function') {\n if (typeof key == 'string' && !has$1(value, 'name')) {\n createNonEnumerableProperty(value, 'name', key);\n }\n state = enforceInternalState(value);\n if (!state.source) {\n state.source = TEMPLATE.join(typeof key == 'string' ? key : '');\n }\n }\n if (O === global_1) {\n if (simple) O[key] = value;\n else setGlobal(key, value);\n return;\n } else if (!unsafe) {\n delete O[key];\n } else if (!noTargetGet && O[key]) {\n simple = true;\n }\n if (simple) O[key] = value;\n else createNonEnumerableProperty(O, key, value);\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n})(Function.prototype, 'toString', function toString() {\n return typeof this == 'function' && getInternalState(this).source || inspectSource(this);\n});\n});\n\nvar path = global_1;\n\nvar aFunction$1 = function (variable) {\n return typeof variable == 'function' ? variable : undefined;\n};\n\nvar getBuiltIn = function (namespace, method) {\n return arguments.length < 2 ? aFunction$1(path[namespace]) || aFunction$1(global_1[namespace])\n : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];\n};\n\nvar ceil = Math.ceil;\nvar floor = Math.floor;\n\n// `ToInteger` abstract operation\n// https://tc39.es/ecma262/#sec-tointeger\nvar toInteger = function (argument) {\n return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);\n};\n\nvar min$1 = Math.min;\n\n// `ToLength` abstract operation\n// https://tc39.es/ecma262/#sec-tolength\nvar toLength = function (argument) {\n return argument > 0 ? min$1(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991\n};\n\nvar max = Math.max;\nvar min = Math.min;\n\n// Helper for a popular repeating case of the spec:\n// Let integer be ? ToInteger(index).\n// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).\nvar toAbsoluteIndex = function (index, length) {\n var integer = toInteger(index);\n return integer < 0 ? max(integer + length, 0) : min(integer, length);\n};\n\n// `Array.prototype.{ indexOf, includes }` methods implementation\nvar createMethod$3 = function (IS_INCLUDES) {\n return function ($this, el, fromIndex) {\n var O = toIndexedObject($this);\n var length = toLength(O.length);\n var index = toAbsoluteIndex(fromIndex, length);\n var value;\n // Array#includes uses SameValueZero equality algorithm\n // eslint-disable-next-line no-self-compare -- NaN check\n if (IS_INCLUDES && el != el) while (length > index) {\n value = O[index++];\n // eslint-disable-next-line no-self-compare -- NaN check\n if (value != value) return true;\n // Array#indexOf ignores holes, Array#includes - not\n } else for (;length > index; index++) {\n if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;\n } return !IS_INCLUDES && -1;\n };\n};\n\nvar arrayIncludes = {\n // `Array.prototype.includes` method\n // https://tc39.es/ecma262/#sec-array.prototype.includes\n includes: createMethod$3(true),\n // `Array.prototype.indexOf` method\n // https://tc39.es/ecma262/#sec-array.prototype.indexof\n indexOf: createMethod$3(false)\n};\n\nvar indexOf = arrayIncludes.indexOf;\n\n\nvar objectKeysInternal = function (object, names) {\n var O = toIndexedObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) !has$1(hiddenKeys$1, key) && has$1(O, key) && result.push(key);\n // Don't enum bug & hidden keys\n while (names.length > i) if (has$1(O, key = names[i++])) {\n ~indexOf(result, key) || result.push(key);\n }\n return result;\n};\n\n// IE8- don't enum bug keys\nvar enumBugKeys = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf'\n];\n\nvar hiddenKeys = enumBugKeys.concat('length', 'prototype');\n\n// `Object.getOwnPropertyNames` method\n// https://tc39.es/ecma262/#sec-object.getownpropertynames\n// eslint-disable-next-line es/no-object-getownpropertynames -- safe\nvar f$1 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {\n return objectKeysInternal(O, hiddenKeys);\n};\n\nvar objectGetOwnPropertyNames = {\n\tf: f$1\n};\n\n// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe\nvar f = Object.getOwnPropertySymbols;\n\nvar objectGetOwnPropertySymbols = {\n\tf: f\n};\n\n// all object keys, includes non-enumerable and symbols\nvar ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {\n var keys = objectGetOwnPropertyNames.f(anObject(it));\n var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;\n return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;\n};\n\nvar copyConstructorProperties = function (target, source) {\n var keys = ownKeys(source);\n var defineProperty = objectDefineProperty.f;\n var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (!has$1(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));\n }\n};\n\nvar replacement = /#|\\.prototype\\./;\n\nvar isForced = function (feature, detection) {\n var value = data[normalize(feature)];\n return value == POLYFILL ? true\n : value == NATIVE ? false\n : typeof detection == 'function' ? fails(detection)\n : !!detection;\n};\n\nvar normalize = isForced.normalize = function (string) {\n return String(string).replace(replacement, '.').toLowerCase();\n};\n\nvar data = isForced.data = {};\nvar NATIVE = isForced.NATIVE = 'N';\nvar POLYFILL = isForced.POLYFILL = 'P';\n\nvar isForced_1 = isForced;\n\nvar getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;\n\n\n\n\n\n\n/*\n options.target - name of the target object\n options.global - target is the global object\n options.stat - export as static methods of target\n options.proto - export as prototype methods of target\n options.real - real prototype method for the `pure` version\n options.forced - export even if the native feature is available\n options.bind - bind methods to the target, required for the `pure` version\n options.wrap - wrap constructors to preventing global pollution, required for the `pure` version\n options.unsafe - use the simple assignment of property instead of delete + defineProperty\n options.sham - add a flag to not completely full polyfills\n options.enumerable - export as enumerable property\n options.noTargetGet - prevent calling a getter on target\n*/\nvar _export = function (options, source) {\n var TARGET = options.target;\n var GLOBAL = options.global;\n var STATIC = options.stat;\n var FORCED, target, key, targetProperty, sourceProperty, descriptor;\n if (GLOBAL) {\n target = global_1;\n } else if (STATIC) {\n target = global_1[TARGET] || setGlobal(TARGET, {});\n } else {\n target = (global_1[TARGET] || {}).prototype;\n }\n if (target) for (key in source) {\n sourceProperty = source[key];\n if (options.noTargetGet) {\n descriptor = getOwnPropertyDescriptor$1(target, key);\n targetProperty = descriptor && descriptor.value;\n } else targetProperty = target[key];\n FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);\n // contained in target\n if (!FORCED && targetProperty !== undefined) {\n if (typeof sourceProperty === typeof targetProperty) continue;\n copyConstructorProperties(sourceProperty, targetProperty);\n }\n // add a flag to not completely full polyfills\n if (options.sham || (targetProperty && targetProperty.sham)) {\n createNonEnumerableProperty(sourceProperty, 'sham', true);\n }\n // extend global\n redefine(target, key, sourceProperty, options);\n }\n};\n\nvar aFunction = function (it) {\n if (typeof it != 'function') {\n throw TypeError(String(it) + ' is not a function');\n } return it;\n};\n\n// optional / simple context binding\nvar functionBindContext = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 0: return function () {\n return fn.call(that);\n };\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n\n// `IsArray` abstract operation\n// https://tc39.es/ecma262/#sec-isarray\n// eslint-disable-next-line es/no-array-isarray -- safe\nvar isArray = Array.isArray || function isArray(arg) {\n return classofRaw(arg) == 'Array';\n};\n\nvar engineUserAgent = getBuiltIn('navigator', 'userAgent') || '';\n\nvar process = global_1.process;\nvar versions = process && process.versions;\nvar v8 = versions && versions.v8;\nvar match, version;\n\nif (v8) {\n match = v8.split('.');\n version = match[0] < 4 ? 1 : match[0] + match[1];\n} else if (engineUserAgent) {\n match = engineUserAgent.match(/Edge\\/(\\d+)/);\n if (!match || match[1] >= 74) {\n match = engineUserAgent.match(/Chrome\\/(\\d+)/);\n if (match) version = match[1];\n }\n}\n\nvar engineV8Version = version && +version;\n\n/* eslint-disable es/no-symbol -- required for testing */\n\n\n\n// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing\nvar nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {\n return !String(Symbol()) ||\n // Chrome 38 Symbol has incorrect toString conversion\n // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances\n !Symbol.sham && engineV8Version && engineV8Version < 41;\n});\n\n/* eslint-disable es/no-symbol -- required for testing */\n\n\nvar useSymbolAsUid = nativeSymbol\n && !Symbol.sham\n && typeof Symbol.iterator == 'symbol';\n\nvar WellKnownSymbolsStore = shared('wks');\nvar Symbol$1 = global_1.Symbol;\nvar createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid;\n\nvar wellKnownSymbol = function (name) {\n if (!has$1(WellKnownSymbolsStore, name) || !(nativeSymbol || typeof WellKnownSymbolsStore[name] == 'string')) {\n if (nativeSymbol && has$1(Symbol$1, name)) {\n WellKnownSymbolsStore[name] = Symbol$1[name];\n } else {\n WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);\n }\n } return WellKnownSymbolsStore[name];\n};\n\nvar SPECIES = wellKnownSymbol('species');\n\n// `ArraySpeciesCreate` abstract operation\n// https://tc39.es/ecma262/#sec-arrayspeciescreate\nvar arraySpeciesCreate = function (originalArray, length) {\n var C;\n if (isArray(originalArray)) {\n C = originalArray.constructor;\n // cross-realm fallback\n if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;\n else if (isObject(C)) {\n C = C[SPECIES];\n if (C === null) C = undefined;\n }\n } return new (C === undefined ? Array : C)(length === 0 ? 0 : length);\n};\n\nvar push = [].push;\n\n// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterOut }` methods implementation\nvar createMethod$2 = function (TYPE) {\n var IS_MAP = TYPE == 1;\n var IS_FILTER = TYPE == 2;\n var IS_SOME = TYPE == 3;\n var IS_EVERY = TYPE == 4;\n var IS_FIND_INDEX = TYPE == 6;\n var IS_FILTER_OUT = TYPE == 7;\n var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;\n return function ($this, callbackfn, that, specificCreate) {\n var O = toObject($this);\n var self = indexedObject(O);\n var boundFunction = functionBindContext(callbackfn, that, 3);\n var length = toLength(self.length);\n var index = 0;\n var create = specificCreate || arraySpeciesCreate;\n var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_OUT ? create($this, 0) : undefined;\n var value, result;\n for (;length > index; index++) if (NO_HOLES || index in self) {\n value = self[index];\n result = boundFunction(value, index, O);\n if (TYPE) {\n if (IS_MAP) target[index] = result; // map\n else if (result) switch (TYPE) {\n case 3: return true; // some\n case 5: return value; // find\n case 6: return index; // findIndex\n case 2: push.call(target, value); // filter\n } else switch (TYPE) {\n case 4: return false; // every\n case 7: push.call(target, value); // filterOut\n }\n }\n }\n return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;\n };\n};\n\nvar arrayIteration = {\n // `Array.prototype.forEach` method\n // https://tc39.es/ecma262/#sec-array.prototype.foreach\n forEach: createMethod$2(0),\n // `Array.prototype.map` method\n // https://tc39.es/ecma262/#sec-array.prototype.map\n map: createMethod$2(1),\n // `Array.prototype.filter` method\n // https://tc39.es/ecma262/#sec-array.prototype.filter\n filter: createMethod$2(2),\n // `Array.prototype.some` method\n // https://tc39.es/ecma262/#sec-array.prototype.some\n some: createMethod$2(3),\n // `Array.prototype.every` method\n // https://tc39.es/ecma262/#sec-array.prototype.every\n every: createMethod$2(4),\n // `Array.prototype.find` method\n // https://tc39.es/ecma262/#sec-array.prototype.find\n find: createMethod$2(5),\n // `Array.prototype.findIndex` method\n // https://tc39.es/ecma262/#sec-array.prototype.findIndex\n findIndex: createMethod$2(6),\n // `Array.prototype.filterOut` method\n // https://github.com/tc39/proposal-array-filtering\n filterOut: createMethod$2(7)\n};\n\n'use strict';\n\n\nvar arrayMethodIsStrict = function (METHOD_NAME, argument) {\n var method = [][METHOD_NAME];\n return !!method && fails(function () {\n // eslint-disable-next-line no-useless-call,no-throw-literal -- required for testing\n method.call(null, argument || function () { throw 1; }, 1);\n });\n};\n\n'use strict';\nvar $forEach = arrayIteration.forEach;\n\n\nvar STRICT_METHOD = arrayMethodIsStrict('forEach');\n\n// `Array.prototype.forEach` method implementation\n// https://tc39.es/ecma262/#sec-array.prototype.foreach\nvar arrayForEach = !STRICT_METHOD ? function forEach(callbackfn /* , thisArg */) {\n return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n// eslint-disable-next-line es/no-array-prototype-foreach -- safe\n} : [].forEach;\n\n'use strict';\n\n\n\n// `Array.prototype.forEach` method\n// https://tc39.es/ecma262/#sec-array.prototype.foreach\n// eslint-disable-next-line es/no-array-prototype-foreach -- safe\n_export({ target: 'Array', proto: true, forced: [].forEach != arrayForEach }, {\n forEach: arrayForEach\n});\n\nvar es_array_forEach = {\n\n};\n\n// iterable DOM collections\n// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods\nvar domIterables = {\n CSSRuleList: 0,\n CSSStyleDeclaration: 0,\n CSSValueList: 0,\n ClientRectList: 0,\n DOMRectList: 0,\n DOMStringList: 0,\n DOMTokenList: 1,\n DataTransferItemList: 0,\n FileList: 0,\n HTMLAllCollection: 0,\n HTMLCollection: 0,\n HTMLFormElement: 0,\n HTMLSelectElement: 0,\n MediaList: 0,\n MimeTypeArray: 0,\n NamedNodeMap: 0,\n NodeList: 1,\n PaintRequestList: 0,\n Plugin: 0,\n PluginArray: 0,\n SVGLengthList: 0,\n SVGNumberList: 0,\n SVGPathSegList: 0,\n SVGPointList: 0,\n SVGStringList: 0,\n SVGTransformList: 0,\n SourceBufferList: 0,\n StyleSheetList: 0,\n TextTrackCueList: 0,\n TextTrackList: 0,\n TouchList: 0\n};\n\nfor (var COLLECTION_NAME in domIterables) {\n var Collection = global_1[COLLECTION_NAME];\n var CollectionPrototype = Collection && Collection.prototype;\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype && CollectionPrototype.forEach !== arrayForEach) try {\n createNonEnumerableProperty(CollectionPrototype, 'forEach', arrayForEach);\n } catch (error) {\n CollectionPrototype.forEach = arrayForEach;\n }\n}\n\nvar web_domCollections_forEach = {\n\n};\n\n// `Object.keys` method\n// https://tc39.es/ecma262/#sec-object.keys\n// eslint-disable-next-line es/no-object-keys -- safe\nvar objectKeys = Object.keys || function keys(O) {\n return objectKeysInternal(O, enumBugKeys);\n};\n\nvar propertyIsEnumerable = objectPropertyIsEnumerable.f;\n\n// `Object.{ entries, values }` methods implementation\nvar createMethod$1 = function (TO_ENTRIES) {\n return function (it) {\n var O = toIndexedObject(it);\n var keys = objectKeys(O);\n var length = keys.length;\n var i = 0;\n var result = [];\n var key;\n while (length > i) {\n key = keys[i++];\n if (!descriptors || propertyIsEnumerable.call(O, key)) {\n result.push(TO_ENTRIES ? [key, O[key]] : O[key]);\n }\n }\n return result;\n };\n};\n\nvar objectToArray = {\n // `Object.entries` method\n // https://tc39.es/ecma262/#sec-object.entries\n entries: createMethod$1(true),\n // `Object.values` method\n // https://tc39.es/ecma262/#sec-object.values\n values: createMethod$1(false)\n};\n\nvar $entries = objectToArray.entries;\n\n// `Object.entries` method\n// https://tc39.es/ecma262/#sec-object.entries\n_export({ target: 'Object', stat: true }, {\n entries: function entries(O) {\n return $entries(O);\n }\n});\n\nvar es_object_entries = {\n\n};\n\nvar aPossiblePrototype = function (it) {\n if (!isObject(it) && it !== null) {\n throw TypeError(\"Can't set \" + String(it) + ' as a prototype');\n } return it;\n};\n\n/* eslint-disable no-proto -- safe */\n\n\n\n// `Object.setPrototypeOf` method\n// https://tc39.es/ecma262/#sec-object.setprototypeof\n// Works with __proto__ only. Old v8 can't work with null proto objects.\n// eslint-disable-next-line es/no-object-setprototypeof -- safe\nvar objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {\n var CORRECT_SETTER = false;\n var test = {};\n var setter;\n try {\n // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\n setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;\n setter.call(test, []);\n CORRECT_SETTER = test instanceof Array;\n } catch (error) { /* empty */ }\n return function setPrototypeOf(O, proto) {\n anObject(O);\n aPossiblePrototype(proto);\n if (CORRECT_SETTER) setter.call(O, proto);\n else O.__proto__ = proto;\n return O;\n };\n}() : undefined);\n\n// makes subclassing work correct for wrapped built-ins\nvar inheritIfRequired = function ($this, dummy, Wrapper) {\n var NewTarget, NewTargetPrototype;\n if (\n // it can work only with native `setPrototypeOf`\n objectSetPrototypeOf &&\n // we haven't completely correct pre-ES6 way for getting `new.target`, so use this\n typeof (NewTarget = dummy.constructor) == 'function' &&\n NewTarget !== Wrapper &&\n isObject(NewTargetPrototype = NewTarget.prototype) &&\n NewTargetPrototype !== Wrapper.prototype\n ) objectSetPrototypeOf($this, NewTargetPrototype);\n return $this;\n};\n\n// `Object.defineProperties` method\n// https://tc39.es/ecma262/#sec-object.defineproperties\n// eslint-disable-next-line es/no-object-defineproperties -- safe\nvar objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) {\n anObject(O);\n var keys = objectKeys(Properties);\n var length = keys.length;\n var index = 0;\n var key;\n while (length > index) objectDefineProperty.f(O, key = keys[index++], Properties[key]);\n return O;\n};\n\nvar html = getBuiltIn('document', 'documentElement');\n\nvar GT = '>';\nvar LT = '<';\nvar PROTOTYPE = 'prototype';\nvar SCRIPT = 'script';\nvar IE_PROTO = sharedKey('IE_PROTO');\n\nvar EmptyConstructor = function () { /* empty */ };\n\nvar scriptTag = function (content) {\n return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;\n};\n\n// Create object with fake `null` prototype: use ActiveX Object with cleared prototype\nvar NullProtoObjectViaActiveX = function (activeXDocument) {\n activeXDocument.write(scriptTag(''));\n activeXDocument.close();\n var temp = activeXDocument.parentWindow.Object;\n activeXDocument = null; // avoid memory leak\n return temp;\n};\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar NullProtoObjectViaIFrame = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = documentCreateElement('iframe');\n var JS = 'java' + SCRIPT + ':';\n var iframeDocument;\n iframe.style.display = 'none';\n html.appendChild(iframe);\n // https://github.com/zloirock/core-js/issues/475\n iframe.src = String(JS);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(scriptTag('document.F=Object'));\n iframeDocument.close();\n return iframeDocument.F;\n};\n\n// Check for document.domain and active x support\n// No need to use active x approach when document.domain is not set\n// see https://github.com/es-shims/es5-shim/issues/150\n// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346\n// avoid IE GC bug\nvar activeXDocument;\nvar NullProtoObject = function () {\n try {\n /* global ActiveXObject -- old IE */\n activeXDocument = document.domain && new ActiveXObject('htmlfile');\n } catch (error) { /* ignore */ }\n NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();\n var length = enumBugKeys.length;\n while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];\n return NullProtoObject();\n};\n\nhiddenKeys$1[IE_PROTO] = true;\n\n// `Object.create` method\n// https://tc39.es/ecma262/#sec-object.create\nvar objectCreate = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n EmptyConstructor[PROTOTYPE] = anObject(O);\n result = new EmptyConstructor();\n EmptyConstructor[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = NullProtoObject();\n return Properties === undefined ? result : objectDefineProperties(result, Properties);\n};\n\n// a string of all valid unicode whitespaces\nvar whitespaces = '\\u0009\\u000A\\u000B\\u000C\\u000D\\u0020\\u00A0\\u1680\\u2000\\u2001\\u2002' +\n '\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF';\n\nvar whitespace = '[' + whitespaces + ']';\nvar ltrim = RegExp('^' + whitespace + whitespace + '*');\nvar rtrim = RegExp(whitespace + whitespace + '*$');\n\n// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation\nvar createMethod = function (TYPE) {\n return function ($this) {\n var string = String(requireObjectCoercible($this));\n if (TYPE & 1) string = string.replace(ltrim, '');\n if (TYPE & 2) string = string.replace(rtrim, '');\n return string;\n };\n};\n\nvar stringTrim = {\n // `String.prototype.{ trimLeft, trimStart }` methods\n // https://tc39.es/ecma262/#sec-string.prototype.trimstart\n start: createMethod(1),\n // `String.prototype.{ trimRight, trimEnd }` methods\n // https://tc39.es/ecma262/#sec-string.prototype.trimend\n end: createMethod(2),\n // `String.prototype.trim` method\n // https://tc39.es/ecma262/#sec-string.prototype.trim\n trim: createMethod(3)\n};\n\n'use strict';\n\n\n\n\n\n\n\n\n\n\nvar getOwnPropertyNames = objectGetOwnPropertyNames.f;\nvar getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;\nvar defineProperty$1 = objectDefineProperty.f;\nvar trim = stringTrim.trim;\n\nvar NUMBER = 'Number';\nvar NativeNumber = global_1[NUMBER];\nvar NumberPrototype = NativeNumber.prototype;\n\n// Opera ~12 has broken Object#toString\nvar BROKEN_CLASSOF = classofRaw(objectCreate(NumberPrototype)) == NUMBER;\n\n// `ToNumber` abstract operation\n// https://tc39.es/ecma262/#sec-tonumber\nvar toNumber = function (argument) {\n var it = toPrimitive(argument, false);\n var first, third, radix, maxCode, digits, length, index, code;\n if (typeof it == 'string' && it.length > 2) {\n it = trim(it);\n first = it.charCodeAt(0);\n if (first === 43 || first === 45) {\n third = it.charCodeAt(2);\n if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix\n } else if (first === 48) {\n switch (it.charCodeAt(1)) {\n case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i\n case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i\n default: return +it;\n }\n digits = it.slice(2);\n length = digits.length;\n for (index = 0; index < length; index++) {\n code = digits.charCodeAt(index);\n // parseInt parses a string to a first unavailable symbol\n // but ToNumber should return NaN if a string contains unavailable symbols\n if (code < 48 || code > maxCode) return NaN;\n } return parseInt(digits, radix);\n }\n } return +it;\n};\n\n// `Number` constructor\n// https://tc39.es/ecma262/#sec-number-constructor\nif (isForced_1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {\n var NumberWrapper = function Number(value) {\n var it = arguments.length < 1 ? 0 : value;\n var dummy = this;\n return dummy instanceof NumberWrapper\n // check on 1..constructor(foo) case\n && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classofRaw(dummy) != NUMBER)\n ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);\n };\n for (var keys = descriptors ? getOwnPropertyNames(NativeNumber) : (\n // ES3:\n 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +\n // ES2015 (in case, if modules with ES2015 Number statics required before):\n 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +\n 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger,' +\n // ESNext\n 'fromString,range'\n ).split(','), j = 0, key; keys.length > j; j++) {\n if (has$1(NativeNumber, key = keys[j]) && !has$1(NumberWrapper, key)) {\n defineProperty$1(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key));\n }\n }\n NumberWrapper.prototype = NumberPrototype;\n NumberPrototype.constructor = NumberWrapper;\n redefine(global_1, NUMBER, NumberWrapper);\n}\n\nvar es_number_constructor = {\n\n};\n\nvar UNSCOPABLES = wellKnownSymbol('unscopables');\nvar ArrayPrototype = Array.prototype;\n\n// Array.prototype[@@unscopables]\n// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables\nif (ArrayPrototype[UNSCOPABLES] == undefined) {\n objectDefineProperty.f(ArrayPrototype, UNSCOPABLES, {\n configurable: true,\n value: objectCreate(null)\n });\n}\n\n// add a key to Array.prototype[@@unscopables]\nvar addToUnscopables = function (key) {\n ArrayPrototype[UNSCOPABLES][key] = true;\n};\n\n'use strict';\n\nvar $includes = arrayIncludes.includes;\n\n\n// `Array.prototype.includes` method\n// https://tc39.es/ecma262/#sec-array.prototype.includes\n_export({ target: 'Array', proto: true }, {\n includes: function includes(el /* , fromIndex = 0 */) {\n return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n\n// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables('includes');\n\nvar es_array_includes = {\n\n};\n\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function _typeof(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nfunction __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nfunction __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nfunction __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nfunction __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nvar __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nfunction __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nfunction __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nfunction __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nfunction __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nfunction __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nfunction __spreadArray(to, from) {\r\n for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\r\n to[j] = from[i];\r\n return to;\r\n}\r\n\r\nfunction __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nfunction __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nfunction __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nfunction __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nfunction __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nfunction __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nfunction __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\n\n/**\r\n * Cannot be reused as es6 does not import comments used for storybook props desc\r\n * Good to keep for lib export\r\n * */\nvar props = {\n /**\r\n * Specifies the duration of the transition in milliseconds.\r\n * Also accepts separate values for enter and leave durations `e.g { enter: 500, leave: 800 }`\r\n */\n duration: {\n type: [Number, Object],\n \"default\": 500\n },\n\n /**\r\n * The entry style animation type.\r\n * Accepts `center` `left` `right` `top` `bottom`\r\n */\n entry: {\n type: String,\n \"default\": 'center',\n validator: function validator(value) {\n return ['center', 'left', 'right', 'top', 'bottom'].includes(value);\n }\n },\n\n /**\r\n * The exit style animation type.\r\n * Accepts `center` `left` `right` `top` `bottom`\r\n */\n exit: {\n type: String,\n \"default\": 'center',\n validator: function validator(value) {\n return ['center', 'left', 'right', 'top', 'bottom'].includes(value);\n }\n },\n\n /**\r\n * Whether to apply the transition on initial render.\r\n */\n appear: {\n type: Boolean,\n required: false\n },\n\n /**\r\n * Controls the timing sequence of leaving/entering transitions.\r\n * Accepts `out-in` or `in-out`\r\n * Required when used with router-view.\r\n * Only exposed when group is false\r\n */\n mode: {\n type: String,\n required: false,\n validator: function validator(value) {\n return ['out-in', 'in-out'].includes(value);\n }\n },\n\n /**\r\n * Whether transition effects are for multiple elements/components.\r\n * Every child in a group must be uniquely keyed for the animations to work properly.\r\n */\n group: {\n type: Boolean,\n required: false\n },\n\n /**\r\n * If not defined, renders without a root element.\r\n * Only usable if group is true.\r\n */\n tag: {\n type: String,\n required: false\n },\n\n /**\r\n * Speed up transitions by skipping hooks.\r\n * Only to be used if elements are show/hidden, e.g v-show.\r\n * Does not work if elements are inserted/removed, e.g v-if\r\n */\n persisted: {\n type: Boolean,\n required: false\n }\n};\n\nvar script$2 = defineComponent({\n name: 'base-transition-component',\n props: __assign(__assign({}, props), {\n name: {\n type: String,\n \"default\": null,\n required: true\n }\n }),\n setup: function setup(props, _a) {\n var emit = _a.emit;\n /**\r\n * Removes the custom props so they aren't rendered within the HTML\r\n */\n\n var baseProps = computed(function () {\n var entry = props[\"entry\"],\n withoutEntry = __rest(props, ['entry']);\n\n var exit = withoutEntry[\"exit\"],\n withoutEntryExit = __rest(withoutEntry, ['exit']);\n\n var group = withoutEntryExit[\"group\"],\n defaultProps = __rest(withoutEntryExit, ['group']);\n\n return defaultProps;\n });\n var defaultDuration = ref(500);\n var durationObj = computed(function () {\n var _a, _b;\n\n var enter = props.duration || defaultDuration.value;\n var leave = props.duration || defaultDuration.value;\n\n if (_typeof(props.duration) === 'object') {\n enter = ((_a = props.duration) === null || _a === void 0 ? void 0 : _a.enter) || defaultDuration.value;\n leave = ((_b = props.duration) === null || _b === void 0 ? void 0 : _b.leave) || defaultDuration.value;\n }\n\n return {\n enter: enter,\n leave: leave\n };\n });\n\n var insertDuration = function insertDuration(el) {\n var _a, _b, _c;\n\n if (el) {\n if (props.group) {\n var slotItems = el.children;\n\n for (var i = 0; i < slotItems.length; i++) {\n if ((_a = slotItems[i]) === null || _a === void 0 ? void 0 : _a.style) {\n slotItems[i].style.transitionDuration = ((_b = durationObj.value) === null || _b === void 0 ? void 0 : _b.enter) + 'ms';\n }\n }\n } else {\n if (el.style) {\n el.style.transitionDuration = ((_c = durationObj.value) === null || _c === void 0 ? void 0 : _c.enter) + 'ms';\n }\n }\n\n emit('onEnter', el);\n }\n };\n\n var insertLeaveDuration = function insertLeaveDuration(el) {\n var _a, _b, _c;\n\n if (el) {\n if (props.group) {\n var slotItems = el.children;\n\n for (var i = 0; i < slotItems.length; i++) {\n if ((_a = slotItems[i]) === null || _a === void 0 ? void 0 : _a.style) {\n slotItems[i].style.transitionDuration = ((_b = durationObj.value) === null || _b === void 0 ? void 0 : _b.leave) + 'ms';\n }\n }\n } else {\n if (el.style) {\n el.style.transitionDuration = ((_c = durationObj.value) === null || _c === void 0 ? void 0 : _c.leave) + 'ms';\n }\n }\n\n emit('onLeave', el);\n }\n };\n\n return {\n baseProps: baseProps,\n insertDuration: insertDuration,\n insertLeaveDuration: insertLeaveDuration\n };\n }\n});\n\nvar defineProperty = objectDefineProperty.f;\n\nvar FunctionPrototype = Function.prototype;\nvar FunctionPrototypeToString = FunctionPrototype.toString;\nvar nameRE = /^\\s*function ([^ (]*)/;\nvar NAME = 'name';\n\n// Function instances `.name` property\n// https://tc39.es/ecma262/#sec-function-instances-name\nif (descriptors && !(NAME in FunctionPrototype)) {\n defineProperty(FunctionPrototype, NAME, {\n configurable: true,\n get: function () {\n try {\n return FunctionPrototypeToString.call(this).match(nameRE)[1];\n } catch (error) {\n return '';\n }\n }\n });\n}\n\nvar es_function_name = {\n\n};\n\nfunction render$2(_ctx, _cache, $props, $setup, $data, $options) {\n return _ctx.group ? (openBlock(), createBlock(TransitionGroup, mergeProps({\n key: 0\n }, _ctx.baseProps, {\n onEnter: _cache[1] || (_cache[1] = function ($event) {\n return _ctx.insertDuration(_ctx.$el);\n }),\n onBeforeLeave: _cache[2] || (_cache[2] = function ($event) {\n return _ctx.insertLeaveDuration(_ctx.$el);\n }),\n name: _ctx.name\n }), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"default\")];\n }),\n _: 3\n }, 16, [\"name\"])) : (openBlock(), createBlock(Transition, mergeProps({\n key: 1\n }, _ctx.baseProps, {\n onEnter: _cache[3] || (_cache[3] = function ($event) {\n return _ctx.insertDuration(_ctx.$el);\n }),\n onBeforeLeave: _cache[4] || (_cache[4] = function ($event) {\n return _ctx.insertLeaveDuration(_ctx.$el);\n }),\n name: _ctx.name\n }), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"default\")];\n }),\n _: 3\n }, 16, [\"name\"]));\n}\n\nscript$2.render = render$2;\n\nvar script$1 = defineComponent({\n name: 'fade-in-out',\n components: {\n BaseTransitionComponent: script$2\n },\n props: {\n /**\r\n * Specifies the duration of the transition in milliseconds.\r\n * Also accepts separate values for enter and leave durations `e.g { enter: 500, leave: 800 }`\r\n */\n duration: {\n type: [Number, Object],\n \"default\": 500\n },\n\n /**\r\n * The entry style animation type.\r\n * Accepts `center` `left`\r\n */\n entry: {\n type: String,\n \"default\": 'center',\n validator: function validator(value) {\n return ['center', 'left'].includes(value);\n }\n },\n\n /**\r\n * The exit style animation type.\r\n * Accepts `center` `left` `right` `top` `bottom`\r\n */\n exit: {\n type: String,\n \"default\": 'center',\n validator: function validator(value) {\n return ['center', 'left', 'right', 'top', 'bottom'].includes(value);\n }\n },\n\n /**\r\n * Whether to apply the transition on initial render.\r\n */\n appear: {\n type: Boolean,\n required: false\n },\n\n /**\r\n * Controls the timing sequence of leaving/entering transitions.\r\n * Accepts `out-in` or `in-out`\r\n * Required when used with router-view.\r\n * Only exposed when group is false\r\n */\n mode: {\n type: String,\n required: false,\n validator: function validator(value) {\n return ['out-in', 'in-out'].includes(value);\n }\n },\n\n /**\r\n * Whether transition effects are for multiple elements/components.\r\n * Every child in a group must be uniquely keyed for the animations to work properly.\r\n */\n group: {\n type: Boolean,\n required: false\n },\n\n /**\r\n * If not defined, renders without a root element.\r\n * Only usable if group is true.\r\n */\n tag: {\n type: String,\n required: false\n },\n\n /**\r\n * Speed up transitions by skipping hooks.\r\n * Only to be used if elements are show/hidden, e.g v-show.\r\n * Does not work if elements are inserted/removed, e.g v-if\r\n */\n persisted: {\n type: Boolean,\n required: false\n }\n },\n setup: function setup(props) {\n var transitionType = ref('fio'); // FadeInOut\n\n var firstChar = function firstChar(type) {\n return type.substring(0, 1);\n };\n\n var transitionName = computed(function () {\n return \"vt_\" + transitionType.value + \"-\" + firstChar(props.entry) + \"-\" + firstChar(props.exit);\n });\n return {\n props: props,\n transitionType: transitionType,\n transitionName: transitionName\n };\n }\n});\n\nfunction render$1(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_BaseTransitionComponent = resolveComponent(\"BaseTransitionComponent\");\n\n return openBlock(), createBlock(_component_BaseTransitionComponent, mergeProps(_ctx.props, {\n name: _ctx.transitionName\n }), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"default\")];\n }),\n _: 3\n }, 16, [\"name\"]);\n}\n\nfunction styleInject(css, ref) {\n if ( ref === void 0 ) ref = {};\n var insertAt = ref.insertAt;\n\n if (!css || typeof document === 'undefined') { return; }\n\n var head = document.head || document.getElementsByTagName('head')[0];\n var style = document.createElement('style');\n style.type = 'text/css';\n\n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild);\n } else {\n head.appendChild(style);\n }\n } else {\n head.appendChild(style);\n }\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n style.appendChild(document.createTextNode(css));\n }\n}\n\nvar css_248z$1 = \".vt_fio-c-c-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-c-enter-from,.vt_fio-c-c-leave-to{opacity:0;-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-c-enter-to,.vt_fio-c-c-leave-from{opacity:1}.vt_fio-c-l-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-l-enter-from,.vt_fio-c-l-leave-to{opacity:0;-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-c-l-enter-to,.vt_fio-c-l-leave-from{opacity:1}.vt_fio-c-r-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-r-enter-from,.vt_fio-c-r-leave-to{opacity:0;-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(10%,0,0);transform:translate3d(10%,0,0)}.vt_fio-c-r-enter-to,.vt_fio-c-r-leave-from{opacity:1}.vt_fio-c-t-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-t-leave-to{opacity:0;-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(0,-10%,0);transform:translate3d(0,-10%,0)}.vt_fio-c-t-enter-from{opacity:0}.vt_fio-c-t-enter-to,.vt_fio-c-t-leave-from{opacity:1}.vt_fio-c-b-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-b-enter-from,.vt_fio-c-b-leave-to{opacity:0;-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(0,10%,0);transform:translate3d(0,10%,0)}.vt_fio-c-b-enter-to,.vt_fio-c-b-leave-from{opacity:1}.vt_fio-l-c-enter-active{-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-c-enter-active,.vt_fio-l-c-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_fio-l-c-enter-from,.vt_fio-l-c-leave-to{opacity:0}.vt_fio-l-c-enter-to,.vt_fio-l-c-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_fio-l-l-enter-active,.vt_fio-l-l-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-l-enter-from,.vt_fio-l-l-leave-to{opacity:0}.vt_fio-l-l-enter-to,.vt_fio-l-l-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_fio-l-r-enter-active{-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-r-enter-active,.vt_fio-l-r-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_fio-l-r-leave-to{opacity:0;-webkit-transform:translate3d(10%,0,0);transform:translate3d(10%,0,0)}.vt_fio-l-r-enter-from{opacity:0}.vt_fio-l-r-enter-to,.vt_fio-l-r-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_fio-l-t-enter-active{-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-t-enter-active,.vt_fio-l-t-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_fio-l-t-leave-to{opacity:0;-webkit-transform:translate3d(0,-10%,0);transform:translate3d(0,-10%,0)}.vt_fio-l-t-enter-from{opacity:0}.vt_fio-l-t-enter-to,.vt_fio-l-t-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_fio-l-b-enter-active{-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-b-enter-active,.vt_fio-l-b-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_fio-l-b-leave-to{opacity:0;-webkit-transform:translate3d(0,10%,0);transform:translate3d(0,10%,0)}.vt_fio-l-b-enter-from{opacity:0}.vt_fio-l-b-enter-to,.vt_fio-l-b-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}\";\nvar stylesheet$1 = \".vt_fio-c-c-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-c-enter-from,.vt_fio-c-c-leave-to{opacity:0;-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-c-enter-to,.vt_fio-c-c-leave-from{opacity:1}.vt_fio-c-l-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-l-enter-from,.vt_fio-c-l-leave-to{opacity:0;-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-c-l-enter-to,.vt_fio-c-l-leave-from{opacity:1}.vt_fio-c-r-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-r-enter-from,.vt_fio-c-r-leave-to{opacity:0;-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(10%,0,0);transform:translate3d(10%,0,0)}.vt_fio-c-r-enter-to,.vt_fio-c-r-leave-from{opacity:1}.vt_fio-c-t-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-t-leave-to{opacity:0;-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(0,-10%,0);transform:translate3d(0,-10%,0)}.vt_fio-c-t-enter-from{opacity:0}.vt_fio-c-t-enter-to,.vt_fio-c-t-leave-from{opacity:1}.vt_fio-c-b-enter-active{-webkit-transition:opacity ease-in;-o-transition:opacity ease-in;transition:opacity ease-in}.vt_fio-c-b-enter-from,.vt_fio-c-b-leave-to{opacity:0;-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(0,10%,0);transform:translate3d(0,10%,0)}.vt_fio-c-b-enter-to,.vt_fio-c-b-leave-from{opacity:1}.vt_fio-l-c-enter-active{-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-c-enter-active,.vt_fio-l-c-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_fio-l-c-enter-from,.vt_fio-l-c-leave-to{opacity:0}.vt_fio-l-c-enter-to,.vt_fio-l-c-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_fio-l-l-enter-active,.vt_fio-l-l-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-l-enter-from,.vt_fio-l-l-leave-to{opacity:0}.vt_fio-l-l-enter-to,.vt_fio-l-l-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_fio-l-r-enter-active{-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-r-enter-active,.vt_fio-l-r-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_fio-l-r-leave-to{opacity:0;-webkit-transform:translate3d(10%,0,0);transform:translate3d(10%,0,0)}.vt_fio-l-r-enter-from{opacity:0}.vt_fio-l-r-enter-to,.vt_fio-l-r-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_fio-l-t-enter-active{-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-t-enter-active,.vt_fio-l-t-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_fio-l-t-leave-to{opacity:0;-webkit-transform:translate3d(0,-10%,0);transform:translate3d(0,-10%,0)}.vt_fio-l-t-enter-from{opacity:0}.vt_fio-l-t-enter-to,.vt_fio-l-t-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_fio-l-b-enter-active{-webkit-transform:translate3d(-10%,0,0);transform:translate3d(-10%,0,0)}.vt_fio-l-b-enter-active,.vt_fio-l-b-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_fio-l-b-leave-to{opacity:0;-webkit-transform:translate3d(0,10%,0);transform:translate3d(0,10%,0)}.vt_fio-l-b-enter-from{opacity:0}.vt_fio-l-b-enter-to,.vt_fio-l-b-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}\";\nstyleInject(css_248z$1);\n\nscript$1.render = render$1;\n\nvar script = defineComponent({\n name: 'slide-in-out',\n components: {\n BaseTransitionComponent: script$2\n },\n props: {\n /**\r\n * Specifies the duration of the transition in milliseconds.\r\n * Also accepts separate values for enter and leave durations `e.g { enter: 500, leave: 800 }`\r\n */\n duration: {\n type: [Number, Object],\n \"default\": 500\n },\n\n /**\r\n * The entry style animation type.\r\n * Accepts `left` `right`\r\n */\n entry: {\n type: String,\n \"default\": 'left',\n validator: function validator(value) {\n return ['left', 'right'].includes(value);\n }\n },\n\n /**\r\n * The exit style animation type.\r\n * Accepts left` `right` `top` `bottom`\r\n */\n exit: {\n type: String,\n \"default\": 'left',\n validator: function validator(value) {\n return ['left', 'right', 'top', 'bottom'].includes(value);\n }\n },\n\n /**\r\n * Whether to apply the transition on initial render.\r\n */\n appear: {\n type: Boolean,\n required: false\n },\n\n /**\r\n * Controls the timing sequence of leaving/entering transitions.\r\n * Accepts `out-in` or `in-out`\r\n * Required when used with router-view.\r\n * Only exposed when group is false\r\n */\n mode: {\n type: String,\n required: false,\n validator: function validator(value) {\n return ['out-in', 'in-out'].includes(value);\n }\n },\n\n /**\r\n * Whether transition effects are for multiple elements/components.\r\n * Every child in a group must be uniquely keyed for the animations to work properly.\r\n */\n group: {\n type: Boolean,\n required: false\n },\n\n /**\r\n * If not defined, renders without a root element.\r\n * Only usable if group is true.\r\n */\n tag: {\n type: String,\n required: false\n },\n\n /**\r\n * Speed up transitions by skipping hooks.\r\n * Only to be used if elements are show/hidden, e.g v-show.\r\n * Does not work if elements are inserted/removed, e.g v-if\r\n */\n persisted: {\n type: Boolean,\n required: false\n }\n },\n setup: function setup(props) {\n var transitionType = ref('sio'); // SlideInOut\n\n var firstChar = function firstChar(type) {\n return type.substring(0, 1);\n };\n\n var transitionName = computed(function () {\n return \"vt_\" + transitionType.value + \"-\" + firstChar(props.entry) + \"-\" + firstChar(props.exit);\n });\n return {\n props: props,\n transitionType: transitionType,\n transitionName: transitionName\n };\n }\n});\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_BaseTransitionComponent = resolveComponent(\"BaseTransitionComponent\");\n\n return openBlock(), createBlock(_component_BaseTransitionComponent, mergeProps(_ctx.props, {\n name: _ctx.transitionName\n }), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"default\")];\n }),\n _: 3\n }, 16, [\"name\"]);\n}\n\nvar css_248z = \".vt_sio-l-r-enter-active{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-l-r-enter-active,.vt_sio-l-r-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-l-r-leave-to{opacity:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-l-r-enter-from{opacity:0}.vt_sio-l-r-enter-to,.vt_sio-l-r-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-l-l-enter-active,.vt_sio-l-l-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-l-l-enter-from,.vt_sio-l-l-leave-to{opacity:0}.vt_sio-l-l-enter-to,.vt_sio-l-l-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-l-t-enter-active{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-l-t-enter-active,.vt_sio-l-t-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-l-t-leave-to{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}.vt_sio-l-t-enter-from{opacity:0}.vt_sio-l-t-enter-to,.vt_sio-l-t-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-l-b-enter-active{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-l-b-enter-active,.vt_sio-l-b-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-l-b-leave-to{opacity:0;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}.vt_sio-l-b-enter-from{opacity:0}.vt_sio-l-b-enter-to,.vt_sio-l-b-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-r-r-enter-active,.vt_sio-r-r-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-r-r-enter-from,.vt_sio-r-r-leave-to{opacity:0}.vt_sio-r-r-enter-to,.vt_sio-r-r-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-r-l-enter-active{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-r-l-enter-active,.vt_sio-r-l-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-r-l-leave-to{opacity:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-r-l-enter-from{opacity:0}.vt_sio-r-l-enter-to,.vt_sio-r-l-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-r-t-enter-active{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-r-t-enter-active,.vt_sio-r-t-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-r-t-leave-to{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}.vt_sio-r-t-enter-from{opacity:0}.vt_sio-r-t-enter-to,.vt_sio-r-t-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-r-b-enter-active{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-r-b-enter-active,.vt_sio-r-b-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-r-b-leave-to{opacity:0;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}.vt_sio-r-b-enter-from{opacity:0}.vt_sio-r-b-enter-to,.vt_sio-r-b-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}\";\nvar stylesheet = \".vt_sio-l-r-enter-active{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-l-r-enter-active,.vt_sio-l-r-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-l-r-leave-to{opacity:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-l-r-enter-from{opacity:0}.vt_sio-l-r-enter-to,.vt_sio-l-r-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-l-l-enter-active,.vt_sio-l-l-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-l-l-enter-from,.vt_sio-l-l-leave-to{opacity:0}.vt_sio-l-l-enter-to,.vt_sio-l-l-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-l-t-enter-active{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-l-t-enter-active,.vt_sio-l-t-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-l-t-leave-to{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}.vt_sio-l-t-enter-from{opacity:0}.vt_sio-l-t-enter-to,.vt_sio-l-t-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-l-b-enter-active{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-l-b-enter-active,.vt_sio-l-b-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-l-b-leave-to{opacity:0;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}.vt_sio-l-b-enter-from{opacity:0}.vt_sio-l-b-enter-to,.vt_sio-l-b-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-r-r-enter-active,.vt_sio-r-r-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-r-r-enter-from,.vt_sio-r-r-leave-to{opacity:0}.vt_sio-r-r-enter-to,.vt_sio-r-r-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-r-l-enter-active{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-r-l-enter-active,.vt_sio-r-l-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-r-l-leave-to{opacity:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.vt_sio-r-l-enter-from{opacity:0}.vt_sio-r-l-enter-to,.vt_sio-r-l-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-r-t-enter-active{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-r-t-enter-active,.vt_sio-r-t-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-r-t-leave-to{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}.vt_sio-r-t-enter-from{opacity:0}.vt_sio-r-t-enter-to,.vt_sio-r-t-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}.vt_sio-r-b-enter-active{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.vt_sio-r-b-enter-active,.vt_sio-r-b-leave-to{-webkit-transition:all ease-in;-o-transition:all ease-in;transition:all ease-in}.vt_sio-r-b-leave-to{opacity:0;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}.vt_sio-r-b-enter-from{opacity:0}.vt_sio-r-b-enter-to,.vt_sio-r-b-leave-from{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}\";\nstyleInject(css_248z);\n\nscript.render = render;\n\nvar components = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tFadeInOut: script$1,\n\tSlideInOut: script\n});\n\nvar install = function install(app) {\n Object.entries(components).forEach(function (_a) {\n var componentName = _a[0],\n component = _a[1];\n app.component(componentName, component);\n });\n};\n\nexport default install;\nexport { script$1 as FadeInOut, script as SlideInOut };\n","export default \"__VITE_PUBLIC_ASSET__f4e32afa__\"","export default \"__VITE_PUBLIC_ASSET__46d3b890__\"","export default \"__VITE_PUBLIC_ASSET__dea2f477__\"","\n\n\n","\n\n\n\n","import { ref } from 'vue';\nimport debounce from 'lodash/debounce';\nimport { Toast } from '@/modules/core/types';\n\nconst toasts = ref>([]);\n\nexport const useNotifications = () => {\n\n const showToast = (toast: Toast) => {\n toasts.value.push(toast)\n }\n\n const showToastDebounced = debounce((toast: Toast) => {\n showToast(toast)\n }, 200, { leading: false, trailing: true })\n\n const handleToastHidden = (toast: Toast) => {\n const index = toasts.value.indexOf(toast);\n if (index !== -1) {\n toasts.value.splice(index, 1);\n }\n }\n\n return {\n toasts,\n showToast,\n handleToastHidden,\n showToastDebounced,\n }\n}","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.Splitting = factory());\n}(this, (function () { 'use strict';\n\nvar root = document;\nvar createText = root.createTextNode.bind(root);\n\n/**\n * # setProperty\n * Apply a CSS var\n * @param el{HTMLElement} \n * @param varName {string} \n * @param value {string|number} \n */\nfunction setProperty(el, varName, value) {\n el.style.setProperty(varName, value);\n} \n\n/**\n * \n * @param {Node} el \n * @param {Node} child \n */\nfunction appendChild(el, child) {\n return el.appendChild(child);\n}\n\nfunction createElement(parent, key, text, whitespace) {\n var el = root.createElement('span');\n key && (el.className = key); \n if (text) { \n !whitespace && el.setAttribute(\"data-\" + key, text);\n el.textContent = text; \n }\n return (parent && appendChild(parent, el)) || el;\n}\n\nfunction getData(el, key) {\n return el.getAttribute(\"data-\" + key)\n}\n\n/**\n * \n * @param e {import('../types').Target} \n * @param parent {HTMLElement}\n * @returns {HTMLElement[]}\n */\nfunction $(e, parent) {\n return !e || e.length == 0\n ? // null or empty string returns empty array\n []\n : e.nodeName\n ? // a single element is wrapped in an array\n [e]\n : // selector and NodeList are converted to Element[]\n [].slice.call(e[0].nodeName ? e : (parent || root).querySelectorAll(e));\n}\n\n/**\n * Creates and fills an array with the value provided\n * @template {T}\n * @param {number} len\n * @param {() => T} valueProvider\n * @return {T}\n */\nfunction Array2D(len) {\n var a = [];\n for (; len--; ) {\n a[len] = [];\n }\n return a;\n}\n\nfunction each(items, fn) {\n items && items.some(fn);\n}\n\nfunction selectFrom(obj) {\n return function (key) {\n return obj[key];\n }\n}\n\n/**\n * # Splitting.index\n * Index split elements and add them to a Splitting instance.\n *\n * @param element {HTMLElement}\n * @param key {string}\n * @param items {HTMLElement[] | HTMLElement[][]}\n */\nfunction index(element, key, items) {\n var prefix = '--' + key;\n var cssVar = prefix + \"-index\";\n\n each(items, function (items, i) {\n if (Array.isArray(items)) {\n each(items, function(item) {\n setProperty(item, cssVar, i);\n });\n } else {\n setProperty(items, cssVar, i);\n }\n });\n\n setProperty(element, prefix + \"-total\", items.length);\n}\n\n/**\n * @type {Record}\n */\nvar plugins = {};\n\n/**\n * @param by {string}\n * @param parent {string}\n * @param deps {string[]}\n * @return {string[]}\n */\nfunction resolvePlugins(by, parent, deps) {\n // skip if already visited this dependency\n var index = deps.indexOf(by);\n if (index == -1) {\n // if new to dependency array, add to the beginning\n deps.unshift(by);\n\n // recursively call this function for all dependencies\n each(plugins[by].depends, function(p) {\n resolvePlugins(p, by, deps);\n });\n } else {\n // if this dependency was added already move to the left of\n // the parent dependency so it gets loaded in order\n var indexOfParent = deps.indexOf(parent);\n deps.splice(index, 1);\n deps.splice(indexOfParent, 0, by);\n }\n return deps;\n}\n\n/**\n * Internal utility for creating plugins... essentially to reduce\n * the size of the library\n * @param {string} by \n * @param {string} key \n * @param {string[]} depends \n * @param {Function} split \n * @returns {import('./types').ISplittingPlugin}\n */\nfunction createPlugin(by, depends, key, split) {\n return {\n by: by,\n depends: depends,\n key: key,\n split: split\n }\n}\n\n/**\n *\n * @param by {string}\n * @returns {import('./types').ISplittingPlugin[]}\n */\nfunction resolve(by) {\n return resolvePlugins(by, 0, []).map(selectFrom(plugins));\n}\n\n/**\n * Adds a new plugin to splitting\n * @param opts {import('./types').ISplittingPlugin}\n */\nfunction add(opts) {\n plugins[opts.by] = opts;\n}\n\n/**\n * # Splitting.split\n * Split an element's textContent into individual elements\n * @param el {Node} Element to split\n * @param key {string}\n * @param splitOn {string}\n * @param includeSpace {boolean}\n * @returns {HTMLElement[]}\n */\nfunction splitText(el, key, splitOn, includePrevious, preserveWhitespace) {\n // Combine any strange text nodes or empty whitespace.\n el.normalize();\n\n // Use fragment to prevent unnecessary DOM thrashing.\n var elements = [];\n var F = document.createDocumentFragment();\n\n if (includePrevious) {\n elements.push(el.previousSibling);\n }\n\n var allElements = [];\n $(el.childNodes).some(function(next) {\n if (next.tagName && !next.hasChildNodes()) {\n // keep elements without child nodes (no text and no children)\n allElements.push(next);\n return;\n }\n // Recursively run through child nodes\n if (next.childNodes && next.childNodes.length) {\n allElements.push(next);\n elements.push.apply(elements, splitText(next, key, splitOn, includePrevious, preserveWhitespace));\n return;\n }\n\n // Get the text to split, trimming out the whitespace\n /** @type {string} */\n var wholeText = next.wholeText || '';\n var contents = wholeText.trim();\n\n // If there's no text left after trimming whitespace, continue the loop\n if (contents.length) {\n // insert leading space if there was one\n if (wholeText[0] === ' ') {\n allElements.push(createText(' '));\n }\n // Concatenate the split text children back into the full array\n each(contents.split(splitOn), function(splitText, i) {\n if (i && preserveWhitespace) {\n allElements.push(createElement(F, \"whitespace\", \" \", preserveWhitespace));\n }\n var splitEl = createElement(F, key, splitText);\n elements.push(splitEl);\n allElements.push(splitEl);\n }); \n // insert trailing space if there was one\n if (wholeText[wholeText.length - 1] === ' ') {\n allElements.push(createText(' '));\n }\n }\n });\n\n each(allElements, function(el) {\n appendChild(F, el);\n });\n\n // Clear out the existing element\n el.innerHTML = \"\";\n appendChild(el, F);\n return elements;\n}\n\n/** an empty value */\nvar _ = 0;\n\nfunction copy(dest, src) {\n for (var k in src) {\n dest[k] = src[k];\n }\n return dest;\n}\n\nvar WORDS = 'words';\n\nvar wordPlugin = createPlugin(\n /*by: */ WORDS,\n /*depends: */ _,\n /*key: */ 'word', \n /*split: */ function(el) {\n return splitText(el, 'word', /\\s+/, 0, 1)\n }\n);\n\nvar CHARS = \"chars\";\n\nvar charPlugin = createPlugin(\n /*by: */ CHARS,\n /*depends: */ [WORDS],\n /*key: */ \"char\", \n /*split: */ function(el, options, ctx) {\n var results = [];\n\n each(ctx[WORDS], function(word, i) {\n results.push.apply(results, splitText(word, \"char\", \"\", options.whitespace && i));\n });\n\n return results;\n }\n);\n\n/**\n * # Splitting\n * \n * @param opts {import('./types').ISplittingOptions} \n */\nfunction Splitting (opts) {\n opts = opts || {};\n var key = opts.key;\n\n return $(opts.target || '[data-splitting]').map(function(el) {\n var ctx = el['🍌']; \n if (!opts.force && ctx) {\n return ctx;\n }\n\n ctx = el['🍌'] = { el: el };\n var items = resolve(opts.by || getData(el, 'splitting') || CHARS);\n var opts2 = copy({}, opts);\n each(items, function(plugin) {\n if (plugin.split) {\n var pluginBy = plugin.by;\n var key2 = (key ? '-' + key : '') + plugin.key;\n var results = plugin.split(el, opts2, ctx);\n key2 && index(el, key2, results);\n ctx[pluginBy] = results;\n el.classList.add(pluginBy);\n } \n });\n\n el.classList.add('splitting');\n return ctx;\n })\n}\n\n/**\n * # Splitting.html\n * \n * @param opts {import('./types').ISplittingOptions}\n */\nfunction html(opts) {\n opts = opts || {};\n var parent = opts.target = createElement();\n parent.innerHTML = opts.content;\n Splitting(opts);\n return parent.outerHTML\n}\n\nSplitting.html = html;\nSplitting.add = add;\n\nfunction detectGrid(el, options, side) {\n var items = $(options.matching || el.children, el);\n var c = {};\n\n each(items, function(w) {\n var val = Math.round(w[side]);\n (c[val] || (c[val] = [])).push(w);\n });\n\n return Object.keys(c).map(Number).sort(byNumber).map(selectFrom(c));\n}\n\nfunction byNumber(a, b) {\n return a - b;\n}\n\nvar linePlugin = createPlugin(\n /*by: */ 'lines',\n /*depends: */ [WORDS],\n /*key: */ 'line',\n /*split: */ function(el, options, ctx) {\n return detectGrid(el, { matching: ctx[WORDS] }, 'offsetTop')\n }\n);\n\nvar itemPlugin = createPlugin(\n /*by: */ 'items',\n /*depends: */ _,\n /*key: */ 'item', \n /*split: */ function(el, options) {\n return $(options.matching || el.children, el)\n }\n);\n\nvar rowPlugin = createPlugin(\n /*by: */ 'rows',\n /*depends: */ _,\n /*key: */ 'row', \n /*split: */ function(el, options) {\n return detectGrid(el, options, \"offsetTop\");\n }\n);\n\nvar columnPlugin = createPlugin(\n /*by: */ 'cols',\n /*depends: */ _,\n /*key: */ \"col\", \n /*split: */ function(el, options) {\n return detectGrid(el, options, \"offsetLeft\");\n }\n);\n\nvar gridPlugin = createPlugin(\n /*by: */ 'grid',\n /*depends: */ ['rows', 'cols']\n);\n\nvar LAYOUT = \"layout\";\n\nvar layoutPlugin = createPlugin(\n /*by: */ LAYOUT,\n /*depends: */ _,\n /*key: */ _,\n /*split: */ function(el, opts) {\n // detect and set options\n var rows = opts.rows = +(opts.rows || getData(el, 'rows') || 1);\n var columns = opts.columns = +(opts.columns || getData(el, 'columns') || 1);\n\n // Seek out the first if the value is true \n opts.image = opts.image || getData(el, 'image') || el.currentSrc || el.src;\n if (opts.image) {\n var img = $(\"img\", el)[0];\n opts.image = img && (img.currentSrc || img.src);\n }\n\n // add optional image to background\n if (opts.image) {\n setProperty(el, \"background-image\", \"url(\" + opts.image + \")\");\n }\n\n var totalCells = rows * columns;\n var elements = [];\n\n var container = createElement(_, \"cell-grid\");\n while (totalCells--) {\n // Create a span\n var cell = createElement(container, \"cell\");\n createElement(cell, \"cell-inner\");\n elements.push(cell);\n }\n\n // Append elements back into the parent\n appendChild(el, container);\n\n return elements;\n }\n);\n\nvar cellRowPlugin = createPlugin(\n /*by: */ \"cellRows\",\n /*depends: */ [LAYOUT],\n /*key: */ \"row\",\n /*split: */ function(el, opts, ctx) {\n var rowCount = opts.rows;\n var result = Array2D(rowCount);\n\n each(ctx[LAYOUT], function(cell, i, src) {\n result[Math.floor(i / (src.length / rowCount))].push(cell);\n });\n\n return result;\n }\n);\n\nvar cellColumnPlugin = createPlugin(\n /*by: */ \"cellColumns\",\n /*depends: */ [LAYOUT],\n /*key: */ \"col\",\n /*split: */ function(el, opts, ctx) {\n var columnCount = opts.columns;\n var result = Array2D(columnCount);\n\n each(ctx[LAYOUT], function(cell, i) {\n result[i % columnCount].push(cell);\n });\n\n return result;\n }\n);\n\nvar cellPlugin = createPlugin(\n /*by: */ \"cells\",\n /*depends: */ ['cellRows', 'cellColumns'],\n /*key: */ \"cell\", \n /*split: */ function(el, opt, ctx) { \n // re-index the layout as the cells\n return ctx[LAYOUT];\n }\n);\n\n// install plugins\n// word/char plugins\nadd(wordPlugin);\nadd(charPlugin);\nadd(linePlugin);\n// grid plugins\nadd(itemPlugin);\nadd(rowPlugin);\nadd(columnPlugin);\nadd(gridPlugin);\n// cell-layout plugins\nadd(layoutPlugin);\nadd(cellRowPlugin);\nadd(cellColumnPlugin);\nadd(cellPlugin);\n\nreturn Splitting;\n\n})));\n","\n\n\n\n","\n\n\n\n","import { shallowRef, watchEffect, readonly, unref, ref, isVue3, version, watch, customRef, getCurrentScope, onScopeDispose, effectScope, provide, inject, isRef, computed, reactive, toRefs as toRefs$1, toRef, isVue2, set as set$1, getCurrentInstance, onBeforeMount, nextTick, onBeforeUnmount, onMounted, onUnmounted, isReactive } from 'vue-demi';\n\nvar __defProp$b = Object.defineProperty;\nvar __defProps$8 = Object.defineProperties;\nvar __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$d = Object.getOwnPropertySymbols;\nvar __hasOwnProp$d = Object.prototype.hasOwnProperty;\nvar __propIsEnum$d = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$b = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$d.call(b, prop))\n __defNormalProp$b(a, prop, b[prop]);\n if (__getOwnPropSymbols$d)\n for (var prop of __getOwnPropSymbols$d(b)) {\n if (__propIsEnum$d.call(b, prop))\n __defNormalProp$b(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));\nfunction computedEager(fn, options) {\n var _a;\n const result = shallowRef();\n watchEffect(() => {\n result.value = fn();\n }, __spreadProps$8(__spreadValues$b({}, options), {\n flush: (_a = options == null ? void 0 : options.flush) != null ? _a : \"sync\"\n }));\n return readonly(result);\n}\n\nvar _a;\nconst isClient = typeof window !== \"undefined\";\nconst isDef = (val) => typeof val !== \"undefined\";\nconst assert = (condition, ...infos) => {\n if (!condition)\n console.warn(...infos);\n};\nconst toString = Object.prototype.toString;\nconst isBoolean = (val) => typeof val === \"boolean\";\nconst isFunction = (val) => typeof val === \"function\";\nconst isNumber = (val) => typeof val === \"number\";\nconst isString = (val) => typeof val === \"string\";\nconst isObject = (val) => toString.call(val) === \"[object Object]\";\nconst isWindow = (val) => typeof window !== \"undefined\" && toString.call(val) === \"[object Window]\";\nconst now = () => Date.now();\nconst timestamp = () => +Date.now();\nconst clamp = (n, min, max) => Math.min(max, Math.max(min, n));\nconst noop = () => {\n};\nconst rand = (min, max) => {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n};\nconst isIOS = isClient && ((_a = window == null ? void 0 : window.navigator) == null ? void 0 : _a.userAgent) && /iP(ad|hone|od)/.test(window.navigator.userAgent);\nconst hasOwn = (val, key) => Object.prototype.hasOwnProperty.call(val, key);\n\nfunction resolveUnref(r) {\n return typeof r === \"function\" ? r() : unref(r);\n}\n\nfunction createFilterWrapper(filter, fn) {\n function wrapper(...args) {\n return new Promise((resolve, reject) => {\n Promise.resolve(filter(() => fn.apply(this, args), { fn, thisArg: this, args })).then(resolve).catch(reject);\n });\n }\n return wrapper;\n}\nconst bypassFilter = (invoke) => {\n return invoke();\n};\nfunction debounceFilter(ms, options = {}) {\n let timer;\n let maxTimer;\n let lastRejector = noop;\n const _clearTimeout = (timer2) => {\n clearTimeout(timer2);\n lastRejector();\n lastRejector = noop;\n };\n const filter = (invoke) => {\n const duration = resolveUnref(ms);\n const maxDuration = resolveUnref(options.maxWait);\n if (timer)\n _clearTimeout(timer);\n if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) {\n if (maxTimer) {\n _clearTimeout(maxTimer);\n maxTimer = null;\n }\n return Promise.resolve(invoke());\n }\n return new Promise((resolve, reject) => {\n lastRejector = options.rejectOnCancel ? reject : resolve;\n if (maxDuration && !maxTimer) {\n maxTimer = setTimeout(() => {\n if (timer)\n _clearTimeout(timer);\n maxTimer = null;\n resolve(invoke());\n }, maxDuration);\n }\n timer = setTimeout(() => {\n if (maxTimer)\n _clearTimeout(maxTimer);\n maxTimer = null;\n resolve(invoke());\n }, duration);\n });\n };\n return filter;\n}\nfunction throttleFilter(ms, trailing = true, leading = true, rejectOnCancel = false) {\n let lastExec = 0;\n let timer;\n let isLeading = true;\n let lastRejector = noop;\n let lastValue;\n const clear = () => {\n if (timer) {\n clearTimeout(timer);\n timer = void 0;\n lastRejector();\n lastRejector = noop;\n }\n };\n const filter = (_invoke) => {\n const duration = resolveUnref(ms);\n const elapsed = Date.now() - lastExec;\n const invoke = () => {\n return lastValue = _invoke();\n };\n clear();\n if (duration <= 0) {\n lastExec = Date.now();\n return invoke();\n }\n if (elapsed > duration && (leading || !isLeading)) {\n lastExec = Date.now();\n invoke();\n } else if (trailing) {\n lastValue = new Promise((resolve, reject) => {\n lastRejector = rejectOnCancel ? reject : resolve;\n timer = setTimeout(() => {\n lastExec = Date.now();\n isLeading = true;\n resolve(invoke());\n clear();\n }, Math.max(0, duration - elapsed));\n });\n }\n if (!leading && !timer)\n timer = setTimeout(() => isLeading = true, duration);\n isLeading = false;\n return lastValue;\n };\n return filter;\n}\nfunction pausableFilter(extendFilter = bypassFilter) {\n const isActive = ref(true);\n function pause() {\n isActive.value = false;\n }\n function resume() {\n isActive.value = true;\n }\n const eventFilter = (...args) => {\n if (isActive.value)\n extendFilter(...args);\n };\n return { isActive: readonly(isActive), pause, resume, eventFilter };\n}\n\nfunction __onlyVue3(name = \"this function\") {\n if (isVue3)\n return;\n throw new Error(`[VueUse] ${name} is only works on Vue 3.`);\n}\nfunction __onlyVue27Plus(name = \"this function\") {\n if (isVue3 || version.startsWith(\"2.7.\"))\n return;\n throw new Error(`[VueUse] ${name} is only works on Vue 2.7 or above.`);\n}\nconst directiveHooks = {\n mounted: isVue3 ? \"mounted\" : \"inserted\",\n updated: isVue3 ? \"updated\" : \"componentUpdated\",\n unmounted: isVue3 ? \"unmounted\" : \"unbind\"\n};\n\nfunction promiseTimeout(ms, throwOnTimeout = false, reason = \"Timeout\") {\n return new Promise((resolve, reject) => {\n if (throwOnTimeout)\n setTimeout(() => reject(reason), ms);\n else\n setTimeout(resolve, ms);\n });\n}\nfunction identity(arg) {\n return arg;\n}\nfunction createSingletonPromise(fn) {\n let _promise;\n function wrapper() {\n if (!_promise)\n _promise = fn();\n return _promise;\n }\n wrapper.reset = async () => {\n const _prev = _promise;\n _promise = void 0;\n if (_prev)\n await _prev;\n };\n return wrapper;\n}\nfunction invoke(fn) {\n return fn();\n}\nfunction containsProp(obj, ...props) {\n return props.some((k) => k in obj);\n}\nfunction increaseWithUnit(target, delta) {\n var _a;\n if (typeof target === \"number\")\n return target + delta;\n const value = ((_a = target.match(/^-?[0-9]+\\.?[0-9]*/)) == null ? void 0 : _a[0]) || \"\";\n const unit = target.slice(value.length);\n const result = parseFloat(value) + delta;\n if (Number.isNaN(result))\n return target;\n return result + unit;\n}\nfunction objectPick(obj, keys, omitUndefined = false) {\n return keys.reduce((n, k) => {\n if (k in obj) {\n if (!omitUndefined || obj[k] !== void 0)\n n[k] = obj[k];\n }\n return n;\n }, {});\n}\nfunction objectEntries(obj) {\n return Object.entries(obj);\n}\n\nfunction computedWithControl(source, fn) {\n let v = void 0;\n let track;\n let trigger;\n const dirty = ref(true);\n const update = () => {\n dirty.value = true;\n trigger();\n };\n watch(source, update, { flush: \"sync\" });\n const get = isFunction(fn) ? fn : fn.get;\n const set = isFunction(fn) ? void 0 : fn.set;\n const result = customRef((_track, _trigger) => {\n track = _track;\n trigger = _trigger;\n return {\n get() {\n if (dirty.value) {\n v = get();\n dirty.value = false;\n }\n track();\n return v;\n },\n set(v2) {\n set == null ? void 0 : set(v2);\n }\n };\n });\n if (Object.isExtensible(result))\n result.trigger = update;\n return result;\n}\n\nfunction tryOnScopeDispose(fn) {\n if (getCurrentScope()) {\n onScopeDispose(fn);\n return true;\n }\n return false;\n}\n\nfunction createEventHook() {\n const fns = new Set();\n const off = (fn) => {\n fns.delete(fn);\n };\n const on = (fn) => {\n fns.add(fn);\n const offFn = () => off(fn);\n tryOnScopeDispose(offFn);\n return {\n off: offFn\n };\n };\n const trigger = (param) => {\n return Promise.all(Array.from(fns).map((fn) => fn(param)));\n };\n return {\n on,\n off,\n trigger\n };\n}\n\nfunction createGlobalState(stateFactory) {\n let initialized = false;\n let state;\n const scope = effectScope(true);\n return (...args) => {\n if (!initialized) {\n state = scope.run(() => stateFactory(...args));\n initialized = true;\n }\n return state;\n };\n}\n\nfunction createInjectionState(composable) {\n const key = Symbol(\"InjectionState\");\n const useProvidingState = (...args) => {\n const state = composable(...args);\n provide(key, state);\n return state;\n };\n const useInjectedState = () => inject(key);\n return [useProvidingState, useInjectedState];\n}\n\nfunction createSharedComposable(composable) {\n let subscribers = 0;\n let state;\n let scope;\n const dispose = () => {\n subscribers -= 1;\n if (scope && subscribers <= 0) {\n scope.stop();\n state = void 0;\n scope = void 0;\n }\n };\n return (...args) => {\n subscribers += 1;\n if (!state) {\n scope = effectScope(true);\n state = scope.run(() => composable(...args));\n }\n tryOnScopeDispose(dispose);\n return state;\n };\n}\n\nfunction extendRef(ref, extend, { enumerable = false, unwrap = true } = {}) {\n __onlyVue27Plus();\n for (const [key, value] of Object.entries(extend)) {\n if (key === \"value\")\n continue;\n if (isRef(value) && unwrap) {\n Object.defineProperty(ref, key, {\n get() {\n return value.value;\n },\n set(v) {\n value.value = v;\n },\n enumerable\n });\n } else {\n Object.defineProperty(ref, key, { value, enumerable });\n }\n }\n return ref;\n}\n\nfunction get(obj, key) {\n if (key == null)\n return unref(obj);\n return unref(obj)[key];\n}\n\nfunction isDefined(v) {\n return unref(v) != null;\n}\n\nvar __defProp$a = Object.defineProperty;\nvar __getOwnPropSymbols$c = Object.getOwnPropertySymbols;\nvar __hasOwnProp$c = Object.prototype.hasOwnProperty;\nvar __propIsEnum$c = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$a = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$c.call(b, prop))\n __defNormalProp$a(a, prop, b[prop]);\n if (__getOwnPropSymbols$c)\n for (var prop of __getOwnPropSymbols$c(b)) {\n if (__propIsEnum$c.call(b, prop))\n __defNormalProp$a(a, prop, b[prop]);\n }\n return a;\n};\nfunction makeDestructurable(obj, arr) {\n if (typeof Symbol !== \"undefined\") {\n const clone = __spreadValues$a({}, obj);\n Object.defineProperty(clone, Symbol.iterator, {\n enumerable: false,\n value() {\n let index = 0;\n return {\n next: () => ({\n value: arr[index++],\n done: index > arr.length\n })\n };\n }\n });\n return clone;\n } else {\n return Object.assign([...arr], obj);\n }\n}\n\nfunction reactify(fn, options) {\n const unrefFn = (options == null ? void 0 : options.computedGetter) === false ? unref : resolveUnref;\n return function(...args) {\n return computed(() => fn.apply(this, args.map((i) => unrefFn(i))));\n };\n}\n\nfunction reactifyObject(obj, optionsOrKeys = {}) {\n let keys = [];\n let options;\n if (Array.isArray(optionsOrKeys)) {\n keys = optionsOrKeys;\n } else {\n options = optionsOrKeys;\n const { includeOwnProperties = true } = optionsOrKeys;\n keys.push(...Object.keys(obj));\n if (includeOwnProperties)\n keys.push(...Object.getOwnPropertyNames(obj));\n }\n return Object.fromEntries(keys.map((key) => {\n const value = obj[key];\n return [\n key,\n typeof value === \"function\" ? reactify(value.bind(obj), options) : value\n ];\n }));\n}\n\nfunction toReactive(objectRef) {\n if (!isRef(objectRef))\n return reactive(objectRef);\n const proxy = new Proxy({}, {\n get(_, p, receiver) {\n return unref(Reflect.get(objectRef.value, p, receiver));\n },\n set(_, p, value) {\n if (isRef(objectRef.value[p]) && !isRef(value))\n objectRef.value[p].value = value;\n else\n objectRef.value[p] = value;\n return true;\n },\n deleteProperty(_, p) {\n return Reflect.deleteProperty(objectRef.value, p);\n },\n has(_, p) {\n return Reflect.has(objectRef.value, p);\n },\n ownKeys() {\n return Object.keys(objectRef.value);\n },\n getOwnPropertyDescriptor() {\n return {\n enumerable: true,\n configurable: true\n };\n }\n });\n return reactive(proxy);\n}\n\nfunction reactiveComputed(fn) {\n return toReactive(computed(fn));\n}\n\nfunction reactiveOmit(obj, ...keys) {\n const flatKeys = keys.flat();\n const predicate = flatKeys[0];\n return reactiveComputed(() => typeof predicate === \"function\" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k, v]) => !predicate(resolveUnref(v), k))) : Object.fromEntries(Object.entries(toRefs$1(obj)).filter((e) => !flatKeys.includes(e[0]))));\n}\n\nfunction reactivePick(obj, ...keys) {\n const flatKeys = keys.flat();\n const predicate = flatKeys[0];\n return reactiveComputed(() => typeof predicate === \"function\" ? Object.fromEntries(Object.entries(toRefs$1(obj)).filter(([k, v]) => predicate(resolveUnref(v), k))) : Object.fromEntries(flatKeys.map((k) => [k, toRef(obj, k)])));\n}\n\nfunction refAutoReset(defaultValue, afterMs = 1e4) {\n return customRef((track, trigger) => {\n let value = defaultValue;\n let timer;\n const resetAfter = () => setTimeout(() => {\n value = defaultValue;\n trigger();\n }, resolveUnref(afterMs));\n tryOnScopeDispose(() => {\n clearTimeout(timer);\n });\n return {\n get() {\n track();\n return value;\n },\n set(newValue) {\n value = newValue;\n trigger();\n clearTimeout(timer);\n timer = resetAfter();\n }\n };\n });\n}\n\nfunction useDebounceFn(fn, ms = 200, options = {}) {\n return createFilterWrapper(debounceFilter(ms, options), fn);\n}\n\nfunction refDebounced(value, ms = 200, options = {}) {\n const debounced = ref(value.value);\n const updater = useDebounceFn(() => {\n debounced.value = value.value;\n }, ms, options);\n watch(value, () => updater());\n return debounced;\n}\n\nfunction refDefault(source, defaultValue) {\n return computed({\n get() {\n var _a;\n return (_a = source.value) != null ? _a : defaultValue;\n },\n set(value) {\n source.value = value;\n }\n });\n}\n\nfunction useThrottleFn(fn, ms = 200, trailing = false, leading = true, rejectOnCancel = false) {\n return createFilterWrapper(throttleFilter(ms, trailing, leading, rejectOnCancel), fn);\n}\n\nfunction refThrottled(value, delay = 200, trailing = true, leading = true) {\n if (delay <= 0)\n return value;\n const throttled = ref(value.value);\n const updater = useThrottleFn(() => {\n throttled.value = value.value;\n }, delay, trailing, leading);\n watch(value, () => updater());\n return throttled;\n}\n\nfunction refWithControl(initial, options = {}) {\n let source = initial;\n let track;\n let trigger;\n const ref = customRef((_track, _trigger) => {\n track = _track;\n trigger = _trigger;\n return {\n get() {\n return get();\n },\n set(v) {\n set(v);\n }\n };\n });\n function get(tracking = true) {\n if (tracking)\n track();\n return source;\n }\n function set(value, triggering = true) {\n var _a, _b;\n if (value === source)\n return;\n const old = source;\n if (((_a = options.onBeforeChange) == null ? void 0 : _a.call(options, value, old)) === false)\n return;\n source = value;\n (_b = options.onChanged) == null ? void 0 : _b.call(options, value, old);\n if (triggering)\n trigger();\n }\n const untrackedGet = () => get(false);\n const silentSet = (v) => set(v, false);\n const peek = () => get(false);\n const lay = (v) => set(v, false);\n return extendRef(ref, {\n get,\n set,\n untrackedGet,\n silentSet,\n peek,\n lay\n }, { enumerable: true });\n}\nconst controlledRef = refWithControl;\n\nfunction resolveRef(r) {\n return typeof r === \"function\" ? computed(r) : ref(r);\n}\n\nfunction set(...args) {\n if (args.length === 2) {\n const [ref, value] = args;\n ref.value = value;\n }\n if (args.length === 3) {\n if (isVue2) {\n set$1(...args);\n } else {\n const [target, key, value] = args;\n target[key] = value;\n }\n }\n}\n\nfunction syncRef(left, right, options = {}) {\n var _a, _b;\n const {\n flush = \"sync\",\n deep = false,\n immediate = true,\n direction = \"both\",\n transform = {}\n } = options;\n let watchLeft;\n let watchRight;\n const transformLTR = (_a = transform.ltr) != null ? _a : (v) => v;\n const transformRTL = (_b = transform.rtl) != null ? _b : (v) => v;\n if (direction === \"both\" || direction === \"ltr\") {\n watchLeft = watch(left, (newValue) => right.value = transformLTR(newValue), { flush, deep, immediate });\n }\n if (direction === \"both\" || direction === \"rtl\") {\n watchRight = watch(right, (newValue) => left.value = transformRTL(newValue), { flush, deep, immediate });\n }\n return () => {\n watchLeft == null ? void 0 : watchLeft();\n watchRight == null ? void 0 : watchRight();\n };\n}\n\nfunction syncRefs(source, targets, options = {}) {\n const {\n flush = \"sync\",\n deep = false,\n immediate = true\n } = options;\n if (!Array.isArray(targets))\n targets = [targets];\n return watch(source, (newValue) => targets.forEach((target) => target.value = newValue), { flush, deep, immediate });\n}\n\nvar __defProp$9 = Object.defineProperty;\nvar __defProps$7 = Object.defineProperties;\nvar __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$b = Object.getOwnPropertySymbols;\nvar __hasOwnProp$b = Object.prototype.hasOwnProperty;\nvar __propIsEnum$b = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$9 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$b.call(b, prop))\n __defNormalProp$9(a, prop, b[prop]);\n if (__getOwnPropSymbols$b)\n for (var prop of __getOwnPropSymbols$b(b)) {\n if (__propIsEnum$b.call(b, prop))\n __defNormalProp$9(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));\nfunction toRefs(objectRef) {\n if (!isRef(objectRef))\n return toRefs$1(objectRef);\n const result = Array.isArray(objectRef.value) ? new Array(objectRef.value.length) : {};\n for (const key in objectRef.value) {\n result[key] = customRef(() => ({\n get() {\n return objectRef.value[key];\n },\n set(v) {\n if (Array.isArray(objectRef.value)) {\n const copy = [...objectRef.value];\n copy[key] = v;\n objectRef.value = copy;\n } else {\n const newObject = __spreadProps$7(__spreadValues$9({}, objectRef.value), { [key]: v });\n Object.setPrototypeOf(newObject, objectRef.value);\n objectRef.value = newObject;\n }\n }\n }));\n }\n return result;\n}\n\nfunction tryOnBeforeMount(fn, sync = true) {\n if (getCurrentInstance())\n onBeforeMount(fn);\n else if (sync)\n fn();\n else\n nextTick(fn);\n}\n\nfunction tryOnBeforeUnmount(fn) {\n if (getCurrentInstance())\n onBeforeUnmount(fn);\n}\n\nfunction tryOnMounted(fn, sync = true) {\n if (getCurrentInstance())\n onMounted(fn);\n else if (sync)\n fn();\n else\n nextTick(fn);\n}\n\nfunction tryOnUnmounted(fn) {\n if (getCurrentInstance())\n onUnmounted(fn);\n}\n\nfunction createUntil(r, isNot = false) {\n function toMatch(condition, { flush = \"sync\", deep = false, timeout, throwOnTimeout } = {}) {\n let stop = null;\n const watcher = new Promise((resolve) => {\n stop = watch(r, (v) => {\n if (condition(v) !== isNot) {\n stop == null ? void 0 : stop();\n resolve(v);\n }\n }, {\n flush,\n deep,\n immediate: true\n });\n });\n const promises = [watcher];\n if (timeout != null) {\n promises.push(promiseTimeout(timeout, throwOnTimeout).then(() => resolveUnref(r)).finally(() => stop == null ? void 0 : stop()));\n }\n return Promise.race(promises);\n }\n function toBe(value, options) {\n if (!isRef(value))\n return toMatch((v) => v === value, options);\n const { flush = \"sync\", deep = false, timeout, throwOnTimeout } = options != null ? options : {};\n let stop = null;\n const watcher = new Promise((resolve) => {\n stop = watch([r, value], ([v1, v2]) => {\n if (isNot !== (v1 === v2)) {\n stop == null ? void 0 : stop();\n resolve(v1);\n }\n }, {\n flush,\n deep,\n immediate: true\n });\n });\n const promises = [watcher];\n if (timeout != null) {\n promises.push(promiseTimeout(timeout, throwOnTimeout).then(() => resolveUnref(r)).finally(() => {\n stop == null ? void 0 : stop();\n return resolveUnref(r);\n }));\n }\n return Promise.race(promises);\n }\n function toBeTruthy(options) {\n return toMatch((v) => Boolean(v), options);\n }\n function toBeNull(options) {\n return toBe(null, options);\n }\n function toBeUndefined(options) {\n return toBe(void 0, options);\n }\n function toBeNaN(options) {\n return toMatch(Number.isNaN, options);\n }\n function toContains(value, options) {\n return toMatch((v) => {\n const array = Array.from(v);\n return array.includes(value) || array.includes(resolveUnref(value));\n }, options);\n }\n function changed(options) {\n return changedTimes(1, options);\n }\n function changedTimes(n = 1, options) {\n let count = -1;\n return toMatch(() => {\n count += 1;\n return count >= n;\n }, options);\n }\n if (Array.isArray(resolveUnref(r))) {\n const instance = {\n toMatch,\n toContains,\n changed,\n changedTimes,\n get not() {\n return createUntil(r, !isNot);\n }\n };\n return instance;\n } else {\n const instance = {\n toMatch,\n toBe,\n toBeTruthy,\n toBeNull,\n toBeNaN,\n toBeUndefined,\n changed,\n changedTimes,\n get not() {\n return createUntil(r, !isNot);\n }\n };\n return instance;\n }\n}\nfunction until(r) {\n return createUntil(r);\n}\n\nconst defaultComparator = (value, othVal) => value === othVal;\nfunction useArrayDifference(...args) {\n var _a;\n const list = args[0];\n const values = args[1];\n let compareFn = (_a = args[2]) != null ? _a : defaultComparator;\n if (isString(compareFn)) {\n const key = compareFn;\n compareFn = (value, othVal) => value[key] === othVal[key];\n }\n return computed(() => resolveUnref(list).filter((x) => resolveUnref(values).findIndex((y) => compareFn(x, y)) === -1));\n}\n\nfunction useArrayEvery(list, fn) {\n return computed(() => resolveUnref(list).every((element, index, array) => fn(resolveUnref(element), index, array)));\n}\n\nfunction useArrayFilter(list, fn) {\n return computed(() => resolveUnref(list).map((i) => resolveUnref(i)).filter(fn));\n}\n\nfunction useArrayFind(list, fn) {\n return computed(() => resolveUnref(resolveUnref(list).find((element, index, array) => fn(resolveUnref(element), index, array))));\n}\n\nfunction useArrayFindIndex(list, fn) {\n return computed(() => resolveUnref(list).findIndex((element, index, array) => fn(resolveUnref(element), index, array)));\n}\n\nfunction findLast(arr, cb) {\n let index = arr.length;\n while (index-- > 0) {\n if (cb(arr[index], index, arr))\n return arr[index];\n }\n return void 0;\n}\nfunction useArrayFindLast(list, fn) {\n return computed(() => resolveUnref(!Array.prototype.findLast ? findLast(resolveUnref(list), (element, index, array) => fn(resolveUnref(element), index, array)) : resolveUnref(list).findLast((element, index, array) => fn(resolveUnref(element), index, array))));\n}\n\nfunction isArrayIncludesOptions(obj) {\n return isObject(obj) && containsProp(obj, \"formIndex\", \"comparator\");\n}\nfunction useArrayIncludes(...args) {\n var _a;\n const list = args[0];\n const value = args[1];\n let comparator = args[2];\n let formIndex = 0;\n if (isArrayIncludesOptions(comparator)) {\n formIndex = (_a = comparator.fromIndex) != null ? _a : 0;\n comparator = comparator.comparator;\n }\n if (typeof comparator === \"string\") {\n const key = comparator;\n comparator = (element, value2) => element[key] === resolveUnref(value2);\n }\n comparator = comparator != null ? comparator : (element, value2) => element === resolveUnref(value2);\n return computed(() => resolveUnref(list).slice(formIndex).some((element, index, array) => comparator(resolveUnref(element), resolveUnref(value), index, resolveUnref(array))));\n}\n\nfunction useArrayJoin(list, separator) {\n return computed(() => resolveUnref(list).map((i) => resolveUnref(i)).join(resolveUnref(separator)));\n}\n\nfunction useArrayMap(list, fn) {\n return computed(() => resolveUnref(list).map((i) => resolveUnref(i)).map(fn));\n}\n\nfunction useArrayReduce(list, reducer, ...args) {\n const reduceCallback = (sum, value, index) => reducer(resolveUnref(sum), resolveUnref(value), index);\n return computed(() => {\n const resolved = resolveUnref(list);\n return args.length ? resolved.reduce(reduceCallback, resolveUnref(args[0])) : resolved.reduce(reduceCallback);\n });\n}\n\nfunction useArraySome(list, fn) {\n return computed(() => resolveUnref(list).some((element, index, array) => fn(resolveUnref(element), index, array)));\n}\n\nfunction uniq(array) {\n return Array.from(new Set(array));\n}\nfunction uniqueElementsBy(array, fn) {\n return array.reduce((acc, v) => {\n if (!acc.some((x) => fn(v, x, array)))\n acc.push(v);\n return acc;\n }, []);\n}\nfunction useArrayUnique(list, compareFn) {\n return computed(() => {\n const resolvedList = resolveUnref(list).map((element) => resolveUnref(element));\n return compareFn ? uniqueElementsBy(resolvedList, compareFn) : uniq(resolvedList);\n });\n}\n\nfunction useCounter(initialValue = 0, options = {}) {\n const count = ref(initialValue);\n const {\n max = Infinity,\n min = -Infinity\n } = options;\n const inc = (delta = 1) => count.value = Math.min(max, count.value + delta);\n const dec = (delta = 1) => count.value = Math.max(min, count.value - delta);\n const get = () => count.value;\n const set = (val) => count.value = Math.max(min, Math.min(max, val));\n const reset = (val = initialValue) => {\n initialValue = val;\n return set(val);\n };\n return { count, inc, dec, get, set, reset };\n}\n\nconst REGEX_PARSE = /^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/;\nconst REGEX_FORMAT = /\\[([^\\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a{1,2}|A{1,2}|m{1,2}|s{1,2}|Z{1,2}|SSS/g;\nconst defaultMeridiem = (hours, minutes, isLowercase, hasPeriod) => {\n let m = hours < 12 ? \"AM\" : \"PM\";\n if (hasPeriod)\n m = m.split(\"\").reduce((acc, curr) => acc += `${curr}.`, \"\");\n return isLowercase ? m.toLowerCase() : m;\n};\nconst formatDate = (date, formatStr, options = {}) => {\n var _a;\n const years = date.getFullYear();\n const month = date.getMonth();\n const days = date.getDate();\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const seconds = date.getSeconds();\n const milliseconds = date.getMilliseconds();\n const day = date.getDay();\n const meridiem = (_a = options.customMeridiem) != null ? _a : defaultMeridiem;\n const matches = {\n YY: () => String(years).slice(-2),\n YYYY: () => years,\n M: () => month + 1,\n MM: () => `${month + 1}`.padStart(2, \"0\"),\n MMM: () => date.toLocaleDateString(options.locales, { month: \"short\" }),\n MMMM: () => date.toLocaleDateString(options.locales, { month: \"long\" }),\n D: () => String(days),\n DD: () => `${days}`.padStart(2, \"0\"),\n H: () => String(hours),\n HH: () => `${hours}`.padStart(2, \"0\"),\n h: () => `${hours % 12 || 12}`.padStart(1, \"0\"),\n hh: () => `${hours % 12 || 12}`.padStart(2, \"0\"),\n m: () => String(minutes),\n mm: () => `${minutes}`.padStart(2, \"0\"),\n s: () => String(seconds),\n ss: () => `${seconds}`.padStart(2, \"0\"),\n SSS: () => `${milliseconds}`.padStart(3, \"0\"),\n d: () => day,\n dd: () => date.toLocaleDateString(options.locales, { weekday: \"narrow\" }),\n ddd: () => date.toLocaleDateString(options.locales, { weekday: \"short\" }),\n dddd: () => date.toLocaleDateString(options.locales, { weekday: \"long\" }),\n A: () => meridiem(hours, minutes),\n AA: () => meridiem(hours, minutes, false, true),\n a: () => meridiem(hours, minutes, true),\n aa: () => meridiem(hours, minutes, true, true)\n };\n return formatStr.replace(REGEX_FORMAT, (match, $1) => $1 || matches[match]());\n};\nconst normalizeDate = (date) => {\n if (date === null)\n return new Date(NaN);\n if (date === void 0)\n return new Date();\n if (date instanceof Date)\n return new Date(date);\n if (typeof date === \"string\" && !/Z$/i.test(date)) {\n const d = date.match(REGEX_PARSE);\n if (d) {\n const m = d[2] - 1 || 0;\n const ms = (d[7] || \"0\").substring(0, 3);\n return new Date(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms);\n }\n }\n return new Date(date);\n};\nfunction useDateFormat(date, formatStr = \"HH:mm:ss\", options = {}) {\n return computed(() => formatDate(normalizeDate(resolveUnref(date)), resolveUnref(formatStr), options));\n}\n\nfunction useIntervalFn(cb, interval = 1e3, options = {}) {\n const {\n immediate = true,\n immediateCallback = false\n } = options;\n let timer = null;\n const isActive = ref(false);\n function clean() {\n if (timer) {\n clearInterval(timer);\n timer = null;\n }\n }\n function pause() {\n isActive.value = false;\n clean();\n }\n function resume() {\n const intervalValue = resolveUnref(interval);\n if (intervalValue <= 0)\n return;\n isActive.value = true;\n if (immediateCallback)\n cb();\n clean();\n timer = setInterval(cb, intervalValue);\n }\n if (immediate && isClient)\n resume();\n if (isRef(interval) || isFunction(interval)) {\n const stopWatch = watch(interval, () => {\n if (isActive.value && isClient)\n resume();\n });\n tryOnScopeDispose(stopWatch);\n }\n tryOnScopeDispose(pause);\n return {\n isActive,\n pause,\n resume\n };\n}\n\nvar __defProp$8 = Object.defineProperty;\nvar __getOwnPropSymbols$a = Object.getOwnPropertySymbols;\nvar __hasOwnProp$a = Object.prototype.hasOwnProperty;\nvar __propIsEnum$a = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$8 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$a.call(b, prop))\n __defNormalProp$8(a, prop, b[prop]);\n if (__getOwnPropSymbols$a)\n for (var prop of __getOwnPropSymbols$a(b)) {\n if (__propIsEnum$a.call(b, prop))\n __defNormalProp$8(a, prop, b[prop]);\n }\n return a;\n};\nfunction useInterval(interval = 1e3, options = {}) {\n const {\n controls: exposeControls = false,\n immediate = true,\n callback\n } = options;\n const counter = ref(0);\n const update = () => counter.value += 1;\n const reset = () => {\n counter.value = 0;\n };\n const controls = useIntervalFn(callback ? () => {\n update();\n callback(counter.value);\n } : update, interval, { immediate });\n if (exposeControls) {\n return __spreadValues$8({\n counter,\n reset\n }, controls);\n } else {\n return counter;\n }\n}\n\nfunction useLastChanged(source, options = {}) {\n var _a;\n const ms = ref((_a = options.initialValue) != null ? _a : null);\n watch(source, () => ms.value = timestamp(), options);\n return ms;\n}\n\nfunction useTimeoutFn(cb, interval, options = {}) {\n const {\n immediate = true\n } = options;\n const isPending = ref(false);\n let timer = null;\n function clear() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n }\n function stop() {\n isPending.value = false;\n clear();\n }\n function start(...args) {\n clear();\n isPending.value = true;\n timer = setTimeout(() => {\n isPending.value = false;\n timer = null;\n cb(...args);\n }, resolveUnref(interval));\n }\n if (immediate) {\n isPending.value = true;\n if (isClient)\n start();\n }\n tryOnScopeDispose(stop);\n return {\n isPending: readonly(isPending),\n start,\n stop\n };\n}\n\nvar __defProp$7 = Object.defineProperty;\nvar __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$9 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$9 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$7 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$9.call(b, prop))\n __defNormalProp$7(a, prop, b[prop]);\n if (__getOwnPropSymbols$9)\n for (var prop of __getOwnPropSymbols$9(b)) {\n if (__propIsEnum$9.call(b, prop))\n __defNormalProp$7(a, prop, b[prop]);\n }\n return a;\n};\nfunction useTimeout(interval = 1e3, options = {}) {\n const {\n controls: exposeControls = false,\n callback\n } = options;\n const controls = useTimeoutFn(callback != null ? callback : noop, interval, options);\n const ready = computed(() => !controls.isPending.value);\n if (exposeControls) {\n return __spreadValues$7({\n ready\n }, controls);\n } else {\n return ready;\n }\n}\n\nfunction useToNumber(value, options = {}) {\n const {\n method = \"parseFloat\",\n radix,\n nanToZero\n } = options;\n return computed(() => {\n let resolved = resolveUnref(value);\n if (typeof resolved === \"string\")\n resolved = Number[method](resolved, radix);\n if (nanToZero && isNaN(resolved))\n resolved = 0;\n return resolved;\n });\n}\n\nfunction useToString(value) {\n return computed(() => `${resolveUnref(value)}`);\n}\n\nfunction useToggle(initialValue = false, options = {}) {\n const {\n truthyValue = true,\n falsyValue = false\n } = options;\n const valueIsRef = isRef(initialValue);\n const _value = ref(initialValue);\n function toggle(value) {\n if (arguments.length) {\n _value.value = value;\n return _value.value;\n } else {\n const truthy = resolveUnref(truthyValue);\n _value.value = _value.value === truthy ? resolveUnref(falsyValue) : truthy;\n return _value.value;\n }\n }\n if (valueIsRef)\n return toggle;\n else\n return [_value, toggle];\n}\n\nfunction watchArray(source, cb, options) {\n let oldList = (options == null ? void 0 : options.immediate) ? [] : [\n ...source instanceof Function ? source() : Array.isArray(source) ? source : unref(source)\n ];\n return watch(source, (newList, _, onCleanup) => {\n const oldListRemains = new Array(oldList.length);\n const added = [];\n for (const obj of newList) {\n let found = false;\n for (let i = 0; i < oldList.length; i++) {\n if (!oldListRemains[i] && obj === oldList[i]) {\n oldListRemains[i] = true;\n found = true;\n break;\n }\n }\n if (!found)\n added.push(obj);\n }\n const removed = oldList.filter((_2, i) => !oldListRemains[i]);\n cb(newList, oldList, added, removed, onCleanup);\n oldList = [...newList];\n }, options);\n}\n\nvar __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$8 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$8 = Object.prototype.propertyIsEnumerable;\nvar __objRest$5 = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$8.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$8)\n for (var prop of __getOwnPropSymbols$8(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$8.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction watchWithFilter(source, cb, options = {}) {\n const _a = options, {\n eventFilter = bypassFilter\n } = _a, watchOptions = __objRest$5(_a, [\n \"eventFilter\"\n ]);\n return watch(source, createFilterWrapper(eventFilter, cb), watchOptions);\n}\n\nvar __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$7 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$7 = Object.prototype.propertyIsEnumerable;\nvar __objRest$4 = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$7.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$7)\n for (var prop of __getOwnPropSymbols$7(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$7.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction watchAtMost(source, cb, options) {\n const _a = options, {\n count\n } = _a, watchOptions = __objRest$4(_a, [\n \"count\"\n ]);\n const current = ref(0);\n const stop = watchWithFilter(source, (...args) => {\n current.value += 1;\n if (current.value >= resolveUnref(count))\n nextTick(() => stop());\n cb(...args);\n }, watchOptions);\n return { count: current, stop };\n}\n\nvar __defProp$6 = Object.defineProperty;\nvar __defProps$6 = Object.defineProperties;\nvar __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$6 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$6 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$6 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$6.call(b, prop))\n __defNormalProp$6(a, prop, b[prop]);\n if (__getOwnPropSymbols$6)\n for (var prop of __getOwnPropSymbols$6(b)) {\n if (__propIsEnum$6.call(b, prop))\n __defNormalProp$6(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));\nvar __objRest$3 = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$6.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$6)\n for (var prop of __getOwnPropSymbols$6(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$6.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction watchDebounced(source, cb, options = {}) {\n const _a = options, {\n debounce = 0,\n maxWait = void 0\n } = _a, watchOptions = __objRest$3(_a, [\n \"debounce\",\n \"maxWait\"\n ]);\n return watchWithFilter(source, cb, __spreadProps$6(__spreadValues$6({}, watchOptions), {\n eventFilter: debounceFilter(debounce, { maxWait })\n }));\n}\n\nvar __defProp$5 = Object.defineProperty;\nvar __defProps$5 = Object.defineProperties;\nvar __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$5 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$5 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$5 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$5.call(b, prop))\n __defNormalProp$5(a, prop, b[prop]);\n if (__getOwnPropSymbols$5)\n for (var prop of __getOwnPropSymbols$5(b)) {\n if (__propIsEnum$5.call(b, prop))\n __defNormalProp$5(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));\nfunction watchDeep(source, cb, options) {\n return watch(source, (v, ov, onInvalidate) => {\n if (v)\n cb(v, ov, onInvalidate);\n }, __spreadProps$5(__spreadValues$5({}, options), {\n deep: true\n }));\n}\n\nvar __defProp$4 = Object.defineProperty;\nvar __defProps$4 = Object.defineProperties;\nvar __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$4 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$4 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$4 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$4.call(b, prop))\n __defNormalProp$4(a, prop, b[prop]);\n if (__getOwnPropSymbols$4)\n for (var prop of __getOwnPropSymbols$4(b)) {\n if (__propIsEnum$4.call(b, prop))\n __defNormalProp$4(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));\nvar __objRest$2 = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$4.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$4)\n for (var prop of __getOwnPropSymbols$4(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$4.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction watchIgnorable(source, cb, options = {}) {\n const _a = options, {\n eventFilter = bypassFilter\n } = _a, watchOptions = __objRest$2(_a, [\n \"eventFilter\"\n ]);\n const filteredCb = createFilterWrapper(eventFilter, cb);\n let ignoreUpdates;\n let ignorePrevAsyncUpdates;\n let stop;\n if (watchOptions.flush === \"sync\") {\n const ignore = ref(false);\n ignorePrevAsyncUpdates = () => {\n };\n ignoreUpdates = (updater) => {\n ignore.value = true;\n updater();\n ignore.value = false;\n };\n stop = watch(source, (...args) => {\n if (!ignore.value)\n filteredCb(...args);\n }, watchOptions);\n } else {\n const disposables = [];\n const ignoreCounter = ref(0);\n const syncCounter = ref(0);\n ignorePrevAsyncUpdates = () => {\n ignoreCounter.value = syncCounter.value;\n };\n disposables.push(watch(source, () => {\n syncCounter.value++;\n }, __spreadProps$4(__spreadValues$4({}, watchOptions), { flush: \"sync\" })));\n ignoreUpdates = (updater) => {\n const syncCounterPrev = syncCounter.value;\n updater();\n ignoreCounter.value += syncCounter.value - syncCounterPrev;\n };\n disposables.push(watch(source, (...args) => {\n const ignore = ignoreCounter.value > 0 && ignoreCounter.value === syncCounter.value;\n ignoreCounter.value = 0;\n syncCounter.value = 0;\n if (ignore)\n return;\n filteredCb(...args);\n }, watchOptions));\n stop = () => {\n disposables.forEach((fn) => fn());\n };\n }\n return { stop, ignoreUpdates, ignorePrevAsyncUpdates };\n}\n\nvar __defProp$3 = Object.defineProperty;\nvar __defProps$3 = Object.defineProperties;\nvar __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$3 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$3 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$3 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$3.call(b, prop))\n __defNormalProp$3(a, prop, b[prop]);\n if (__getOwnPropSymbols$3)\n for (var prop of __getOwnPropSymbols$3(b)) {\n if (__propIsEnum$3.call(b, prop))\n __defNormalProp$3(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));\nfunction watchImmediate(source, cb, options) {\n return watch(source, (v, ov, onInvalidate) => {\n if (v)\n cb(v, ov, onInvalidate);\n }, __spreadProps$3(__spreadValues$3({}, options), {\n immediate: true\n }));\n}\n\nfunction watchOnce(source, cb, options) {\n const stop = watch(source, (...args) => {\n nextTick(() => stop());\n return cb(...args);\n }, options);\n}\n\nvar __defProp$2 = Object.defineProperty;\nvar __defProps$2 = Object.defineProperties;\nvar __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$2 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$2 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$2 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$2.call(b, prop))\n __defNormalProp$2(a, prop, b[prop]);\n if (__getOwnPropSymbols$2)\n for (var prop of __getOwnPropSymbols$2(b)) {\n if (__propIsEnum$2.call(b, prop))\n __defNormalProp$2(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));\nvar __objRest$1 = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$2)\n for (var prop of __getOwnPropSymbols$2(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction watchPausable(source, cb, options = {}) {\n const _a = options, {\n eventFilter: filter\n } = _a, watchOptions = __objRest$1(_a, [\n \"eventFilter\"\n ]);\n const { eventFilter, pause, resume, isActive } = pausableFilter(filter);\n const stop = watchWithFilter(source, cb, __spreadProps$2(__spreadValues$2({}, watchOptions), {\n eventFilter\n }));\n return { stop, pause, resume, isActive };\n}\n\nvar __defProp$1 = Object.defineProperty;\nvar __defProps$1 = Object.defineProperties;\nvar __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$1 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$1 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$1 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$1.call(b, prop))\n __defNormalProp$1(a, prop, b[prop]);\n if (__getOwnPropSymbols$1)\n for (var prop of __getOwnPropSymbols$1(b)) {\n if (__propIsEnum$1.call(b, prop))\n __defNormalProp$1(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));\nvar __objRest = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$1)\n for (var prop of __getOwnPropSymbols$1(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction watchThrottled(source, cb, options = {}) {\n const _a = options, {\n throttle = 0,\n trailing = true,\n leading = true\n } = _a, watchOptions = __objRest(_a, [\n \"throttle\",\n \"trailing\",\n \"leading\"\n ]);\n return watchWithFilter(source, cb, __spreadProps$1(__spreadValues$1({}, watchOptions), {\n eventFilter: throttleFilter(throttle, trailing, leading)\n }));\n}\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nfunction watchTriggerable(source, cb, options = {}) {\n let cleanupFn;\n function onEffect() {\n if (!cleanupFn)\n return;\n const fn = cleanupFn;\n cleanupFn = void 0;\n fn();\n }\n function onCleanup(callback) {\n cleanupFn = callback;\n }\n const _cb = (value, oldValue) => {\n onEffect();\n return cb(value, oldValue, onCleanup);\n };\n const res = watchIgnorable(source, _cb, options);\n const { ignoreUpdates } = res;\n const trigger = () => {\n let res2;\n ignoreUpdates(() => {\n res2 = _cb(getWatchSources(source), getOldValue(source));\n });\n return res2;\n };\n return __spreadProps(__spreadValues({}, res), {\n trigger\n });\n}\nfunction getWatchSources(sources) {\n if (isReactive(sources))\n return sources;\n if (Array.isArray(sources))\n return sources.map((item) => getOneWatchSource(item));\n return getOneWatchSource(sources);\n}\nfunction getOneWatchSource(source) {\n return typeof source === \"function\" ? source() : unref(source);\n}\nfunction getOldValue(source) {\n return Array.isArray(source) ? source.map(() => void 0) : void 0;\n}\n\nfunction whenever(source, cb, options) {\n return watch(source, (v, ov, onInvalidate) => {\n if (v)\n cb(v, ov, onInvalidate);\n }, options);\n}\n\nexport { __onlyVue27Plus, __onlyVue3, assert, refAutoReset as autoResetRef, bypassFilter, clamp, computedEager, computedWithControl, containsProp, computedWithControl as controlledComputed, controlledRef, createEventHook, createFilterWrapper, createGlobalState, createInjectionState, reactify as createReactiveFn, createSharedComposable, createSingletonPromise, debounceFilter, refDebounced as debouncedRef, watchDebounced as debouncedWatch, directiveHooks, computedEager as eagerComputed, extendRef, formatDate, get, hasOwn, identity, watchIgnorable as ignorableWatch, increaseWithUnit, invoke, isBoolean, isClient, isDef, isDefined, isFunction, isIOS, isNumber, isObject, isString, isWindow, makeDestructurable, noop, normalizeDate, now, objectEntries, objectPick, pausableFilter, watchPausable as pausableWatch, promiseTimeout, rand, reactify, reactifyObject, reactiveComputed, reactiveOmit, reactivePick, refAutoReset, refDebounced, refDefault, refThrottled, refWithControl, resolveRef, resolveUnref, set, syncRef, syncRefs, throttleFilter, refThrottled as throttledRef, watchThrottled as throttledWatch, timestamp, toReactive, toRefs, tryOnBeforeMount, tryOnBeforeUnmount, tryOnMounted, tryOnScopeDispose, tryOnUnmounted, until, useArrayDifference, useArrayEvery, useArrayFilter, useArrayFind, useArrayFindIndex, useArrayFindLast, useArrayIncludes, useArrayJoin, useArrayMap, useArrayReduce, useArraySome, useArrayUnique, useCounter, useDateFormat, refDebounced as useDebounce, useDebounceFn, useInterval, useIntervalFn, useLastChanged, refThrottled as useThrottle, useThrottleFn, useTimeout, useTimeoutFn, useToNumber, useToString, useToggle, watchArray, watchAtMost, watchDebounced, watchDeep, watchIgnorable, watchImmediate, watchOnce, watchPausable, watchThrottled, watchTriggerable, watchWithFilter, whenever };\n","import { noop, resolveUnref, isClient, isString, tryOnScopeDispose, isIOS, tryOnMounted, computedWithControl, promiseTimeout, isFunction, resolveRef, increaseWithUnit, objectEntries, useTimeoutFn, pausableWatch, createEventHook, timestamp, pausableFilter, watchIgnorable, debounceFilter, createFilterWrapper, bypassFilter, createSingletonPromise, toRefs, containsProp, until, hasOwn, throttleFilter, useDebounceFn, useThrottleFn, isObject, isNumber, useIntervalFn, clamp, syncRef, objectPick, tryOnUnmounted, watchWithFilter, identity, isDef } from '@vueuse/shared';\nexport * from '@vueuse/shared';\nimport { isRef, ref, shallowRef, watchEffect, computed, inject, unref, watch, getCurrentInstance, customRef, onUpdated, reactive, onMounted, nextTick, markRaw, readonly, getCurrentScope, isVue2, set, del, isReadonly, onBeforeUpdate } from 'vue-demi';\nimport { useMutationObserver as useMutationObserver$1 } from '@vueuse/core';\n\nfunction computedAsync(evaluationCallback, initialState, optionsOrRef) {\n let options;\n if (isRef(optionsOrRef)) {\n options = {\n evaluating: optionsOrRef\n };\n } else {\n options = optionsOrRef || {};\n }\n const {\n lazy = false,\n evaluating = void 0,\n shallow = true,\n onError = noop\n } = options;\n const started = ref(!lazy);\n const current = shallow ? shallowRef(initialState) : ref(initialState);\n let counter = 0;\n watchEffect(async (onInvalidate) => {\n if (!started.value)\n return;\n counter++;\n const counterAtBeginning = counter;\n let hasFinished = false;\n if (evaluating) {\n Promise.resolve().then(() => {\n evaluating.value = true;\n });\n }\n try {\n const result = await evaluationCallback((cancelCallback) => {\n onInvalidate(() => {\n if (evaluating)\n evaluating.value = false;\n if (!hasFinished)\n cancelCallback();\n });\n });\n if (counterAtBeginning === counter)\n current.value = result;\n } catch (e) {\n onError(e);\n } finally {\n if (evaluating && counterAtBeginning === counter)\n evaluating.value = false;\n hasFinished = true;\n }\n });\n if (lazy) {\n return computed(() => {\n started.value = true;\n return current.value;\n });\n } else {\n return current;\n }\n}\n\nfunction computedInject(key, options, defaultSource, treatDefaultAsFactory) {\n let source = inject(key);\n if (defaultSource)\n source = inject(key, defaultSource);\n if (treatDefaultAsFactory)\n source = inject(key, defaultSource, treatDefaultAsFactory);\n if (typeof options === \"function\") {\n return computed((ctx) => options(source, ctx));\n } else {\n return computed({\n get: (ctx) => options.get(source, ctx),\n set: options.set\n });\n }\n}\n\nconst createUnrefFn = (fn) => {\n return function(...args) {\n return fn.apply(this, args.map((i) => unref(i)));\n };\n};\n\nfunction unrefElement(elRef) {\n var _a;\n const plain = resolveUnref(elRef);\n return (_a = plain == null ? void 0 : plain.$el) != null ? _a : plain;\n}\n\nconst defaultWindow = isClient ? window : void 0;\nconst defaultDocument = isClient ? window.document : void 0;\nconst defaultNavigator = isClient ? window.navigator : void 0;\nconst defaultLocation = isClient ? window.location : void 0;\n\nfunction useEventListener(...args) {\n let target;\n let events;\n let listeners;\n let options;\n if (isString(args[0]) || Array.isArray(args[0])) {\n [events, listeners, options] = args;\n target = defaultWindow;\n } else {\n [target, events, listeners, options] = args;\n }\n if (!target)\n return noop;\n if (!Array.isArray(events))\n events = [events];\n if (!Array.isArray(listeners))\n listeners = [listeners];\n const cleanups = [];\n const cleanup = () => {\n cleanups.forEach((fn) => fn());\n cleanups.length = 0;\n };\n const register = (el, event, listener, options2) => {\n el.addEventListener(event, listener, options2);\n return () => el.removeEventListener(event, listener, options2);\n };\n const stopWatch = watch(() => [unrefElement(target), resolveUnref(options)], ([el, options2]) => {\n cleanup();\n if (!el)\n return;\n cleanups.push(...events.flatMap((event) => {\n return listeners.map((listener) => register(el, event, listener, options2));\n }));\n }, { immediate: true, flush: \"post\" });\n const stop = () => {\n stopWatch();\n cleanup();\n };\n tryOnScopeDispose(stop);\n return stop;\n}\n\nlet _iOSWorkaround = false;\nfunction onClickOutside(target, handler, options = {}) {\n const { window = defaultWindow, ignore = [], capture = true, detectIframe = false } = options;\n if (!window)\n return;\n if (isIOS && !_iOSWorkaround) {\n _iOSWorkaround = true;\n Array.from(window.document.body.children).forEach((el) => el.addEventListener(\"click\", noop));\n }\n let shouldListen = true;\n const shouldIgnore = (event) => {\n return ignore.some((target2) => {\n if (typeof target2 === \"string\") {\n return Array.from(window.document.querySelectorAll(target2)).some((el) => el === event.target || event.composedPath().includes(el));\n } else {\n const el = unrefElement(target2);\n return el && (event.target === el || event.composedPath().includes(el));\n }\n });\n };\n const listener = (event) => {\n const el = unrefElement(target);\n if (!el || el === event.target || event.composedPath().includes(el))\n return;\n if (event.detail === 0)\n shouldListen = !shouldIgnore(event);\n if (!shouldListen) {\n shouldListen = true;\n return;\n }\n handler(event);\n };\n const cleanup = [\n useEventListener(window, \"click\", listener, { passive: true, capture }),\n useEventListener(window, \"pointerdown\", (e) => {\n const el = unrefElement(target);\n if (el)\n shouldListen = !e.composedPath().includes(el) && !shouldIgnore(e);\n }, { passive: true }),\n detectIframe && useEventListener(window, \"blur\", (event) => {\n var _a;\n const el = unrefElement(target);\n if (((_a = window.document.activeElement) == null ? void 0 : _a.tagName) === \"IFRAME\" && !(el == null ? void 0 : el.contains(window.document.activeElement)))\n handler(event);\n })\n ].filter(Boolean);\n const stop = () => cleanup.forEach((fn) => fn());\n return stop;\n}\n\nvar __defProp$n = Object.defineProperty;\nvar __defProps$a = Object.defineProperties;\nvar __getOwnPropDescs$a = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$q = Object.getOwnPropertySymbols;\nvar __hasOwnProp$q = Object.prototype.hasOwnProperty;\nvar __propIsEnum$q = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$n = (obj, key, value) => key in obj ? __defProp$n(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$n = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$q.call(b, prop))\n __defNormalProp$n(a, prop, b[prop]);\n if (__getOwnPropSymbols$q)\n for (var prop of __getOwnPropSymbols$q(b)) {\n if (__propIsEnum$q.call(b, prop))\n __defNormalProp$n(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$a = (a, b) => __defProps$a(a, __getOwnPropDescs$a(b));\nconst createKeyPredicate = (keyFilter) => {\n if (typeof keyFilter === \"function\")\n return keyFilter;\n else if (typeof keyFilter === \"string\")\n return (event) => event.key === keyFilter;\n else if (Array.isArray(keyFilter))\n return (event) => keyFilter.includes(event.key);\n return () => true;\n};\nfunction onKeyStroke(...args) {\n let key;\n let handler;\n let options = {};\n if (args.length === 3) {\n key = args[0];\n handler = args[1];\n options = args[2];\n } else if (args.length === 2) {\n if (typeof args[1] === \"object\") {\n key = true;\n handler = args[0];\n options = args[1];\n } else {\n key = args[0];\n handler = args[1];\n }\n } else {\n key = true;\n handler = args[0];\n }\n const {\n target = defaultWindow,\n eventName = \"keydown\",\n passive = false,\n dedupe = false\n } = options;\n const predicate = createKeyPredicate(key);\n const listener = (e) => {\n if (e.repeat && resolveUnref(dedupe))\n return;\n if (predicate(e))\n handler(e);\n };\n return useEventListener(target, eventName, listener, passive);\n}\nfunction onKeyDown(key, handler, options = {}) {\n return onKeyStroke(key, handler, __spreadProps$a(__spreadValues$n({}, options), { eventName: \"keydown\" }));\n}\nfunction onKeyPressed(key, handler, options = {}) {\n return onKeyStroke(key, handler, __spreadProps$a(__spreadValues$n({}, options), { eventName: \"keypress\" }));\n}\nfunction onKeyUp(key, handler, options = {}) {\n return onKeyStroke(key, handler, __spreadProps$a(__spreadValues$n({}, options), { eventName: \"keyup\" }));\n}\n\nconst DEFAULT_DELAY = 500;\nfunction onLongPress(target, handler, options) {\n var _a, _b;\n const elementRef = computed(() => unrefElement(target));\n let timeout;\n function clear() {\n if (timeout) {\n clearTimeout(timeout);\n timeout = void 0;\n }\n }\n function onDown(ev) {\n var _a2, _b2, _c, _d;\n if (((_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.self) && ev.target !== elementRef.value)\n return;\n clear();\n if ((_b2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _b2.prevent)\n ev.preventDefault();\n if ((_c = options == null ? void 0 : options.modifiers) == null ? void 0 : _c.stop)\n ev.stopPropagation();\n timeout = setTimeout(() => handler(ev), (_d = options == null ? void 0 : options.delay) != null ? _d : DEFAULT_DELAY);\n }\n const listenerOptions = {\n capture: (_a = options == null ? void 0 : options.modifiers) == null ? void 0 : _a.capture,\n once: (_b = options == null ? void 0 : options.modifiers) == null ? void 0 : _b.once\n };\n useEventListener(elementRef, \"pointerdown\", onDown, listenerOptions);\n useEventListener(elementRef, \"pointerup\", clear, listenerOptions);\n useEventListener(elementRef, \"pointerleave\", clear, listenerOptions);\n}\n\nconst isFocusedElementEditable = () => {\n const { activeElement, body } = document;\n if (!activeElement)\n return false;\n if (activeElement === body)\n return false;\n switch (activeElement.tagName) {\n case \"INPUT\":\n case \"TEXTAREA\":\n return true;\n }\n return activeElement.hasAttribute(\"contenteditable\");\n};\nconst isTypedCharValid = ({\n keyCode,\n metaKey,\n ctrlKey,\n altKey\n}) => {\n if (metaKey || ctrlKey || altKey)\n return false;\n if (keyCode >= 48 && keyCode <= 57 || keyCode >= 96 && keyCode <= 105)\n return true;\n if (keyCode >= 65 && keyCode <= 90)\n return true;\n return false;\n};\nfunction onStartTyping(callback, options = {}) {\n const { document: document2 = defaultDocument } = options;\n const keydown = (event) => {\n !isFocusedElementEditable() && isTypedCharValid(event) && callback(event);\n };\n if (document2)\n useEventListener(document2, \"keydown\", keydown, { passive: true });\n}\n\nfunction templateRef(key, initialValue = null) {\n const instance = getCurrentInstance();\n let _trigger = () => {\n };\n const element = customRef((track, trigger) => {\n _trigger = trigger;\n return {\n get() {\n var _a, _b;\n track();\n return (_b = (_a = instance == null ? void 0 : instance.proxy) == null ? void 0 : _a.$refs[key]) != null ? _b : initialValue;\n },\n set() {\n }\n };\n });\n tryOnMounted(_trigger);\n onUpdated(_trigger);\n return element;\n}\n\nfunction useActiveElement(options = {}) {\n var _a;\n const { window = defaultWindow } = options;\n const document = (_a = options.document) != null ? _a : window == null ? void 0 : window.document;\n const activeElement = computedWithControl(() => null, () => document == null ? void 0 : document.activeElement);\n if (window) {\n useEventListener(window, \"blur\", (event) => {\n if (event.relatedTarget !== null)\n return;\n activeElement.trigger();\n }, true);\n useEventListener(window, \"focus\", activeElement.trigger, true);\n }\n return activeElement;\n}\n\nfunction useAsyncQueue(tasks, options = {}) {\n const {\n interrupt = true,\n onError = noop,\n onFinished = noop\n } = options;\n const promiseState = {\n pending: \"pending\",\n rejected: \"rejected\",\n fulfilled: \"fulfilled\"\n };\n const initialResult = Array.from(new Array(tasks.length), () => ({ state: promiseState.pending, data: null }));\n const result = reactive(initialResult);\n const activeIndex = ref(-1);\n if (!tasks || tasks.length === 0) {\n onFinished();\n return {\n activeIndex,\n result\n };\n }\n function updateResult(state, res) {\n activeIndex.value++;\n result[activeIndex.value].data = res;\n result[activeIndex.value].state = state;\n }\n tasks.reduce((prev, curr) => {\n return prev.then((prevRes) => {\n var _a;\n if (((_a = result[activeIndex.value]) == null ? void 0 : _a.state) === promiseState.rejected && interrupt) {\n onFinished();\n return;\n }\n return curr(prevRes).then((currentRes) => {\n updateResult(promiseState.fulfilled, currentRes);\n activeIndex.value === tasks.length - 1 && onFinished();\n return currentRes;\n });\n }).catch((e) => {\n updateResult(promiseState.rejected, e);\n onError();\n return e;\n });\n }, Promise.resolve());\n return {\n activeIndex,\n result\n };\n}\n\nfunction useAsyncState(promise, initialState, options) {\n const {\n immediate = true,\n delay = 0,\n onError = noop,\n onSuccess = noop,\n resetOnExecute = true,\n shallow = true,\n throwError\n } = options != null ? options : {};\n const state = shallow ? shallowRef(initialState) : ref(initialState);\n const isReady = ref(false);\n const isLoading = ref(false);\n const error = shallowRef(void 0);\n async function execute(delay2 = 0, ...args) {\n if (resetOnExecute)\n state.value = initialState;\n error.value = void 0;\n isReady.value = false;\n isLoading.value = true;\n if (delay2 > 0)\n await promiseTimeout(delay2);\n const _promise = typeof promise === \"function\" ? promise(...args) : promise;\n try {\n const data = await _promise;\n state.value = data;\n isReady.value = true;\n onSuccess(data);\n } catch (e) {\n error.value = e;\n onError(e);\n if (throwError)\n throw e;\n } finally {\n isLoading.value = false;\n }\n return state.value;\n }\n if (immediate)\n execute(delay);\n return {\n state,\n isReady,\n isLoading,\n error,\n execute\n };\n}\n\nconst defaults = {\n array: (v) => JSON.stringify(v),\n object: (v) => JSON.stringify(v),\n set: (v) => JSON.stringify(Array.from(v)),\n map: (v) => JSON.stringify(Object.fromEntries(v)),\n null: () => \"\"\n};\nfunction getDefaultSerialization(target) {\n if (!target)\n return defaults.null;\n if (target instanceof Map)\n return defaults.map;\n else if (target instanceof Set)\n return defaults.set;\n else if (Array.isArray(target))\n return defaults.array;\n else\n return defaults.object;\n}\n\nfunction useBase64(target, options) {\n const base64 = ref(\"\");\n const promise = ref();\n function execute() {\n if (!isClient)\n return;\n promise.value = new Promise((resolve, reject) => {\n try {\n const _target = resolveUnref(target);\n if (_target == null) {\n resolve(\"\");\n } else if (typeof _target === \"string\") {\n resolve(blobToBase64(new Blob([_target], { type: \"text/plain\" })));\n } else if (_target instanceof Blob) {\n resolve(blobToBase64(_target));\n } else if (_target instanceof ArrayBuffer) {\n resolve(window.btoa(String.fromCharCode(...new Uint8Array(_target))));\n } else if (_target instanceof HTMLCanvasElement) {\n resolve(_target.toDataURL(options == null ? void 0 : options.type, options == null ? void 0 : options.quality));\n } else if (_target instanceof HTMLImageElement) {\n const img = _target.cloneNode(false);\n img.crossOrigin = \"Anonymous\";\n imgLoaded(img).then(() => {\n const canvas = document.createElement(\"canvas\");\n const ctx = canvas.getContext(\"2d\");\n canvas.width = img.width;\n canvas.height = img.height;\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n resolve(canvas.toDataURL(options == null ? void 0 : options.type, options == null ? void 0 : options.quality));\n }).catch(reject);\n } else if (typeof _target === \"object\") {\n const _serializeFn = (options == null ? void 0 : options.serializer) || getDefaultSerialization(_target);\n const serialized = _serializeFn(_target);\n return resolve(blobToBase64(new Blob([serialized], { type: \"application/json\" })));\n } else {\n reject(new Error(\"target is unsupported types\"));\n }\n } catch (error) {\n reject(error);\n }\n });\n promise.value.then((res) => base64.value = res);\n return promise.value;\n }\n if (isRef(target) || isFunction(target))\n watch(target, execute, { immediate: true });\n else\n execute();\n return {\n base64,\n promise,\n execute\n };\n}\nfunction imgLoaded(img) {\n return new Promise((resolve, reject) => {\n if (!img.complete) {\n img.onload = () => {\n resolve();\n };\n img.onerror = reject;\n } else {\n resolve();\n }\n });\n}\nfunction blobToBase64(blob) {\n return new Promise((resolve, reject) => {\n const fr = new FileReader();\n fr.onload = (e) => {\n resolve(e.target.result);\n };\n fr.onerror = reject;\n fr.readAsDataURL(blob);\n });\n}\n\nfunction useMounted() {\n const isMounted = ref(false);\n onMounted(() => {\n isMounted.value = true;\n });\n return isMounted;\n}\n\nfunction useSupported(callback) {\n const isMounted = useMounted();\n return computed(() => {\n isMounted.value;\n return Boolean(callback());\n });\n}\n\nfunction useBattery({ navigator = defaultNavigator } = {}) {\n const events = [\"chargingchange\", \"chargingtimechange\", \"dischargingtimechange\", \"levelchange\"];\n const isSupported = useSupported(() => navigator && \"getBattery\" in navigator);\n const charging = ref(false);\n const chargingTime = ref(0);\n const dischargingTime = ref(0);\n const level = ref(1);\n let battery;\n function updateBatteryInfo() {\n charging.value = this.charging;\n chargingTime.value = this.chargingTime || 0;\n dischargingTime.value = this.dischargingTime || 0;\n level.value = this.level;\n }\n if (isSupported.value) {\n navigator.getBattery().then((_battery) => {\n battery = _battery;\n updateBatteryInfo.call(battery);\n for (const event of events)\n useEventListener(battery, event, updateBatteryInfo, { passive: true });\n });\n }\n return {\n isSupported,\n charging,\n chargingTime,\n dischargingTime,\n level\n };\n}\n\nfunction useBluetooth(options) {\n let {\n acceptAllDevices = false\n } = options || {};\n const {\n filters = void 0,\n optionalServices = void 0,\n navigator = defaultNavigator\n } = options || {};\n const isSupported = useSupported(() => navigator && \"bluetooth\" in navigator);\n const device = shallowRef(void 0);\n const error = shallowRef(null);\n watch(device, () => {\n connectToBluetoothGATTServer();\n });\n async function requestDevice() {\n if (!isSupported.value)\n return;\n error.value = null;\n if (filters && filters.length > 0)\n acceptAllDevices = false;\n try {\n device.value = await (navigator == null ? void 0 : navigator.bluetooth.requestDevice({\n acceptAllDevices,\n filters,\n optionalServices\n }));\n } catch (err) {\n error.value = err;\n }\n }\n const server = ref();\n const isConnected = computed(() => {\n var _a;\n return ((_a = server.value) == null ? void 0 : _a.connected) || false;\n });\n async function connectToBluetoothGATTServer() {\n error.value = null;\n if (device.value && device.value.gatt) {\n device.value.addEventListener(\"gattserverdisconnected\", () => {\n });\n try {\n server.value = await device.value.gatt.connect();\n } catch (err) {\n error.value = err;\n }\n }\n }\n tryOnMounted(() => {\n var _a;\n if (device.value)\n (_a = device.value.gatt) == null ? void 0 : _a.connect();\n });\n tryOnScopeDispose(() => {\n var _a;\n if (device.value)\n (_a = device.value.gatt) == null ? void 0 : _a.disconnect();\n });\n return {\n isSupported,\n isConnected,\n device,\n requestDevice,\n server,\n error\n };\n}\n\nfunction useMediaQuery(query, options = {}) {\n const { window = defaultWindow } = options;\n const isSupported = useSupported(() => window && \"matchMedia\" in window && typeof window.matchMedia === \"function\");\n let mediaQuery;\n const matches = ref(false);\n const cleanup = () => {\n if (!mediaQuery)\n return;\n if (\"removeEventListener\" in mediaQuery)\n mediaQuery.removeEventListener(\"change\", update);\n else\n mediaQuery.removeListener(update);\n };\n const update = () => {\n if (!isSupported.value)\n return;\n cleanup();\n mediaQuery = window.matchMedia(resolveRef(query).value);\n matches.value = mediaQuery.matches;\n if (\"addEventListener\" in mediaQuery)\n mediaQuery.addEventListener(\"change\", update);\n else\n mediaQuery.addListener(update);\n };\n watchEffect(update);\n tryOnScopeDispose(() => cleanup());\n return matches;\n}\n\nconst breakpointsTailwind = {\n \"sm\": 640,\n \"md\": 768,\n \"lg\": 1024,\n \"xl\": 1280,\n \"2xl\": 1536\n};\nconst breakpointsBootstrapV5 = {\n sm: 576,\n md: 768,\n lg: 992,\n xl: 1200,\n xxl: 1400\n};\nconst breakpointsVuetify = {\n xs: 600,\n sm: 960,\n md: 1264,\n lg: 1904\n};\nconst breakpointsAntDesign = {\n xs: 480,\n sm: 576,\n md: 768,\n lg: 992,\n xl: 1200,\n xxl: 1600\n};\nconst breakpointsQuasar = {\n xs: 600,\n sm: 1024,\n md: 1440,\n lg: 1920\n};\nconst breakpointsSematic = {\n mobileS: 320,\n mobileM: 375,\n mobileL: 425,\n tablet: 768,\n laptop: 1024,\n laptopL: 1440,\n desktop4K: 2560\n};\nconst breakpointsMasterCss = {\n \"3xs\": 360,\n \"2xs\": 480,\n \"xs\": 600,\n \"sm\": 768,\n \"md\": 1024,\n \"lg\": 1280,\n \"xl\": 1440,\n \"2xl\": 1600,\n \"3xl\": 1920,\n \"4xl\": 2560\n};\n\nfunction useBreakpoints(breakpoints, options = {}) {\n function getValue(k, delta) {\n let v = breakpoints[k];\n if (delta != null)\n v = increaseWithUnit(v, delta);\n if (typeof v === \"number\")\n v = `${v}px`;\n return v;\n }\n const { window = defaultWindow } = options;\n function match(query) {\n if (!window)\n return false;\n return window.matchMedia(query).matches;\n }\n const greaterOrEqual = (k) => {\n return useMediaQuery(`(min-width: ${getValue(k)})`, options);\n };\n const shortcutMethods = Object.keys(breakpoints).reduce((shortcuts, k) => {\n Object.defineProperty(shortcuts, k, {\n get: () => greaterOrEqual(k),\n enumerable: true,\n configurable: true\n });\n return shortcuts;\n }, {});\n return Object.assign(shortcutMethods, {\n greater(k) {\n return useMediaQuery(`(min-width: ${getValue(k, 0.1)})`, options);\n },\n greaterOrEqual,\n smaller(k) {\n return useMediaQuery(`(max-width: ${getValue(k, -0.1)})`, options);\n },\n smallerOrEqual(k) {\n return useMediaQuery(`(max-width: ${getValue(k)})`, options);\n },\n between(a, b) {\n return useMediaQuery(`(min-width: ${getValue(a)}) and (max-width: ${getValue(b, -0.1)})`, options);\n },\n isGreater(k) {\n return match(`(min-width: ${getValue(k, 0.1)})`);\n },\n isGreaterOrEqual(k) {\n return match(`(min-width: ${getValue(k)})`);\n },\n isSmaller(k) {\n return match(`(max-width: ${getValue(k, -0.1)})`);\n },\n isSmallerOrEqual(k) {\n return match(`(max-width: ${getValue(k)})`);\n },\n isInBetween(a, b) {\n return match(`(min-width: ${getValue(a)}) and (max-width: ${getValue(b, -0.1)})`);\n },\n current() {\n const points = Object.keys(breakpoints).map((i) => [i, greaterOrEqual(i)]);\n return computed(() => points.filter(([, v]) => v.value).map(([k]) => k));\n }\n });\n}\n\nconst useBroadcastChannel = (options) => {\n const {\n name,\n window = defaultWindow\n } = options;\n const isSupported = useSupported(() => window && \"BroadcastChannel\" in window);\n const isClosed = ref(false);\n const channel = ref();\n const data = ref();\n const error = shallowRef(null);\n const post = (data2) => {\n if (channel.value)\n channel.value.postMessage(data2);\n };\n const close = () => {\n if (channel.value)\n channel.value.close();\n isClosed.value = true;\n };\n if (isSupported.value) {\n tryOnMounted(() => {\n error.value = null;\n channel.value = new BroadcastChannel(name);\n channel.value.addEventListener(\"message\", (e) => {\n data.value = e.data;\n }, { passive: true });\n channel.value.addEventListener(\"messageerror\", (e) => {\n error.value = e;\n }, { passive: true });\n channel.value.addEventListener(\"close\", () => {\n isClosed.value = true;\n });\n });\n }\n tryOnScopeDispose(() => {\n close();\n });\n return {\n isSupported,\n channel,\n data,\n post,\n close,\n error,\n isClosed\n };\n};\n\nvar __defProp$m = Object.defineProperty;\nvar __getOwnPropSymbols$p = Object.getOwnPropertySymbols;\nvar __hasOwnProp$p = Object.prototype.hasOwnProperty;\nvar __propIsEnum$p = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$m = (obj, key, value) => key in obj ? __defProp$m(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$m = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$p.call(b, prop))\n __defNormalProp$m(a, prop, b[prop]);\n if (__getOwnPropSymbols$p)\n for (var prop of __getOwnPropSymbols$p(b)) {\n if (__propIsEnum$p.call(b, prop))\n __defNormalProp$m(a, prop, b[prop]);\n }\n return a;\n};\nconst WRITABLE_PROPERTIES = [\n \"hash\",\n \"host\",\n \"hostname\",\n \"href\",\n \"pathname\",\n \"port\",\n \"protocol\",\n \"search\"\n];\nfunction useBrowserLocation({ window = defaultWindow } = {}) {\n const refs = Object.fromEntries(WRITABLE_PROPERTIES.map((key) => [key, ref()]));\n for (const [key, ref2] of objectEntries(refs)) {\n watch(ref2, (value) => {\n if (!(window == null ? void 0 : window.location) || window.location[key] === value)\n return;\n window.location[key] = value;\n });\n }\n const buildState = (trigger) => {\n var _a;\n const { state: state2, length } = (window == null ? void 0 : window.history) || {};\n const { origin } = (window == null ? void 0 : window.location) || {};\n for (const key of WRITABLE_PROPERTIES)\n refs[key].value = (_a = window == null ? void 0 : window.location) == null ? void 0 : _a[key];\n return reactive(__spreadValues$m({\n trigger,\n state: state2,\n length,\n origin\n }, refs));\n };\n const state = ref(buildState(\"load\"));\n if (window) {\n useEventListener(window, \"popstate\", () => state.value = buildState(\"popstate\"), { passive: true });\n useEventListener(window, \"hashchange\", () => state.value = buildState(\"hashchange\"), { passive: true });\n }\n return state;\n}\n\nfunction useCached(refValue, comparator = (a, b) => a === b, watchOptions) {\n const cachedValue = ref(refValue.value);\n watch(() => refValue.value, (value) => {\n if (!comparator(value, cachedValue.value))\n cachedValue.value = value;\n }, watchOptions);\n return cachedValue;\n}\n\nfunction useClipboard(options = {}) {\n const {\n navigator = defaultNavigator,\n read = false,\n source,\n copiedDuring = 1500,\n legacy = false\n } = options;\n const events = [\"copy\", \"cut\"];\n const isClipboardApiSupported = useSupported(() => navigator && \"clipboard\" in navigator);\n const isSupported = computed(() => isClipboardApiSupported.value || legacy);\n const text = ref(\"\");\n const copied = ref(false);\n const timeout = useTimeoutFn(() => copied.value = false, copiedDuring);\n function updateText() {\n if (isClipboardApiSupported.value) {\n navigator.clipboard.readText().then((value) => {\n text.value = value;\n });\n } else {\n text.value = legacyRead();\n }\n }\n if (isSupported.value && read) {\n for (const event of events)\n useEventListener(event, updateText);\n }\n async function copy(value = resolveUnref(source)) {\n if (isSupported.value && value != null) {\n if (isClipboardApiSupported.value)\n await navigator.clipboard.writeText(value);\n else\n legacyCopy(value);\n text.value = value;\n copied.value = true;\n timeout.start();\n }\n }\n function legacyCopy(value) {\n const ta = document.createElement(\"textarea\");\n ta.value = value != null ? value : \"\";\n ta.style.position = \"absolute\";\n ta.style.opacity = \"0\";\n document.body.appendChild(ta);\n ta.select();\n document.execCommand(\"copy\");\n ta.remove();\n }\n function legacyRead() {\n var _a, _b, _c;\n return (_c = (_b = (_a = document == null ? void 0 : document.getSelection) == null ? void 0 : _a.call(document)) == null ? void 0 : _b.toString()) != null ? _c : \"\";\n }\n return {\n isSupported,\n text,\n copied,\n copy\n };\n}\n\nvar __defProp$l = Object.defineProperty;\nvar __defProps$9 = Object.defineProperties;\nvar __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$o = Object.getOwnPropertySymbols;\nvar __hasOwnProp$o = Object.prototype.hasOwnProperty;\nvar __propIsEnum$o = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$l = (obj, key, value) => key in obj ? __defProp$l(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$l = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$o.call(b, prop))\n __defNormalProp$l(a, prop, b[prop]);\n if (__getOwnPropSymbols$o)\n for (var prop of __getOwnPropSymbols$o(b)) {\n if (__propIsEnum$o.call(b, prop))\n __defNormalProp$l(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));\nfunction cloneFnJSON(source) {\n return JSON.parse(JSON.stringify(source));\n}\nfunction useCloned(source, options = {}) {\n const cloned = ref({});\n const {\n manual,\n clone = cloneFnJSON,\n deep = true,\n immediate = true\n } = options;\n function sync() {\n cloned.value = clone(unref(source));\n }\n if (!manual && isRef(source)) {\n watch(source, sync, __spreadProps$9(__spreadValues$l({}, options), {\n deep,\n immediate\n }));\n } else {\n sync();\n }\n return { cloned, sync };\n}\n\nconst _global = typeof globalThis !== \"undefined\" ? globalThis : typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : {};\nconst globalKey = \"__vueuse_ssr_handlers__\";\n_global[globalKey] = _global[globalKey] || {};\nconst handlers = _global[globalKey];\nfunction getSSRHandler(key, fallback) {\n return handlers[key] || fallback;\n}\nfunction setSSRHandler(key, fn) {\n handlers[key] = fn;\n}\n\nfunction guessSerializerType(rawInit) {\n return rawInit == null ? \"any\" : rawInit instanceof Set ? \"set\" : rawInit instanceof Map ? \"map\" : rawInit instanceof Date ? \"date\" : typeof rawInit === \"boolean\" ? \"boolean\" : typeof rawInit === \"string\" ? \"string\" : typeof rawInit === \"object\" ? \"object\" : !Number.isNaN(rawInit) ? \"number\" : \"any\";\n}\n\nvar __defProp$k = Object.defineProperty;\nvar __getOwnPropSymbols$n = Object.getOwnPropertySymbols;\nvar __hasOwnProp$n = Object.prototype.hasOwnProperty;\nvar __propIsEnum$n = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$k = (obj, key, value) => key in obj ? __defProp$k(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$k = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$n.call(b, prop))\n __defNormalProp$k(a, prop, b[prop]);\n if (__getOwnPropSymbols$n)\n for (var prop of __getOwnPropSymbols$n(b)) {\n if (__propIsEnum$n.call(b, prop))\n __defNormalProp$k(a, prop, b[prop]);\n }\n return a;\n};\nconst StorageSerializers = {\n boolean: {\n read: (v) => v === \"true\",\n write: (v) => String(v)\n },\n object: {\n read: (v) => JSON.parse(v),\n write: (v) => JSON.stringify(v)\n },\n number: {\n read: (v) => Number.parseFloat(v),\n write: (v) => String(v)\n },\n any: {\n read: (v) => v,\n write: (v) => String(v)\n },\n string: {\n read: (v) => v,\n write: (v) => String(v)\n },\n map: {\n read: (v) => new Map(JSON.parse(v)),\n write: (v) => JSON.stringify(Array.from(v.entries()))\n },\n set: {\n read: (v) => new Set(JSON.parse(v)),\n write: (v) => JSON.stringify(Array.from(v))\n },\n date: {\n read: (v) => new Date(v),\n write: (v) => v.toISOString()\n }\n};\nconst customStorageEventName = \"vueuse-storage\";\nfunction useStorage(key, defaults, storage, options = {}) {\n var _a;\n const {\n flush = \"pre\",\n deep = true,\n listenToStorageChanges = true,\n writeDefaults = true,\n mergeDefaults = false,\n shallow,\n window = defaultWindow,\n eventFilter,\n onError = (e) => {\n console.error(e);\n }\n } = options;\n const data = (shallow ? shallowRef : ref)(defaults);\n if (!storage) {\n try {\n storage = getSSRHandler(\"getDefaultStorage\", () => {\n var _a2;\n return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage;\n })();\n } catch (e) {\n onError(e);\n }\n }\n if (!storage)\n return data;\n const rawInit = resolveUnref(defaults);\n const type = guessSerializerType(rawInit);\n const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type];\n const { pause: pauseWatch, resume: resumeWatch } = pausableWatch(data, () => write(data.value), { flush, deep, eventFilter });\n if (window && listenToStorageChanges) {\n useEventListener(window, \"storage\", update);\n useEventListener(window, customStorageEventName, updateFromCustomEvent);\n }\n update();\n return data;\n function write(v) {\n try {\n if (v == null) {\n storage.removeItem(key);\n } else {\n const serialized = serializer.write(v);\n const oldValue = storage.getItem(key);\n if (oldValue !== serialized) {\n storage.setItem(key, serialized);\n if (window) {\n window.dispatchEvent(new CustomEvent(customStorageEventName, {\n detail: {\n key,\n oldValue,\n newValue: serialized,\n storageArea: storage\n }\n }));\n }\n }\n }\n } catch (e) {\n onError(e);\n }\n }\n function read(event) {\n const rawValue = event ? event.newValue : storage.getItem(key);\n if (rawValue == null) {\n if (writeDefaults && rawInit !== null)\n storage.setItem(key, serializer.write(rawInit));\n return rawInit;\n } else if (!event && mergeDefaults) {\n const value = serializer.read(rawValue);\n if (isFunction(mergeDefaults))\n return mergeDefaults(value, rawInit);\n else if (type === \"object\" && !Array.isArray(value))\n return __spreadValues$k(__spreadValues$k({}, rawInit), value);\n return value;\n } else if (typeof rawValue !== \"string\") {\n return rawValue;\n } else {\n return serializer.read(rawValue);\n }\n }\n function updateFromCustomEvent(event) {\n update(event.detail);\n }\n function update(event) {\n if (event && event.storageArea !== storage)\n return;\n if (event && event.key == null) {\n data.value = rawInit;\n return;\n }\n if (event && event.key !== key)\n return;\n pauseWatch();\n try {\n data.value = read(event);\n } catch (e) {\n onError(e);\n } finally {\n if (event)\n nextTick(resumeWatch);\n else\n resumeWatch();\n }\n }\n}\n\nfunction usePreferredDark(options) {\n return useMediaQuery(\"(prefers-color-scheme: dark)\", options);\n}\n\nvar __defProp$j = Object.defineProperty;\nvar __getOwnPropSymbols$m = Object.getOwnPropertySymbols;\nvar __hasOwnProp$m = Object.prototype.hasOwnProperty;\nvar __propIsEnum$m = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$j = (obj, key, value) => key in obj ? __defProp$j(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$j = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$m.call(b, prop))\n __defNormalProp$j(a, prop, b[prop]);\n if (__getOwnPropSymbols$m)\n for (var prop of __getOwnPropSymbols$m(b)) {\n if (__propIsEnum$m.call(b, prop))\n __defNormalProp$j(a, prop, b[prop]);\n }\n return a;\n};\nfunction useColorMode(options = {}) {\n const {\n selector = \"html\",\n attribute = \"class\",\n initialValue = \"auto\",\n window = defaultWindow,\n storage,\n storageKey = \"vueuse-color-scheme\",\n listenToStorageChanges = true,\n storageRef,\n emitAuto,\n disableTransition = false\n } = options;\n const modes = __spreadValues$j({\n auto: \"\",\n light: \"light\",\n dark: \"dark\"\n }, options.modes || {});\n const preferredDark = usePreferredDark({ window });\n const preferredMode = computed(() => preferredDark.value ? \"dark\" : \"light\");\n const store = storageRef || (storageKey == null ? ref(initialValue) : useStorage(storageKey, initialValue, storage, { window, listenToStorageChanges }));\n const state = computed({\n get() {\n return store.value === \"auto\" && !emitAuto ? preferredMode.value : store.value;\n },\n set(v) {\n store.value = v;\n }\n });\n const updateHTMLAttrs = getSSRHandler(\"updateHTMLAttrs\", (selector2, attribute2, value) => {\n const el = window == null ? void 0 : window.document.querySelector(selector2);\n if (!el)\n return;\n let style;\n if (disableTransition) {\n style = window.document.createElement(\"style\");\n style.type = \"text/css\";\n style.appendChild(document.createTextNode(\"*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}\"));\n window.document.head.appendChild(style);\n }\n if (attribute2 === \"class\") {\n const current = value.split(/\\s/g);\n Object.values(modes).flatMap((i) => (i || \"\").split(/\\s/g)).filter(Boolean).forEach((v) => {\n if (current.includes(v))\n el.classList.add(v);\n else\n el.classList.remove(v);\n });\n } else {\n el.setAttribute(attribute2, value);\n }\n if (disableTransition) {\n window.getComputedStyle(style).opacity;\n document.head.removeChild(style);\n }\n });\n function defaultOnChanged(mode) {\n var _a;\n const resolvedMode = mode === \"auto\" ? preferredMode.value : mode;\n updateHTMLAttrs(selector, attribute, (_a = modes[resolvedMode]) != null ? _a : resolvedMode);\n }\n function onChanged(mode) {\n if (options.onChanged)\n options.onChanged(mode, defaultOnChanged);\n else\n defaultOnChanged(mode);\n }\n watch(state, onChanged, { flush: \"post\", immediate: true });\n if (emitAuto)\n watch(preferredMode, () => onChanged(state.value), { flush: \"post\" });\n tryOnMounted(() => onChanged(state.value));\n return state;\n}\n\nfunction useConfirmDialog(revealed = ref(false)) {\n const confirmHook = createEventHook();\n const cancelHook = createEventHook();\n const revealHook = createEventHook();\n let _resolve = noop;\n const reveal = (data) => {\n revealHook.trigger(data);\n revealed.value = true;\n return new Promise((resolve) => {\n _resolve = resolve;\n });\n };\n const confirm = (data) => {\n revealed.value = false;\n confirmHook.trigger(data);\n _resolve({ data, isCanceled: false });\n };\n const cancel = (data) => {\n revealed.value = false;\n cancelHook.trigger(data);\n _resolve({ data, isCanceled: true });\n };\n return {\n isRevealed: computed(() => revealed.value),\n reveal,\n confirm,\n cancel,\n onReveal: revealHook.on,\n onConfirm: confirmHook.on,\n onCancel: cancelHook.on\n };\n}\n\nfunction useCssVar(prop, target, options = {}) {\n const { window = defaultWindow, initialValue = \"\", observe = false } = options;\n const variable = ref(initialValue);\n const elRef = computed(() => {\n var _a;\n return unrefElement(target) || ((_a = window == null ? void 0 : window.document) == null ? void 0 : _a.documentElement);\n });\n function updateCssVar() {\n var _a;\n const key = resolveUnref(prop);\n const el = resolveUnref(elRef);\n if (el && window) {\n const value = (_a = window.getComputedStyle(el).getPropertyValue(key)) == null ? void 0 : _a.trim();\n variable.value = value || initialValue;\n }\n }\n if (observe) {\n useMutationObserver$1(elRef, updateCssVar, {\n attributes: true,\n window\n });\n }\n watch([elRef, () => resolveUnref(prop)], updateCssVar, { immediate: true });\n watch(variable, (val) => {\n var _a;\n if ((_a = elRef.value) == null ? void 0 : _a.style)\n elRef.value.style.setProperty(resolveUnref(prop), val);\n });\n return variable;\n}\n\nfunction useCurrentElement() {\n const vm = getCurrentInstance();\n const currentElement = computedWithControl(() => null, () => vm.proxy.$el);\n onUpdated(currentElement.trigger);\n onMounted(currentElement.trigger);\n return currentElement;\n}\n\nfunction useCycleList(list, options) {\n const state = shallowRef(getInitialValue());\n const listRef = resolveRef(list);\n const index = computed({\n get() {\n var _a;\n const targetList = resolveUnref(list);\n let index2 = (options == null ? void 0 : options.getIndexOf) ? options.getIndexOf(state.value, targetList) : targetList.indexOf(state.value);\n if (index2 < 0)\n index2 = (_a = options == null ? void 0 : options.fallbackIndex) != null ? _a : 0;\n return index2;\n },\n set(v) {\n set(v);\n }\n });\n function set(i) {\n const targetList = listRef.value;\n const length = targetList.length;\n const index2 = (i % length + length) % length;\n const value = targetList[index2];\n state.value = value;\n return value;\n }\n function shift(delta = 1) {\n return set(index.value + delta);\n }\n function next(n = 1) {\n return shift(n);\n }\n function prev(n = 1) {\n return shift(-n);\n }\n function getInitialValue() {\n var _a, _b;\n return (_b = resolveUnref((_a = options == null ? void 0 : options.initialValue) != null ? _a : resolveUnref(list)[0])) != null ? _b : void 0;\n }\n watch(listRef, () => set(index.value));\n return {\n state,\n index,\n next,\n prev\n };\n}\n\nvar __defProp$i = Object.defineProperty;\nvar __defProps$8 = Object.defineProperties;\nvar __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$l = Object.getOwnPropertySymbols;\nvar __hasOwnProp$l = Object.prototype.hasOwnProperty;\nvar __propIsEnum$l = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$i = (obj, key, value) => key in obj ? __defProp$i(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$i = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$l.call(b, prop))\n __defNormalProp$i(a, prop, b[prop]);\n if (__getOwnPropSymbols$l)\n for (var prop of __getOwnPropSymbols$l(b)) {\n if (__propIsEnum$l.call(b, prop))\n __defNormalProp$i(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));\nfunction useDark(options = {}) {\n const {\n valueDark = \"dark\",\n valueLight = \"\",\n window = defaultWindow\n } = options;\n const mode = useColorMode(__spreadProps$8(__spreadValues$i({}, options), {\n onChanged: (mode2, defaultHandler) => {\n var _a;\n if (options.onChanged)\n (_a = options.onChanged) == null ? void 0 : _a.call(options, mode2 === \"dark\", defaultHandler, mode2);\n else\n defaultHandler(mode2);\n },\n modes: {\n dark: valueDark,\n light: valueLight\n }\n }));\n const preferredDark = usePreferredDark({ window });\n const isDark = computed({\n get() {\n return mode.value === \"dark\";\n },\n set(v) {\n if (v === preferredDark.value)\n mode.value = \"auto\";\n else\n mode.value = v ? \"dark\" : \"light\";\n }\n });\n return isDark;\n}\n\nconst fnBypass = (v) => v;\nconst fnSetSource = (source, value) => source.value = value;\nfunction defaultDump(clone) {\n return clone ? isFunction(clone) ? clone : cloneFnJSON : fnBypass;\n}\nfunction defaultParse(clone) {\n return clone ? isFunction(clone) ? clone : cloneFnJSON : fnBypass;\n}\nfunction useManualRefHistory(source, options = {}) {\n const {\n clone = false,\n dump = defaultDump(clone),\n parse = defaultParse(clone),\n setSource = fnSetSource\n } = options;\n function _createHistoryRecord() {\n return markRaw({\n snapshot: dump(source.value),\n timestamp: timestamp()\n });\n }\n const last = ref(_createHistoryRecord());\n const undoStack = ref([]);\n const redoStack = ref([]);\n const _setSource = (record) => {\n setSource(source, parse(record.snapshot));\n last.value = record;\n };\n const commit = () => {\n undoStack.value.unshift(last.value);\n last.value = _createHistoryRecord();\n if (options.capacity && undoStack.value.length > options.capacity)\n undoStack.value.splice(options.capacity, Infinity);\n if (redoStack.value.length)\n redoStack.value.splice(0, redoStack.value.length);\n };\n const clear = () => {\n undoStack.value.splice(0, undoStack.value.length);\n redoStack.value.splice(0, redoStack.value.length);\n };\n const undo = () => {\n const state = undoStack.value.shift();\n if (state) {\n redoStack.value.unshift(last.value);\n _setSource(state);\n }\n };\n const redo = () => {\n const state = redoStack.value.shift();\n if (state) {\n undoStack.value.unshift(last.value);\n _setSource(state);\n }\n };\n const reset = () => {\n _setSource(last.value);\n };\n const history = computed(() => [last.value, ...undoStack.value]);\n const canUndo = computed(() => undoStack.value.length > 0);\n const canRedo = computed(() => redoStack.value.length > 0);\n return {\n source,\n undoStack,\n redoStack,\n last,\n history,\n canUndo,\n canRedo,\n clear,\n commit,\n reset,\n undo,\n redo\n };\n}\n\nvar __defProp$h = Object.defineProperty;\nvar __defProps$7 = Object.defineProperties;\nvar __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$k = Object.getOwnPropertySymbols;\nvar __hasOwnProp$k = Object.prototype.hasOwnProperty;\nvar __propIsEnum$k = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$h = (obj, key, value) => key in obj ? __defProp$h(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$h = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$k.call(b, prop))\n __defNormalProp$h(a, prop, b[prop]);\n if (__getOwnPropSymbols$k)\n for (var prop of __getOwnPropSymbols$k(b)) {\n if (__propIsEnum$k.call(b, prop))\n __defNormalProp$h(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));\nfunction useRefHistory(source, options = {}) {\n const {\n deep = false,\n flush = \"pre\",\n eventFilter\n } = options;\n const {\n eventFilter: composedFilter,\n pause,\n resume: resumeTracking,\n isActive: isTracking\n } = pausableFilter(eventFilter);\n const {\n ignoreUpdates,\n ignorePrevAsyncUpdates,\n stop\n } = watchIgnorable(source, commit, { deep, flush, eventFilter: composedFilter });\n function setSource(source2, value) {\n ignorePrevAsyncUpdates();\n ignoreUpdates(() => {\n source2.value = value;\n });\n }\n const manualHistory = useManualRefHistory(source, __spreadProps$7(__spreadValues$h({}, options), { clone: options.clone || deep, setSource }));\n const { clear, commit: manualCommit } = manualHistory;\n function commit() {\n ignorePrevAsyncUpdates();\n manualCommit();\n }\n function resume(commitNow) {\n resumeTracking();\n if (commitNow)\n commit();\n }\n function batch(fn) {\n let canceled = false;\n const cancel = () => canceled = true;\n ignoreUpdates(() => {\n fn(cancel);\n });\n if (!canceled)\n commit();\n }\n function dispose() {\n stop();\n clear();\n }\n return __spreadProps$7(__spreadValues$h({}, manualHistory), {\n isTracking,\n pause,\n resume,\n commit,\n batch,\n dispose\n });\n}\n\nvar __defProp$g = Object.defineProperty;\nvar __defProps$6 = Object.defineProperties;\nvar __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$j = Object.getOwnPropertySymbols;\nvar __hasOwnProp$j = Object.prototype.hasOwnProperty;\nvar __propIsEnum$j = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$g = (obj, key, value) => key in obj ? __defProp$g(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$g = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$j.call(b, prop))\n __defNormalProp$g(a, prop, b[prop]);\n if (__getOwnPropSymbols$j)\n for (var prop of __getOwnPropSymbols$j(b)) {\n if (__propIsEnum$j.call(b, prop))\n __defNormalProp$g(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));\nfunction useDebouncedRefHistory(source, options = {}) {\n const filter = options.debounce ? debounceFilter(options.debounce) : void 0;\n const history = useRefHistory(source, __spreadProps$6(__spreadValues$g({}, options), { eventFilter: filter }));\n return __spreadValues$g({}, history);\n}\n\nfunction useDeviceMotion(options = {}) {\n const {\n window = defaultWindow,\n eventFilter = bypassFilter\n } = options;\n const acceleration = ref({ x: null, y: null, z: null });\n const rotationRate = ref({ alpha: null, beta: null, gamma: null });\n const interval = ref(0);\n const accelerationIncludingGravity = ref({\n x: null,\n y: null,\n z: null\n });\n if (window) {\n const onDeviceMotion = createFilterWrapper(eventFilter, (event) => {\n acceleration.value = event.acceleration;\n accelerationIncludingGravity.value = event.accelerationIncludingGravity;\n rotationRate.value = event.rotationRate;\n interval.value = event.interval;\n });\n useEventListener(window, \"devicemotion\", onDeviceMotion);\n }\n return {\n acceleration,\n accelerationIncludingGravity,\n rotationRate,\n interval\n };\n}\n\nfunction useDeviceOrientation(options = {}) {\n const { window = defaultWindow } = options;\n const isSupported = useSupported(() => window && \"DeviceOrientationEvent\" in window);\n const isAbsolute = ref(false);\n const alpha = ref(null);\n const beta = ref(null);\n const gamma = ref(null);\n if (window && isSupported.value) {\n useEventListener(window, \"deviceorientation\", (event) => {\n isAbsolute.value = event.absolute;\n alpha.value = event.alpha;\n beta.value = event.beta;\n gamma.value = event.gamma;\n });\n }\n return {\n isSupported,\n isAbsolute,\n alpha,\n beta,\n gamma\n };\n}\n\nfunction useDevicePixelRatio({\n window = defaultWindow\n} = {}) {\n const pixelRatio = ref(1);\n if (window) {\n let observe = function() {\n pixelRatio.value = window.devicePixelRatio;\n cleanup();\n media = window.matchMedia(`(resolution: ${pixelRatio.value}dppx)`);\n media.addEventListener(\"change\", observe, { once: true });\n }, cleanup = function() {\n media == null ? void 0 : media.removeEventListener(\"change\", observe);\n };\n let media;\n observe();\n tryOnScopeDispose(cleanup);\n }\n return { pixelRatio };\n}\n\nfunction usePermission(permissionDesc, options = {}) {\n const {\n controls = false,\n navigator = defaultNavigator\n } = options;\n const isSupported = useSupported(() => navigator && \"permissions\" in navigator);\n let permissionStatus;\n const desc = typeof permissionDesc === \"string\" ? { name: permissionDesc } : permissionDesc;\n const state = ref();\n const onChange = () => {\n if (permissionStatus)\n state.value = permissionStatus.state;\n };\n const query = createSingletonPromise(async () => {\n if (!isSupported.value)\n return;\n if (!permissionStatus) {\n try {\n permissionStatus = await navigator.permissions.query(desc);\n useEventListener(permissionStatus, \"change\", onChange);\n onChange();\n } catch (e) {\n state.value = \"prompt\";\n }\n }\n return permissionStatus;\n });\n query();\n if (controls) {\n return {\n state,\n isSupported,\n query\n };\n } else {\n return state;\n }\n}\n\nfunction useDevicesList(options = {}) {\n const {\n navigator = defaultNavigator,\n requestPermissions = false,\n constraints = { audio: true, video: true },\n onUpdated\n } = options;\n const devices = ref([]);\n const videoInputs = computed(() => devices.value.filter((i) => i.kind === \"videoinput\"));\n const audioInputs = computed(() => devices.value.filter((i) => i.kind === \"audioinput\"));\n const audioOutputs = computed(() => devices.value.filter((i) => i.kind === \"audiooutput\"));\n const isSupported = useSupported(() => navigator && navigator.mediaDevices && navigator.mediaDevices.enumerateDevices);\n const permissionGranted = ref(false);\n let stream;\n async function update() {\n if (!isSupported.value)\n return;\n devices.value = await navigator.mediaDevices.enumerateDevices();\n onUpdated == null ? void 0 : onUpdated(devices.value);\n if (stream) {\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n }\n }\n async function ensurePermissions() {\n if (!isSupported.value)\n return false;\n if (permissionGranted.value)\n return true;\n const { state, query } = usePermission(\"camera\", { controls: true });\n await query();\n if (state.value !== \"granted\") {\n stream = await navigator.mediaDevices.getUserMedia(constraints);\n update();\n permissionGranted.value = true;\n } else {\n permissionGranted.value = true;\n }\n return permissionGranted.value;\n }\n if (isSupported.value) {\n if (requestPermissions)\n ensurePermissions();\n useEventListener(navigator.mediaDevices, \"devicechange\", update);\n update();\n }\n return {\n devices,\n ensurePermissions,\n permissionGranted,\n videoInputs,\n audioInputs,\n audioOutputs,\n isSupported\n };\n}\n\nfunction useDisplayMedia(options = {}) {\n var _a;\n const enabled = ref((_a = options.enabled) != null ? _a : false);\n const video = options.video;\n const audio = options.audio;\n const { navigator = defaultNavigator } = options;\n const isSupported = useSupported(() => {\n var _a2;\n return (_a2 = navigator == null ? void 0 : navigator.mediaDevices) == null ? void 0 : _a2.getDisplayMedia;\n });\n const constraint = { audio, video };\n const stream = shallowRef();\n async function _start() {\n if (!isSupported.value || stream.value)\n return;\n stream.value = await navigator.mediaDevices.getDisplayMedia(constraint);\n return stream.value;\n }\n async function _stop() {\n var _a2;\n (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => t.stop());\n stream.value = void 0;\n }\n function stop() {\n _stop();\n enabled.value = false;\n }\n async function start() {\n await _start();\n if (stream.value)\n enabled.value = true;\n return stream.value;\n }\n watch(enabled, (v) => {\n if (v)\n _start();\n else\n _stop();\n }, { immediate: true });\n return {\n isSupported,\n stream,\n start,\n stop,\n enabled\n };\n}\n\nfunction useDocumentVisibility({ document = defaultDocument } = {}) {\n if (!document)\n return ref(\"visible\");\n const visibility = ref(document.visibilityState);\n useEventListener(document, \"visibilitychange\", () => {\n visibility.value = document.visibilityState;\n });\n return visibility;\n}\n\nvar __defProp$f = Object.defineProperty;\nvar __defProps$5 = Object.defineProperties;\nvar __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$i = Object.getOwnPropertySymbols;\nvar __hasOwnProp$i = Object.prototype.hasOwnProperty;\nvar __propIsEnum$i = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$f = (obj, key, value) => key in obj ? __defProp$f(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$f = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$i.call(b, prop))\n __defNormalProp$f(a, prop, b[prop]);\n if (__getOwnPropSymbols$i)\n for (var prop of __getOwnPropSymbols$i(b)) {\n if (__propIsEnum$i.call(b, prop))\n __defNormalProp$f(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));\nfunction useDraggable(target, options = {}) {\n var _a, _b, _c;\n const draggingElement = (_a = options.draggingElement) != null ? _a : defaultWindow;\n const draggingHandle = (_b = options.handle) != null ? _b : target;\n const position = ref((_c = resolveUnref(options.initialValue)) != null ? _c : { x: 0, y: 0 });\n const pressedDelta = ref();\n const filterEvent = (e) => {\n if (options.pointerTypes)\n return options.pointerTypes.includes(e.pointerType);\n return true;\n };\n const handleEvent = (e) => {\n if (resolveUnref(options.preventDefault))\n e.preventDefault();\n if (resolveUnref(options.stopPropagation))\n e.stopPropagation();\n };\n const start = (e) => {\n var _a2;\n if (!filterEvent(e))\n return;\n if (resolveUnref(options.exact) && e.target !== resolveUnref(target))\n return;\n const rect = resolveUnref(target).getBoundingClientRect();\n const pos = {\n x: e.clientX - rect.left,\n y: e.clientY - rect.top\n };\n if (((_a2 = options.onStart) == null ? void 0 : _a2.call(options, pos, e)) === false)\n return;\n pressedDelta.value = pos;\n handleEvent(e);\n };\n const move = (e) => {\n var _a2;\n if (!filterEvent(e))\n return;\n if (!pressedDelta.value)\n return;\n position.value = {\n x: e.clientX - pressedDelta.value.x,\n y: e.clientY - pressedDelta.value.y\n };\n (_a2 = options.onMove) == null ? void 0 : _a2.call(options, position.value, e);\n handleEvent(e);\n };\n const end = (e) => {\n var _a2;\n if (!filterEvent(e))\n return;\n if (!pressedDelta.value)\n return;\n pressedDelta.value = void 0;\n (_a2 = options.onEnd) == null ? void 0 : _a2.call(options, position.value, e);\n handleEvent(e);\n };\n if (isClient) {\n useEventListener(draggingHandle, \"pointerdown\", start, true);\n useEventListener(draggingElement, \"pointermove\", move, true);\n useEventListener(draggingElement, \"pointerup\", end, true);\n }\n return __spreadProps$5(__spreadValues$f({}, toRefs(position)), {\n position,\n isDragging: computed(() => !!pressedDelta.value),\n style: computed(() => `left:${position.value.x}px;top:${position.value.y}px;`)\n });\n}\n\nfunction useDropZone(target, onDrop) {\n const isOverDropZone = ref(false);\n let counter = 0;\n if (isClient) {\n useEventListener(target, \"dragenter\", (event) => {\n event.preventDefault();\n counter += 1;\n isOverDropZone.value = true;\n });\n useEventListener(target, \"dragover\", (event) => {\n event.preventDefault();\n });\n useEventListener(target, \"dragleave\", (event) => {\n event.preventDefault();\n counter -= 1;\n if (counter === 0)\n isOverDropZone.value = false;\n });\n useEventListener(target, \"drop\", (event) => {\n var _a, _b;\n event.preventDefault();\n counter = 0;\n isOverDropZone.value = false;\n const files = Array.from((_b = (_a = event.dataTransfer) == null ? void 0 : _a.files) != null ? _b : []);\n onDrop == null ? void 0 : onDrop(files.length === 0 ? null : files);\n });\n }\n return {\n isOverDropZone\n };\n}\n\nvar __getOwnPropSymbols$h = Object.getOwnPropertySymbols;\nvar __hasOwnProp$h = Object.prototype.hasOwnProperty;\nvar __propIsEnum$h = Object.prototype.propertyIsEnumerable;\nvar __objRest$3 = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$h.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$h)\n for (var prop of __getOwnPropSymbols$h(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$h.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction useResizeObserver(target, callback, options = {}) {\n const _a = options, { window = defaultWindow } = _a, observerOptions = __objRest$3(_a, [\"window\"]);\n let observer;\n const isSupported = useSupported(() => window && \"ResizeObserver\" in window);\n const cleanup = () => {\n if (observer) {\n observer.disconnect();\n observer = void 0;\n }\n };\n const targets = computed(() => Array.isArray(target) ? target.map((el) => unrefElement(el)) : [unrefElement(target)]);\n const stopWatch = watch(targets, (els) => {\n cleanup();\n if (isSupported.value && window) {\n observer = new ResizeObserver(callback);\n for (const _el of els)\n _el && observer.observe(_el, observerOptions);\n }\n }, { immediate: true, flush: \"post\", deep: true });\n const stop = () => {\n cleanup();\n stopWatch();\n };\n tryOnScopeDispose(stop);\n return {\n isSupported,\n stop\n };\n}\n\nfunction useElementBounding(target, options = {}) {\n const {\n reset = true,\n windowResize = true,\n windowScroll = true,\n immediate = true\n } = options;\n const height = ref(0);\n const bottom = ref(0);\n const left = ref(0);\n const right = ref(0);\n const top = ref(0);\n const width = ref(0);\n const x = ref(0);\n const y = ref(0);\n function update() {\n const el = unrefElement(target);\n if (!el) {\n if (reset) {\n height.value = 0;\n bottom.value = 0;\n left.value = 0;\n right.value = 0;\n top.value = 0;\n width.value = 0;\n x.value = 0;\n y.value = 0;\n }\n return;\n }\n const rect = el.getBoundingClientRect();\n height.value = rect.height;\n bottom.value = rect.bottom;\n left.value = rect.left;\n right.value = rect.right;\n top.value = rect.top;\n width.value = rect.width;\n x.value = rect.x;\n y.value = rect.y;\n }\n useResizeObserver(target, update);\n watch(() => unrefElement(target), (ele) => !ele && update());\n if (windowScroll)\n useEventListener(\"scroll\", update, { capture: true, passive: true });\n if (windowResize)\n useEventListener(\"resize\", update, { passive: true });\n tryOnMounted(() => {\n if (immediate)\n update();\n });\n return {\n height,\n bottom,\n left,\n right,\n top,\n width,\n x,\n y,\n update\n };\n}\n\nfunction useRafFn(fn, options = {}) {\n const {\n immediate = true,\n window = defaultWindow\n } = options;\n const isActive = ref(false);\n let previousFrameTimestamp = 0;\n let rafId = null;\n function loop(timestamp) {\n if (!isActive.value || !window)\n return;\n const delta = timestamp - previousFrameTimestamp;\n fn({ delta, timestamp });\n previousFrameTimestamp = timestamp;\n rafId = window.requestAnimationFrame(loop);\n }\n function resume() {\n if (!isActive.value && window) {\n isActive.value = true;\n rafId = window.requestAnimationFrame(loop);\n }\n }\n function pause() {\n isActive.value = false;\n if (rafId != null && window) {\n window.cancelAnimationFrame(rafId);\n rafId = null;\n }\n }\n if (immediate)\n resume();\n tryOnScopeDispose(pause);\n return {\n isActive: readonly(isActive),\n pause,\n resume\n };\n}\n\nvar __defProp$e = Object.defineProperty;\nvar __getOwnPropSymbols$g = Object.getOwnPropertySymbols;\nvar __hasOwnProp$g = Object.prototype.hasOwnProperty;\nvar __propIsEnum$g = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$e = (obj, key, value) => key in obj ? __defProp$e(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$e = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$g.call(b, prop))\n __defNormalProp$e(a, prop, b[prop]);\n if (__getOwnPropSymbols$g)\n for (var prop of __getOwnPropSymbols$g(b)) {\n if (__propIsEnum$g.call(b, prop))\n __defNormalProp$e(a, prop, b[prop]);\n }\n return a;\n};\nfunction useElementByPoint(options) {\n const element = ref(null);\n const { x, y, document = defaultDocument } = options;\n const controls = useRafFn(() => {\n element.value = (document == null ? void 0 : document.elementFromPoint(resolveUnref(x), resolveUnref(y))) || null;\n });\n return __spreadValues$e({\n element\n }, controls);\n}\n\nfunction useElementHover(el, options = {}) {\n const {\n delayEnter = 0,\n delayLeave = 0,\n window = defaultWindow\n } = options;\n const isHovered = ref(false);\n let timer;\n const toggle = (entering) => {\n const delay = entering ? delayEnter : delayLeave;\n if (timer) {\n clearTimeout(timer);\n timer = void 0;\n }\n if (delay)\n timer = setTimeout(() => isHovered.value = entering, delay);\n else\n isHovered.value = entering;\n };\n if (!window)\n return isHovered;\n useEventListener(el, \"mouseenter\", () => toggle(true), { passive: true });\n useEventListener(el, \"mouseleave\", () => toggle(false), { passive: true });\n return isHovered;\n}\n\nfunction useElementSize(target, initialSize = { width: 0, height: 0 }, options = {}) {\n const { window = defaultWindow, box = \"content-box\" } = options;\n const isSVG = computed(() => {\n var _a, _b;\n return (_b = (_a = unrefElement(target)) == null ? void 0 : _a.namespaceURI) == null ? void 0 : _b.includes(\"svg\");\n });\n const width = ref(initialSize.width);\n const height = ref(initialSize.height);\n useResizeObserver(target, ([entry]) => {\n const boxSize = box === \"border-box\" ? entry.borderBoxSize : box === \"content-box\" ? entry.contentBoxSize : entry.devicePixelContentBoxSize;\n if (window && isSVG.value) {\n const $elem = unrefElement(target);\n if ($elem) {\n const styles = window.getComputedStyle($elem);\n width.value = parseFloat(styles.width);\n height.value = parseFloat(styles.height);\n }\n } else {\n if (boxSize) {\n const formatBoxSize = Array.isArray(boxSize) ? boxSize : [boxSize];\n width.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0);\n height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0);\n } else {\n width.value = entry.contentRect.width;\n height.value = entry.contentRect.height;\n }\n }\n }, options);\n watch(() => unrefElement(target), (ele) => {\n width.value = ele ? initialSize.width : 0;\n height.value = ele ? initialSize.height : 0;\n });\n return {\n width,\n height\n };\n}\n\nfunction useIntersectionObserver(target, callback, options = {}) {\n const {\n root,\n rootMargin = \"0px\",\n threshold = 0.1,\n window = defaultWindow\n } = options;\n const isSupported = useSupported(() => window && \"IntersectionObserver\" in window);\n let cleanup = noop;\n const stopWatch = isSupported.value ? watch(() => ({\n el: unrefElement(target),\n root: unrefElement(root)\n }), ({ el, root: root2 }) => {\n cleanup();\n if (!el)\n return;\n const observer = new IntersectionObserver(callback, {\n root: root2,\n rootMargin,\n threshold\n });\n observer.observe(el);\n cleanup = () => {\n observer.disconnect();\n cleanup = noop;\n };\n }, { immediate: true, flush: \"post\" }) : noop;\n const stop = () => {\n cleanup();\n stopWatch();\n };\n tryOnScopeDispose(stop);\n return {\n isSupported,\n stop\n };\n}\n\nfunction useElementVisibility(element, { window = defaultWindow, scrollTarget } = {}) {\n const elementIsVisible = ref(false);\n useIntersectionObserver(element, ([{ isIntersecting }]) => {\n elementIsVisible.value = isIntersecting;\n }, {\n root: scrollTarget,\n window\n });\n return elementIsVisible;\n}\n\nconst events = new Map();\n\nfunction useEventBus(key) {\n const scope = getCurrentScope();\n function on(listener) {\n var _a;\n const listeners = events.get(key) || new Set();\n listeners.add(listener);\n events.set(key, listeners);\n const _off = () => off(listener);\n (_a = scope == null ? void 0 : scope.cleanups) == null ? void 0 : _a.push(_off);\n return _off;\n }\n function once(listener) {\n function _listener(...args) {\n off(_listener);\n listener(...args);\n }\n return on(_listener);\n }\n function off(listener) {\n const listeners = events.get(key);\n if (!listeners)\n return;\n listeners.delete(listener);\n if (!listeners.size)\n reset();\n }\n function reset() {\n events.delete(key);\n }\n function emit(event, payload) {\n var _a;\n (_a = events.get(key)) == null ? void 0 : _a.forEach((v) => v(event, payload));\n }\n return { on, once, off, emit, reset };\n}\n\nfunction useEventSource(url, events = [], options = {}) {\n const event = ref(null);\n const data = ref(null);\n const status = ref(\"CONNECTING\");\n const eventSource = ref(null);\n const error = shallowRef(null);\n const {\n withCredentials = false\n } = options;\n const close = () => {\n if (eventSource.value) {\n eventSource.value.close();\n eventSource.value = null;\n status.value = \"CLOSED\";\n }\n };\n const es = new EventSource(url, { withCredentials });\n eventSource.value = es;\n es.onopen = () => {\n status.value = \"OPEN\";\n error.value = null;\n };\n es.onerror = (e) => {\n status.value = \"CLOSED\";\n error.value = e;\n };\n es.onmessage = (e) => {\n event.value = null;\n data.value = e.data;\n };\n for (const event_name of events) {\n useEventListener(es, event_name, (e) => {\n event.value = event_name;\n data.value = e.data || null;\n });\n }\n tryOnScopeDispose(() => {\n close();\n });\n return {\n eventSource,\n event,\n data,\n status,\n error,\n close\n };\n}\n\nfunction useEyeDropper(options = {}) {\n const { initialValue = \"\" } = options;\n const isSupported = useSupported(() => typeof window !== \"undefined\" && \"EyeDropper\" in window);\n const sRGBHex = ref(initialValue);\n async function open(openOptions) {\n if (!isSupported.value)\n return;\n const eyeDropper = new window.EyeDropper();\n const result = await eyeDropper.open(openOptions);\n sRGBHex.value = result.sRGBHex;\n return result;\n }\n return { isSupported, sRGBHex, open };\n}\n\nfunction useFavicon(newIcon = null, options = {}) {\n const {\n baseUrl = \"\",\n rel = \"icon\",\n document = defaultDocument\n } = options;\n const favicon = resolveRef(newIcon);\n const applyIcon = (icon) => {\n document == null ? void 0 : document.head.querySelectorAll(`link[rel*=\"${rel}\"]`).forEach((el) => el.href = `${baseUrl}${icon}`);\n };\n watch(favicon, (i, o) => {\n if (isString(i) && i !== o)\n applyIcon(i);\n }, { immediate: true });\n return favicon;\n}\n\nvar __defProp$d = Object.defineProperty;\nvar __defProps$4 = Object.defineProperties;\nvar __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$f = Object.getOwnPropertySymbols;\nvar __hasOwnProp$f = Object.prototype.hasOwnProperty;\nvar __propIsEnum$f = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$d = (obj, key, value) => key in obj ? __defProp$d(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$d = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$f.call(b, prop))\n __defNormalProp$d(a, prop, b[prop]);\n if (__getOwnPropSymbols$f)\n for (var prop of __getOwnPropSymbols$f(b)) {\n if (__propIsEnum$f.call(b, prop))\n __defNormalProp$d(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));\nconst payloadMapping = {\n json: \"application/json\",\n text: \"text/plain\"\n};\nfunction isFetchOptions(obj) {\n return obj && containsProp(obj, \"immediate\", \"refetch\", \"initialData\", \"timeout\", \"beforeFetch\", \"afterFetch\", \"onFetchError\", \"fetch\");\n}\nfunction isAbsoluteURL(url) {\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\nfunction headersToObject(headers) {\n if (typeof Headers !== \"undefined\" && headers instanceof Headers)\n return Object.fromEntries([...headers.entries()]);\n return headers;\n}\nfunction combineCallbacks(combination, ...callbacks) {\n if (combination === \"overwrite\") {\n return async (ctx) => {\n const callback = callbacks[callbacks.length - 1];\n if (callback !== void 0)\n await callback(ctx);\n return ctx;\n };\n } else {\n return async (ctx) => {\n await callbacks.reduce((prevCallback, callback) => prevCallback.then(async () => {\n if (callback)\n ctx = __spreadValues$d(__spreadValues$d({}, ctx), await callback(ctx));\n }), Promise.resolve());\n return ctx;\n };\n }\n}\nfunction createFetch(config = {}) {\n const _combination = config.combination || \"chain\";\n const _options = config.options || {};\n const _fetchOptions = config.fetchOptions || {};\n function useFactoryFetch(url, ...args) {\n const computedUrl = computed(() => {\n const baseUrl = resolveUnref(config.baseUrl);\n const targetUrl = resolveUnref(url);\n return baseUrl && !isAbsoluteURL(targetUrl) ? joinPaths(baseUrl, targetUrl) : targetUrl;\n });\n let options = _options;\n let fetchOptions = _fetchOptions;\n if (args.length > 0) {\n if (isFetchOptions(args[0])) {\n options = __spreadProps$4(__spreadValues$d(__spreadValues$d({}, options), args[0]), {\n beforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[0].beforeFetch),\n afterFetch: combineCallbacks(_combination, _options.afterFetch, args[0].afterFetch),\n onFetchError: combineCallbacks(_combination, _options.onFetchError, args[0].onFetchError)\n });\n } else {\n fetchOptions = __spreadProps$4(__spreadValues$d(__spreadValues$d({}, fetchOptions), args[0]), {\n headers: __spreadValues$d(__spreadValues$d({}, headersToObject(fetchOptions.headers) || {}), headersToObject(args[0].headers) || {})\n });\n }\n }\n if (args.length > 1 && isFetchOptions(args[1])) {\n options = __spreadProps$4(__spreadValues$d(__spreadValues$d({}, options), args[1]), {\n beforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[1].beforeFetch),\n afterFetch: combineCallbacks(_combination, _options.afterFetch, args[1].afterFetch),\n onFetchError: combineCallbacks(_combination, _options.onFetchError, args[1].onFetchError)\n });\n }\n return useFetch(computedUrl, fetchOptions, options);\n }\n return useFactoryFetch;\n}\nfunction useFetch(url, ...args) {\n var _a;\n const supportsAbort = typeof AbortController === \"function\";\n let fetchOptions = {};\n let options = { immediate: true, refetch: false, timeout: 0 };\n const config = {\n method: \"GET\",\n type: \"text\",\n payload: void 0\n };\n if (args.length > 0) {\n if (isFetchOptions(args[0]))\n options = __spreadValues$d(__spreadValues$d({}, options), args[0]);\n else\n fetchOptions = args[0];\n }\n if (args.length > 1) {\n if (isFetchOptions(args[1]))\n options = __spreadValues$d(__spreadValues$d({}, options), args[1]);\n }\n const {\n fetch = (_a = defaultWindow) == null ? void 0 : _a.fetch,\n initialData,\n timeout\n } = options;\n const responseEvent = createEventHook();\n const errorEvent = createEventHook();\n const finallyEvent = createEventHook();\n const isFinished = ref(false);\n const isFetching = ref(false);\n const aborted = ref(false);\n const statusCode = ref(null);\n const response = shallowRef(null);\n const error = shallowRef(null);\n const data = shallowRef(initialData || null);\n const canAbort = computed(() => supportsAbort && isFetching.value);\n let controller;\n let timer;\n const abort = () => {\n if (supportsAbort) {\n controller == null ? void 0 : controller.abort();\n controller = new AbortController();\n controller.signal.onabort = () => aborted.value = true;\n fetchOptions = __spreadProps$4(__spreadValues$d({}, fetchOptions), {\n signal: controller.signal\n });\n }\n };\n const loading = (isLoading) => {\n isFetching.value = isLoading;\n isFinished.value = !isLoading;\n };\n if (timeout)\n timer = useTimeoutFn(abort, timeout, { immediate: false });\n const execute = async (throwOnFailed = false) => {\n var _a2;\n abort();\n loading(true);\n error.value = null;\n statusCode.value = null;\n aborted.value = false;\n const defaultFetchOptions = {\n method: config.method,\n headers: {}\n };\n if (config.payload) {\n const headers = headersToObject(defaultFetchOptions.headers);\n if (config.payloadType)\n headers[\"Content-Type\"] = (_a2 = payloadMapping[config.payloadType]) != null ? _a2 : config.payloadType;\n const payload = resolveUnref(config.payload);\n defaultFetchOptions.body = config.payloadType === \"json\" ? JSON.stringify(payload) : payload;\n }\n let isCanceled = false;\n const context = {\n url: resolveUnref(url),\n options: __spreadValues$d(__spreadValues$d({}, defaultFetchOptions), fetchOptions),\n cancel: () => {\n isCanceled = true;\n }\n };\n if (options.beforeFetch)\n Object.assign(context, await options.beforeFetch(context));\n if (isCanceled || !fetch) {\n loading(false);\n return Promise.resolve(null);\n }\n let responseData = null;\n if (timer)\n timer.start();\n return new Promise((resolve, reject) => {\n var _a3;\n fetch(context.url, __spreadProps$4(__spreadValues$d(__spreadValues$d({}, defaultFetchOptions), context.options), {\n headers: __spreadValues$d(__spreadValues$d({}, headersToObject(defaultFetchOptions.headers)), headersToObject((_a3 = context.options) == null ? void 0 : _a3.headers))\n })).then(async (fetchResponse) => {\n response.value = fetchResponse;\n statusCode.value = fetchResponse.status;\n responseData = await fetchResponse[config.type]();\n if (!fetchResponse.ok) {\n data.value = initialData || null;\n throw new Error(fetchResponse.statusText);\n }\n if (options.afterFetch)\n ({ data: responseData } = await options.afterFetch({ data: responseData, response: fetchResponse }));\n data.value = responseData;\n responseEvent.trigger(fetchResponse);\n return resolve(fetchResponse);\n }).catch(async (fetchError) => {\n let errorData = fetchError.message || fetchError.name;\n if (options.onFetchError)\n ({ error: errorData } = await options.onFetchError({ data: responseData, error: fetchError, response: response.value }));\n error.value = errorData;\n errorEvent.trigger(fetchError);\n if (throwOnFailed)\n return reject(fetchError);\n return resolve(null);\n }).finally(() => {\n loading(false);\n if (timer)\n timer.stop();\n finallyEvent.trigger(null);\n });\n });\n };\n const refetch = resolveRef(options.refetch);\n watch([\n refetch,\n resolveRef(url)\n ], ([refetch2]) => refetch2 && execute(), { deep: true });\n const shell = {\n isFinished,\n statusCode,\n response,\n error,\n data,\n isFetching,\n canAbort,\n aborted,\n abort,\n execute,\n onFetchResponse: responseEvent.on,\n onFetchError: errorEvent.on,\n onFetchFinally: finallyEvent.on,\n get: setMethod(\"GET\"),\n put: setMethod(\"PUT\"),\n post: setMethod(\"POST\"),\n delete: setMethod(\"DELETE\"),\n patch: setMethod(\"PATCH\"),\n head: setMethod(\"HEAD\"),\n options: setMethod(\"OPTIONS\"),\n json: setType(\"json\"),\n text: setType(\"text\"),\n blob: setType(\"blob\"),\n arrayBuffer: setType(\"arrayBuffer\"),\n formData: setType(\"formData\")\n };\n function setMethod(method) {\n return (payload, payloadType) => {\n if (!isFetching.value) {\n config.method = method;\n config.payload = payload;\n config.payloadType = payloadType;\n if (isRef(config.payload)) {\n watch([\n refetch,\n resolveRef(config.payload)\n ], ([refetch2]) => refetch2 && execute(), { deep: true });\n }\n const rawPayload = resolveUnref(config.payload);\n if (!payloadType && rawPayload && Object.getPrototypeOf(rawPayload) === Object.prototype && !(rawPayload instanceof FormData))\n config.payloadType = \"json\";\n return __spreadProps$4(__spreadValues$d({}, shell), {\n then(onFulfilled, onRejected) {\n return waitUntilFinished().then(onFulfilled, onRejected);\n }\n });\n }\n return void 0;\n };\n }\n function waitUntilFinished() {\n return new Promise((resolve, reject) => {\n until(isFinished).toBe(true).then(() => resolve(shell)).catch((error2) => reject(error2));\n });\n }\n function setType(type) {\n return () => {\n if (!isFetching.value) {\n config.type = type;\n return __spreadProps$4(__spreadValues$d({}, shell), {\n then(onFulfilled, onRejected) {\n return waitUntilFinished().then(onFulfilled, onRejected);\n }\n });\n }\n return void 0;\n };\n }\n if (options.immediate)\n setTimeout(execute, 0);\n return __spreadProps$4(__spreadValues$d({}, shell), {\n then(onFulfilled, onRejected) {\n return waitUntilFinished().then(onFulfilled, onRejected);\n }\n });\n}\nfunction joinPaths(start, end) {\n if (!start.endsWith(\"/\") && !end.startsWith(\"/\"))\n return `${start}/${end}`;\n return `${start}${end}`;\n}\n\nvar __defProp$c = Object.defineProperty;\nvar __getOwnPropSymbols$e = Object.getOwnPropertySymbols;\nvar __hasOwnProp$e = Object.prototype.hasOwnProperty;\nvar __propIsEnum$e = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$c = (obj, key, value) => key in obj ? __defProp$c(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$c = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$e.call(b, prop))\n __defNormalProp$c(a, prop, b[prop]);\n if (__getOwnPropSymbols$e)\n for (var prop of __getOwnPropSymbols$e(b)) {\n if (__propIsEnum$e.call(b, prop))\n __defNormalProp$c(a, prop, b[prop]);\n }\n return a;\n};\nconst DEFAULT_OPTIONS = {\n multiple: true,\n accept: \"*\"\n};\nfunction useFileDialog(options = {}) {\n const {\n document = defaultDocument\n } = options;\n const files = ref(null);\n const { on: onChange, trigger } = createEventHook();\n let input;\n if (document) {\n input = document.createElement(\"input\");\n input.type = \"file\";\n input.onchange = (event) => {\n const result = event.target;\n files.value = result.files;\n trigger(files.value);\n };\n }\n const open = (localOptions) => {\n if (!input)\n return;\n const _options = __spreadValues$c(__spreadValues$c(__spreadValues$c({}, DEFAULT_OPTIONS), options), localOptions);\n input.multiple = _options.multiple;\n input.accept = _options.accept;\n if (hasOwn(_options, \"capture\"))\n input.capture = _options.capture;\n input.click();\n };\n const reset = () => {\n files.value = null;\n if (input)\n input.value = \"\";\n };\n return {\n files: readonly(files),\n open,\n reset,\n onChange\n };\n}\n\nvar __defProp$b = Object.defineProperty;\nvar __getOwnPropSymbols$d = Object.getOwnPropertySymbols;\nvar __hasOwnProp$d = Object.prototype.hasOwnProperty;\nvar __propIsEnum$d = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$b = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$d.call(b, prop))\n __defNormalProp$b(a, prop, b[prop]);\n if (__getOwnPropSymbols$d)\n for (var prop of __getOwnPropSymbols$d(b)) {\n if (__propIsEnum$d.call(b, prop))\n __defNormalProp$b(a, prop, b[prop]);\n }\n return a;\n};\nfunction useFileSystemAccess(options = {}) {\n const {\n window: _window = defaultWindow,\n dataType = \"Text\"\n } = unref(options);\n const window = _window;\n const isSupported = useSupported(() => window && \"showSaveFilePicker\" in window && \"showOpenFilePicker\" in window);\n const fileHandle = ref();\n const data = ref();\n const file = ref();\n const fileName = computed(() => {\n var _a, _b;\n return (_b = (_a = file.value) == null ? void 0 : _a.name) != null ? _b : \"\";\n });\n const fileMIME = computed(() => {\n var _a, _b;\n return (_b = (_a = file.value) == null ? void 0 : _a.type) != null ? _b : \"\";\n });\n const fileSize = computed(() => {\n var _a, _b;\n return (_b = (_a = file.value) == null ? void 0 : _a.size) != null ? _b : 0;\n });\n const fileLastModified = computed(() => {\n var _a, _b;\n return (_b = (_a = file.value) == null ? void 0 : _a.lastModified) != null ? _b : 0;\n });\n async function open(_options = {}) {\n if (!isSupported.value)\n return;\n const [handle] = await window.showOpenFilePicker(__spreadValues$b(__spreadValues$b({}, unref(options)), _options));\n fileHandle.value = handle;\n await updateFile();\n await updateData();\n }\n async function create(_options = {}) {\n if (!isSupported.value)\n return;\n fileHandle.value = await window.showSaveFilePicker(__spreadValues$b(__spreadValues$b({}, unref(options)), _options));\n data.value = void 0;\n await updateFile();\n await updateData();\n }\n async function save(_options = {}) {\n if (!isSupported.value)\n return;\n if (!fileHandle.value)\n return saveAs(_options);\n if (data.value) {\n const writableStream = await fileHandle.value.createWritable();\n await writableStream.write(data.value);\n await writableStream.close();\n }\n await updateFile();\n }\n async function saveAs(_options = {}) {\n if (!isSupported.value)\n return;\n fileHandle.value = await window.showSaveFilePicker(__spreadValues$b(__spreadValues$b({}, unref(options)), _options));\n if (data.value) {\n const writableStream = await fileHandle.value.createWritable();\n await writableStream.write(data.value);\n await writableStream.close();\n }\n await updateFile();\n }\n async function updateFile() {\n var _a;\n file.value = await ((_a = fileHandle.value) == null ? void 0 : _a.getFile());\n }\n async function updateData() {\n var _a, _b;\n if (unref(dataType) === \"Text\")\n data.value = await ((_a = file.value) == null ? void 0 : _a.text());\n if (unref(dataType) === \"ArrayBuffer\")\n data.value = await ((_b = file.value) == null ? void 0 : _b.arrayBuffer());\n if (unref(dataType) === \"Blob\")\n data.value = file.value;\n }\n watch(() => unref(dataType), updateData);\n return {\n isSupported,\n data,\n file,\n fileName,\n fileMIME,\n fileSize,\n fileLastModified,\n open,\n create,\n save,\n saveAs,\n updateData\n };\n}\n\nfunction useFocus(target, options = {}) {\n const { initialValue = false } = options;\n const innerFocused = ref(false);\n const targetElement = computed(() => unrefElement(target));\n useEventListener(targetElement, \"focus\", () => innerFocused.value = true);\n useEventListener(targetElement, \"blur\", () => innerFocused.value = false);\n const focused = computed({\n get: () => innerFocused.value,\n set(value) {\n var _a, _b;\n if (!value && innerFocused.value)\n (_a = targetElement.value) == null ? void 0 : _a.blur();\n else if (value && !innerFocused.value)\n (_b = targetElement.value) == null ? void 0 : _b.focus();\n }\n });\n watch(targetElement, () => {\n focused.value = initialValue;\n }, { immediate: true, flush: \"post\" });\n return { focused };\n}\n\nfunction useFocusWithin(target, options = {}) {\n const activeElement = useActiveElement(options);\n const targetElement = computed(() => unrefElement(target));\n const focused = computed(() => targetElement.value && activeElement.value ? targetElement.value.contains(activeElement.value) : false);\n return { focused };\n}\n\nfunction useFps(options) {\n var _a;\n const fps = ref(0);\n if (typeof performance === \"undefined\")\n return fps;\n const every = (_a = options == null ? void 0 : options.every) != null ? _a : 10;\n let last = performance.now();\n let ticks = 0;\n useRafFn(() => {\n ticks += 1;\n if (ticks >= every) {\n const now = performance.now();\n const diff = now - last;\n fps.value = Math.round(1e3 / (diff / ticks));\n last = now;\n ticks = 0;\n }\n });\n return fps;\n}\n\nconst functionsMap = [\n [\n \"requestFullscreen\",\n \"exitFullscreen\",\n \"fullscreenElement\",\n \"fullscreenEnabled\",\n \"fullscreenchange\",\n \"fullscreenerror\"\n ],\n [\n \"webkitRequestFullscreen\",\n \"webkitExitFullscreen\",\n \"webkitFullscreenElement\",\n \"webkitFullscreenEnabled\",\n \"webkitfullscreenchange\",\n \"webkitfullscreenerror\"\n ],\n [\n \"webkitEnterFullscreen\",\n \"webkitExitFullscreen\",\n \"webkitFullscreenElement\",\n \"webkitFullscreenEnabled\",\n \"webkitfullscreenchange\",\n \"webkitfullscreenerror\"\n ],\n [\n \"webkitRequestFullScreen\",\n \"webkitCancelFullScreen\",\n \"webkitCurrentFullScreenElement\",\n \"webkitCancelFullScreen\",\n \"webkitfullscreenchange\",\n \"webkitfullscreenerror\"\n ],\n [\n \"mozRequestFullScreen\",\n \"mozCancelFullScreen\",\n \"mozFullScreenElement\",\n \"mozFullScreenEnabled\",\n \"mozfullscreenchange\",\n \"mozfullscreenerror\"\n ],\n [\n \"msRequestFullscreen\",\n \"msExitFullscreen\",\n \"msFullscreenElement\",\n \"msFullscreenEnabled\",\n \"MSFullscreenChange\",\n \"MSFullscreenError\"\n ]\n];\nfunction useFullscreen(target, options = {}) {\n const { document = defaultDocument, autoExit = false } = options;\n const targetRef = target || (document == null ? void 0 : document.querySelector(\"html\"));\n const isFullscreen = ref(false);\n let map = functionsMap[0];\n const isSupported = useSupported(() => {\n if (!document) {\n return false;\n } else {\n const target2 = unrefElement(targetRef);\n for (const m of functionsMap) {\n if (m[1] in document || target2 && m[0] in target2) {\n map = m;\n return true;\n }\n }\n }\n return false;\n });\n const [REQUEST, EXIT, ELEMENT, , EVENT] = map;\n async function exit() {\n if (!isSupported.value)\n return;\n if (document == null ? void 0 : document[ELEMENT])\n await document[EXIT]();\n isFullscreen.value = false;\n }\n async function enter() {\n if (!isSupported.value)\n return;\n await exit();\n const target2 = unrefElement(targetRef);\n if (target2) {\n await target2[REQUEST]();\n isFullscreen.value = true;\n }\n }\n async function toggle() {\n if (isFullscreen.value)\n await exit();\n else\n await enter();\n }\n if (document) {\n useEventListener(document, EVENT, () => {\n isFullscreen.value = !!(document == null ? void 0 : document[ELEMENT]);\n }, false);\n }\n if (autoExit)\n tryOnScopeDispose(exit);\n return {\n isSupported,\n isFullscreen,\n enter,\n exit,\n toggle\n };\n}\n\nfunction mapGamepadToXbox360Controller(gamepad) {\n return computed(() => {\n if (gamepad.value) {\n return {\n buttons: {\n a: gamepad.value.buttons[0],\n b: gamepad.value.buttons[1],\n x: gamepad.value.buttons[2],\n y: gamepad.value.buttons[3]\n },\n bumper: {\n left: gamepad.value.buttons[4],\n right: gamepad.value.buttons[5]\n },\n triggers: {\n left: gamepad.value.buttons[6],\n right: gamepad.value.buttons[7]\n },\n stick: {\n left: {\n horizontal: gamepad.value.axes[0],\n vertical: gamepad.value.axes[1],\n button: gamepad.value.buttons[10]\n },\n right: {\n horizontal: gamepad.value.axes[2],\n vertical: gamepad.value.axes[3],\n button: gamepad.value.buttons[11]\n }\n },\n dpad: {\n up: gamepad.value.buttons[12],\n down: gamepad.value.buttons[13],\n left: gamepad.value.buttons[14],\n right: gamepad.value.buttons[15]\n },\n back: gamepad.value.buttons[8],\n start: gamepad.value.buttons[9]\n };\n }\n return null;\n });\n}\nfunction useGamepad(options = {}) {\n const {\n navigator = defaultNavigator\n } = options;\n const isSupported = useSupported(() => navigator && \"getGamepads\" in navigator);\n const gamepads = ref([]);\n const onConnectedHook = createEventHook();\n const onDisconnectedHook = createEventHook();\n const stateFromGamepad = (gamepad) => {\n const hapticActuators = [];\n const vibrationActuator = \"vibrationActuator\" in gamepad ? gamepad.vibrationActuator : null;\n if (vibrationActuator)\n hapticActuators.push(vibrationActuator);\n if (gamepad.hapticActuators)\n hapticActuators.push(...gamepad.hapticActuators);\n return {\n id: gamepad.id,\n hapticActuators,\n index: gamepad.index,\n mapping: gamepad.mapping,\n connected: gamepad.connected,\n timestamp: gamepad.timestamp,\n axes: gamepad.axes.map((axes) => axes),\n buttons: gamepad.buttons.map((button) => ({ pressed: button.pressed, touched: button.touched, value: button.value }))\n };\n };\n const updateGamepadState = () => {\n const _gamepads = (navigator == null ? void 0 : navigator.getGamepads()) || [];\n for (let i = 0; i < _gamepads.length; ++i) {\n const gamepad = _gamepads[i];\n if (gamepad) {\n const index = gamepads.value.findIndex(({ index: index2 }) => index2 === gamepad.index);\n if (index > -1)\n gamepads.value[index] = stateFromGamepad(gamepad);\n }\n }\n };\n const { isActive, pause, resume } = useRafFn(updateGamepadState);\n const onGamepadConnected = (gamepad) => {\n if (!gamepads.value.some(({ index }) => index === gamepad.index)) {\n gamepads.value.push(stateFromGamepad(gamepad));\n onConnectedHook.trigger(gamepad.index);\n }\n resume();\n };\n const onGamepadDisconnected = (gamepad) => {\n gamepads.value = gamepads.value.filter((x) => x.index !== gamepad.index);\n onDisconnectedHook.trigger(gamepad.index);\n };\n useEventListener(\"gamepadconnected\", (e) => onGamepadConnected(e.gamepad));\n useEventListener(\"gamepaddisconnected\", (e) => onGamepadDisconnected(e.gamepad));\n tryOnMounted(() => {\n const _gamepads = (navigator == null ? void 0 : navigator.getGamepads()) || [];\n if (_gamepads) {\n for (let i = 0; i < _gamepads.length; ++i) {\n const gamepad = _gamepads[i];\n if (gamepad)\n onGamepadConnected(gamepad);\n }\n }\n });\n pause();\n return {\n isSupported,\n onConnected: onConnectedHook.on,\n onDisconnected: onDisconnectedHook.on,\n gamepads,\n pause,\n resume,\n isActive\n };\n}\n\nfunction useGeolocation(options = {}) {\n const {\n enableHighAccuracy = true,\n maximumAge = 3e4,\n timeout = 27e3,\n navigator = defaultNavigator,\n immediate = true\n } = options;\n const isSupported = useSupported(() => navigator && \"geolocation\" in navigator);\n const locatedAt = ref(null);\n const error = shallowRef(null);\n const coords = ref({\n accuracy: 0,\n latitude: Infinity,\n longitude: Infinity,\n altitude: null,\n altitudeAccuracy: null,\n heading: null,\n speed: null\n });\n function updatePosition(position) {\n locatedAt.value = position.timestamp;\n coords.value = position.coords;\n error.value = null;\n }\n let watcher;\n function resume() {\n if (isSupported.value) {\n watcher = navigator.geolocation.watchPosition(updatePosition, (err) => error.value = err, {\n enableHighAccuracy,\n maximumAge,\n timeout\n });\n }\n }\n if (immediate)\n resume();\n function pause() {\n if (watcher && navigator)\n navigator.geolocation.clearWatch(watcher);\n }\n tryOnScopeDispose(() => {\n pause();\n });\n return {\n isSupported,\n coords,\n locatedAt,\n error,\n resume,\n pause\n };\n}\n\nconst defaultEvents$1 = [\"mousemove\", \"mousedown\", \"resize\", \"keydown\", \"touchstart\", \"wheel\"];\nconst oneMinute = 6e4;\nfunction useIdle(timeout = oneMinute, options = {}) {\n const {\n initialState = false,\n listenForVisibilityChange = true,\n events = defaultEvents$1,\n window = defaultWindow,\n eventFilter = throttleFilter(50)\n } = options;\n const idle = ref(initialState);\n const lastActive = ref(timestamp());\n let timer;\n const reset = () => {\n idle.value = false;\n clearTimeout(timer);\n timer = setTimeout(() => idle.value = true, timeout);\n };\n const onEvent = createFilterWrapper(eventFilter, () => {\n lastActive.value = timestamp();\n reset();\n });\n if (window) {\n const document = window.document;\n for (const event of events)\n useEventListener(window, event, onEvent, { passive: true });\n if (listenForVisibilityChange) {\n useEventListener(document, \"visibilitychange\", () => {\n if (!document.hidden)\n onEvent();\n });\n }\n reset();\n }\n return {\n idle,\n lastActive,\n reset\n };\n}\n\nvar __defProp$a = Object.defineProperty;\nvar __getOwnPropSymbols$c = Object.getOwnPropertySymbols;\nvar __hasOwnProp$c = Object.prototype.hasOwnProperty;\nvar __propIsEnum$c = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$a = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$c.call(b, prop))\n __defNormalProp$a(a, prop, b[prop]);\n if (__getOwnPropSymbols$c)\n for (var prop of __getOwnPropSymbols$c(b)) {\n if (__propIsEnum$c.call(b, prop))\n __defNormalProp$a(a, prop, b[prop]);\n }\n return a;\n};\nasync function loadImage(options) {\n return new Promise((resolve, reject) => {\n const img = new Image();\n const { src, srcset, sizes } = options;\n img.src = src;\n if (srcset)\n img.srcset = srcset;\n if (sizes)\n img.sizes = sizes;\n img.onload = () => resolve(img);\n img.onerror = reject;\n });\n}\nconst useImage = (options, asyncStateOptions = {}) => {\n const state = useAsyncState(() => loadImage(resolveUnref(options)), void 0, __spreadValues$a({\n resetOnExecute: true\n }, asyncStateOptions));\n watch(() => resolveUnref(options), () => state.execute(asyncStateOptions.delay), { deep: true });\n return state;\n};\n\nconst ARRIVED_STATE_THRESHOLD_PIXELS = 1;\nfunction useScroll(element, options = {}) {\n const {\n throttle = 0,\n idle = 200,\n onStop = noop,\n onScroll = noop,\n offset = {\n left: 0,\n right: 0,\n top: 0,\n bottom: 0\n },\n eventListenerOptions = {\n capture: false,\n passive: true\n },\n behavior = \"auto\"\n } = options;\n const internalX = ref(0);\n const internalY = ref(0);\n const x = computed({\n get() {\n return internalX.value;\n },\n set(x2) {\n scrollTo(x2, void 0);\n }\n });\n const y = computed({\n get() {\n return internalY.value;\n },\n set(y2) {\n scrollTo(void 0, y2);\n }\n });\n function scrollTo(_x, _y) {\n var _a, _b, _c;\n const _element = resolveUnref(element);\n if (!_element)\n return;\n (_c = _element instanceof Document ? document.body : _element) == null ? void 0 : _c.scrollTo({\n top: (_a = resolveUnref(_y)) != null ? _a : y.value,\n left: (_b = resolveUnref(_x)) != null ? _b : x.value,\n behavior: resolveUnref(behavior)\n });\n }\n const isScrolling = ref(false);\n const arrivedState = reactive({\n left: true,\n right: false,\n top: true,\n bottom: false\n });\n const directions = reactive({\n left: false,\n right: false,\n top: false,\n bottom: false\n });\n const onScrollEnd = (e) => {\n if (!isScrolling.value)\n return;\n isScrolling.value = false;\n directions.left = false;\n directions.right = false;\n directions.top = false;\n directions.bottom = false;\n onStop(e);\n };\n const onScrollEndDebounced = useDebounceFn(onScrollEnd, throttle + idle);\n const onScrollHandler = (e) => {\n const eventTarget = e.target === document ? e.target.documentElement : e.target;\n const scrollLeft = eventTarget.scrollLeft;\n directions.left = scrollLeft < internalX.value;\n directions.right = scrollLeft > internalY.value;\n arrivedState.left = scrollLeft <= 0 + (offset.left || 0);\n arrivedState.right = scrollLeft + eventTarget.clientWidth >= eventTarget.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;\n internalX.value = scrollLeft;\n let scrollTop = eventTarget.scrollTop;\n if (e.target === document && !scrollTop)\n scrollTop = document.body.scrollTop;\n directions.top = scrollTop < internalY.value;\n directions.bottom = scrollTop > internalY.value;\n arrivedState.top = scrollTop <= 0 + (offset.top || 0);\n arrivedState.bottom = scrollTop + eventTarget.clientHeight >= eventTarget.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;\n internalY.value = scrollTop;\n isScrolling.value = true;\n onScrollEndDebounced(e);\n onScroll(e);\n };\n useEventListener(element, \"scroll\", throttle ? useThrottleFn(onScrollHandler, throttle, true, false) : onScrollHandler, eventListenerOptions);\n useEventListener(element, \"scrollend\", onScrollEnd, eventListenerOptions);\n return {\n x,\n y,\n isScrolling,\n arrivedState,\n directions\n };\n}\n\nvar __defProp$9 = Object.defineProperty;\nvar __defProps$3 = Object.defineProperties;\nvar __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$b = Object.getOwnPropertySymbols;\nvar __hasOwnProp$b = Object.prototype.hasOwnProperty;\nvar __propIsEnum$b = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$9 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$b.call(b, prop))\n __defNormalProp$9(a, prop, b[prop]);\n if (__getOwnPropSymbols$b)\n for (var prop of __getOwnPropSymbols$b(b)) {\n if (__propIsEnum$b.call(b, prop))\n __defNormalProp$9(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));\nfunction useInfiniteScroll(element, onLoadMore, options = {}) {\n var _a, _b;\n const direction = (_a = options.direction) != null ? _a : \"bottom\";\n const state = reactive(useScroll(element, __spreadProps$3(__spreadValues$9({}, options), {\n offset: __spreadValues$9({\n [direction]: (_b = options.distance) != null ? _b : 0\n }, options.offset)\n })));\n watch(() => state.arrivedState[direction], async (v) => {\n var _a2, _b2;\n if (v) {\n const elem = resolveUnref(element);\n const previous = {\n height: (_a2 = elem == null ? void 0 : elem.scrollHeight) != null ? _a2 : 0,\n width: (_b2 = elem == null ? void 0 : elem.scrollWidth) != null ? _b2 : 0\n };\n await onLoadMore(state);\n if (options.preserveScrollPosition && elem) {\n nextTick(() => {\n elem.scrollTo({\n top: elem.scrollHeight - previous.height,\n left: elem.scrollWidth - previous.width\n });\n });\n }\n }\n });\n}\n\nconst defaultEvents = [\"mousedown\", \"mouseup\", \"keydown\", \"keyup\"];\nfunction useKeyModifier(modifier, options = {}) {\n const {\n events = defaultEvents,\n document = defaultDocument,\n initial = null\n } = options;\n const state = ref(initial);\n if (document) {\n events.forEach((listenerEvent) => {\n useEventListener(document, listenerEvent, (evt) => {\n if (typeof evt.getModifierState === \"function\")\n state.value = evt.getModifierState(modifier);\n });\n });\n }\n return state;\n}\n\nfunction useLocalStorage(key, initialValue, options = {}) {\n const { window = defaultWindow } = options;\n return useStorage(key, initialValue, window == null ? void 0 : window.localStorage, options);\n}\n\nconst DefaultMagicKeysAliasMap = {\n ctrl: \"control\",\n command: \"meta\",\n cmd: \"meta\",\n option: \"alt\",\n up: \"arrowup\",\n down: \"arrowdown\",\n left: \"arrowleft\",\n right: \"arrowright\"\n};\n\nfunction useMagicKeys(options = {}) {\n const {\n reactive: useReactive = false,\n target = defaultWindow,\n aliasMap = DefaultMagicKeysAliasMap,\n passive = true,\n onEventFired = noop\n } = options;\n const current = reactive(new Set());\n const obj = {\n toJSON() {\n return {};\n },\n current\n };\n const refs = useReactive ? reactive(obj) : obj;\n const metaDeps = new Set();\n const usedKeys = new Set();\n function setRefs(key, value) {\n if (key in refs) {\n if (useReactive)\n refs[key] = value;\n else\n refs[key].value = value;\n }\n }\n function reset() {\n current.clear();\n for (const key of usedKeys)\n setRefs(key, false);\n }\n function updateRefs(e, value) {\n var _a, _b;\n const key = (_a = e.key) == null ? void 0 : _a.toLowerCase();\n const code = (_b = e.code) == null ? void 0 : _b.toLowerCase();\n const values = [code, key].filter(Boolean);\n if (key) {\n if (value)\n current.add(key);\n else\n current.delete(key);\n }\n for (const key2 of values) {\n usedKeys.add(key2);\n setRefs(key2, value);\n }\n if (key === \"meta\" && !value) {\n metaDeps.forEach((key2) => {\n current.delete(key2);\n setRefs(key2, false);\n });\n metaDeps.clear();\n } else if (typeof e.getModifierState === \"function\" && e.getModifierState(\"Meta\") && value) {\n [...current, ...values].forEach((key2) => metaDeps.add(key2));\n }\n }\n useEventListener(target, \"keydown\", (e) => {\n updateRefs(e, true);\n return onEventFired(e);\n }, { passive });\n useEventListener(target, \"keyup\", (e) => {\n updateRefs(e, false);\n return onEventFired(e);\n }, { passive });\n useEventListener(\"blur\", reset, { passive: true });\n useEventListener(\"focus\", reset, { passive: true });\n const proxy = new Proxy(refs, {\n get(target2, prop, rec) {\n if (typeof prop !== \"string\")\n return Reflect.get(target2, prop, rec);\n prop = prop.toLowerCase();\n if (prop in aliasMap)\n prop = aliasMap[prop];\n if (!(prop in refs)) {\n if (/[+_-]/.test(prop)) {\n const keys = prop.split(/[+_-]/g).map((i) => i.trim());\n refs[prop] = computed(() => keys.every((key) => unref(proxy[key])));\n } else {\n refs[prop] = ref(false);\n }\n }\n const r = Reflect.get(target2, prop, rec);\n return useReactive ? unref(r) : r;\n }\n });\n return proxy;\n}\n\nvar __defProp$8 = Object.defineProperty;\nvar __getOwnPropSymbols$a = Object.getOwnPropertySymbols;\nvar __hasOwnProp$a = Object.prototype.hasOwnProperty;\nvar __propIsEnum$a = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$8 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$a.call(b, prop))\n __defNormalProp$8(a, prop, b[prop]);\n if (__getOwnPropSymbols$a)\n for (var prop of __getOwnPropSymbols$a(b)) {\n if (__propIsEnum$a.call(b, prop))\n __defNormalProp$8(a, prop, b[prop]);\n }\n return a;\n};\nfunction usingElRef(source, cb) {\n if (resolveUnref(source))\n cb(resolveUnref(source));\n}\nfunction timeRangeToArray(timeRanges) {\n let ranges = [];\n for (let i = 0; i < timeRanges.length; ++i)\n ranges = [...ranges, [timeRanges.start(i), timeRanges.end(i)]];\n return ranges;\n}\nfunction tracksToArray(tracks) {\n return Array.from(tracks).map(({ label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }, id) => ({ id, label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }));\n}\nconst defaultOptions = {\n src: \"\",\n tracks: []\n};\nfunction useMediaControls(target, options = {}) {\n options = __spreadValues$8(__spreadValues$8({}, defaultOptions), options);\n const {\n document = defaultDocument\n } = options;\n const currentTime = ref(0);\n const duration = ref(0);\n const seeking = ref(false);\n const volume = ref(1);\n const waiting = ref(false);\n const ended = ref(false);\n const playing = ref(false);\n const rate = ref(1);\n const stalled = ref(false);\n const buffered = ref([]);\n const tracks = ref([]);\n const selectedTrack = ref(-1);\n const isPictureInPicture = ref(false);\n const muted = ref(false);\n const supportsPictureInPicture = document && \"pictureInPictureEnabled\" in document;\n const sourceErrorEvent = createEventHook();\n const disableTrack = (track) => {\n usingElRef(target, (el) => {\n if (track) {\n const id = isNumber(track) ? track : track.id;\n el.textTracks[id].mode = \"disabled\";\n } else {\n for (let i = 0; i < el.textTracks.length; ++i)\n el.textTracks[i].mode = \"disabled\";\n }\n selectedTrack.value = -1;\n });\n };\n const enableTrack = (track, disableTracks = true) => {\n usingElRef(target, (el) => {\n const id = isNumber(track) ? track : track.id;\n if (disableTracks)\n disableTrack();\n el.textTracks[id].mode = \"showing\";\n selectedTrack.value = id;\n });\n };\n const togglePictureInPicture = () => {\n return new Promise((resolve, reject) => {\n usingElRef(target, async (el) => {\n if (supportsPictureInPicture) {\n if (!isPictureInPicture.value) {\n el.requestPictureInPicture().then(resolve).catch(reject);\n } else {\n document.exitPictureInPicture().then(resolve).catch(reject);\n }\n }\n });\n });\n };\n watchEffect(() => {\n if (!document)\n return;\n const el = resolveUnref(target);\n if (!el)\n return;\n const src = resolveUnref(options.src);\n let sources = [];\n if (!src)\n return;\n if (isString(src))\n sources = [{ src }];\n else if (Array.isArray(src))\n sources = src;\n else if (isObject(src))\n sources = [src];\n el.querySelectorAll(\"source\").forEach((e) => {\n e.removeEventListener(\"error\", sourceErrorEvent.trigger);\n e.remove();\n });\n sources.forEach(({ src: src2, type }) => {\n const source = document.createElement(\"source\");\n source.setAttribute(\"src\", src2);\n source.setAttribute(\"type\", type || \"\");\n source.addEventListener(\"error\", sourceErrorEvent.trigger);\n el.appendChild(source);\n });\n el.load();\n });\n tryOnScopeDispose(() => {\n const el = resolveUnref(target);\n if (!el)\n return;\n el.querySelectorAll(\"source\").forEach((e) => e.removeEventListener(\"error\", sourceErrorEvent.trigger));\n });\n watch(volume, (vol) => {\n const el = resolveUnref(target);\n if (!el)\n return;\n el.volume = vol;\n });\n watch(muted, (mute) => {\n const el = resolveUnref(target);\n if (!el)\n return;\n el.muted = mute;\n });\n watch(rate, (rate2) => {\n const el = resolveUnref(target);\n if (!el)\n return;\n el.playbackRate = rate2;\n });\n watchEffect(() => {\n if (!document)\n return;\n const textTracks = resolveUnref(options.tracks);\n const el = resolveUnref(target);\n if (!textTracks || !textTracks.length || !el)\n return;\n el.querySelectorAll(\"track\").forEach((e) => e.remove());\n textTracks.forEach(({ default: isDefault, kind, label, src, srcLang }, i) => {\n const track = document.createElement(\"track\");\n track.default = isDefault || false;\n track.kind = kind;\n track.label = label;\n track.src = src;\n track.srclang = srcLang;\n if (track.default)\n selectedTrack.value = i;\n el.appendChild(track);\n });\n });\n const { ignoreUpdates: ignoreCurrentTimeUpdates } = watchIgnorable(currentTime, (time) => {\n const el = resolveUnref(target);\n if (!el)\n return;\n el.currentTime = time;\n });\n const { ignoreUpdates: ignorePlayingUpdates } = watchIgnorable(playing, (isPlaying) => {\n const el = resolveUnref(target);\n if (!el)\n return;\n isPlaying ? el.play() : el.pause();\n });\n useEventListener(target, \"timeupdate\", () => ignoreCurrentTimeUpdates(() => currentTime.value = resolveUnref(target).currentTime));\n useEventListener(target, \"durationchange\", () => duration.value = resolveUnref(target).duration);\n useEventListener(target, \"progress\", () => buffered.value = timeRangeToArray(resolveUnref(target).buffered));\n useEventListener(target, \"seeking\", () => seeking.value = true);\n useEventListener(target, \"seeked\", () => seeking.value = false);\n useEventListener(target, \"waiting\", () => waiting.value = true);\n useEventListener(target, \"playing\", () => {\n waiting.value = false;\n ended.value = false;\n });\n useEventListener(target, \"ratechange\", () => rate.value = resolveUnref(target).playbackRate);\n useEventListener(target, \"stalled\", () => stalled.value = true);\n useEventListener(target, \"ended\", () => ended.value = true);\n useEventListener(target, \"pause\", () => ignorePlayingUpdates(() => playing.value = false));\n useEventListener(target, \"play\", () => ignorePlayingUpdates(() => playing.value = true));\n useEventListener(target, \"enterpictureinpicture\", () => isPictureInPicture.value = true);\n useEventListener(target, \"leavepictureinpicture\", () => isPictureInPicture.value = false);\n useEventListener(target, \"volumechange\", () => {\n const el = resolveUnref(target);\n if (!el)\n return;\n volume.value = el.volume;\n muted.value = el.muted;\n });\n const listeners = [];\n const stop = watch([target], () => {\n const el = resolveUnref(target);\n if (!el)\n return;\n stop();\n listeners[0] = useEventListener(el.textTracks, \"addtrack\", () => tracks.value = tracksToArray(el.textTracks));\n listeners[1] = useEventListener(el.textTracks, \"removetrack\", () => tracks.value = tracksToArray(el.textTracks));\n listeners[2] = useEventListener(el.textTracks, \"change\", () => tracks.value = tracksToArray(el.textTracks));\n });\n tryOnScopeDispose(() => listeners.forEach((listener) => listener()));\n return {\n currentTime,\n duration,\n waiting,\n seeking,\n ended,\n stalled,\n buffered,\n playing,\n rate,\n volume,\n muted,\n tracks,\n selectedTrack,\n enableTrack,\n disableTrack,\n supportsPictureInPicture,\n togglePictureInPicture,\n isPictureInPicture,\n onSourceError: sourceErrorEvent.on\n };\n}\n\nconst getMapVue2Compat = () => {\n const data = reactive({});\n return {\n get: (key) => data[key],\n set: (key, value) => set(data, key, value),\n has: (key) => hasOwn(data, key),\n delete: (key) => del(data, key),\n clear: () => {\n Object.keys(data).forEach((key) => {\n del(data, key);\n });\n }\n };\n};\nfunction useMemoize(resolver, options) {\n const initCache = () => {\n if (options == null ? void 0 : options.cache)\n return reactive(options.cache);\n if (isVue2)\n return getMapVue2Compat();\n return reactive(new Map());\n };\n const cache = initCache();\n const generateKey = (...args) => (options == null ? void 0 : options.getKey) ? options.getKey(...args) : JSON.stringify(args);\n const _loadData = (key, ...args) => {\n cache.set(key, resolver(...args));\n return cache.get(key);\n };\n const loadData = (...args) => _loadData(generateKey(...args), ...args);\n const deleteData = (...args) => {\n cache.delete(generateKey(...args));\n };\n const clearData = () => {\n cache.clear();\n };\n const memoized = (...args) => {\n const key = generateKey(...args);\n if (cache.has(key))\n return cache.get(key);\n return _loadData(key, ...args);\n };\n memoized.load = loadData;\n memoized.delete = deleteData;\n memoized.clear = clearData;\n memoized.generateKey = generateKey;\n memoized.cache = cache;\n return memoized;\n}\n\nfunction useMemory(options = {}) {\n const memory = ref();\n const isSupported = useSupported(() => typeof performance !== \"undefined\" && \"memory\" in performance);\n if (isSupported.value) {\n const { interval = 1e3 } = options;\n useIntervalFn(() => {\n memory.value = performance.memory;\n }, interval, { immediate: options.immediate, immediateCallback: options.immediateCallback });\n }\n return { isSupported, memory };\n}\n\nfunction useMouse(options = {}) {\n const {\n type = \"page\",\n touch = true,\n resetOnTouchEnds = false,\n initialValue = { x: 0, y: 0 },\n window = defaultWindow,\n eventFilter\n } = options;\n const x = ref(initialValue.x);\n const y = ref(initialValue.y);\n const sourceType = ref(null);\n const mouseHandler = (event) => {\n if (type === \"page\") {\n x.value = event.pageX;\n y.value = event.pageY;\n } else if (type === \"client\") {\n x.value = event.clientX;\n y.value = event.clientY;\n } else if (type === \"movement\") {\n x.value = event.movementX;\n y.value = event.movementY;\n }\n sourceType.value = \"mouse\";\n };\n const reset = () => {\n x.value = initialValue.x;\n y.value = initialValue.y;\n };\n const touchHandler = (event) => {\n if (event.touches.length > 0) {\n const touch2 = event.touches[0];\n if (type === \"page\") {\n x.value = touch2.pageX;\n y.value = touch2.pageY;\n } else if (type === \"client\") {\n x.value = touch2.clientX;\n y.value = touch2.clientY;\n }\n sourceType.value = \"touch\";\n }\n };\n const mouseHandlerWrapper = (event) => {\n return eventFilter === void 0 ? mouseHandler(event) : eventFilter(() => mouseHandler(event), {});\n };\n const touchHandlerWrapper = (event) => {\n return eventFilter === void 0 ? touchHandler(event) : eventFilter(() => touchHandler(event), {});\n };\n if (window) {\n useEventListener(window, \"mousemove\", mouseHandlerWrapper, { passive: true });\n useEventListener(window, \"dragover\", mouseHandlerWrapper, { passive: true });\n if (touch && type !== \"movement\") {\n useEventListener(window, \"touchstart\", touchHandlerWrapper, { passive: true });\n useEventListener(window, \"touchmove\", touchHandlerWrapper, { passive: true });\n if (resetOnTouchEnds)\n useEventListener(window, \"touchend\", reset, { passive: true });\n }\n }\n return {\n x,\n y,\n sourceType\n };\n}\n\nfunction useMouseInElement(target, options = {}) {\n const {\n handleOutside = true,\n window = defaultWindow\n } = options;\n const { x, y, sourceType } = useMouse(options);\n const targetRef = ref(target != null ? target : window == null ? void 0 : window.document.body);\n const elementX = ref(0);\n const elementY = ref(0);\n const elementPositionX = ref(0);\n const elementPositionY = ref(0);\n const elementHeight = ref(0);\n const elementWidth = ref(0);\n const isOutside = ref(true);\n let stop = () => {\n };\n if (window) {\n stop = watch([targetRef, x, y], () => {\n const el = unrefElement(targetRef);\n if (!el)\n return;\n const {\n left,\n top,\n width,\n height\n } = el.getBoundingClientRect();\n elementPositionX.value = left + window.pageXOffset;\n elementPositionY.value = top + window.pageYOffset;\n elementHeight.value = height;\n elementWidth.value = width;\n const elX = x.value - elementPositionX.value;\n const elY = y.value - elementPositionY.value;\n isOutside.value = width === 0 || height === 0 || elX < 0 || elY < 0 || elX > width || elY > height;\n if (handleOutside || !isOutside.value) {\n elementX.value = elX;\n elementY.value = elY;\n }\n }, { immediate: true });\n useEventListener(document, \"mouseleave\", () => {\n isOutside.value = true;\n });\n }\n return {\n x,\n y,\n sourceType,\n elementX,\n elementY,\n elementPositionX,\n elementPositionY,\n elementHeight,\n elementWidth,\n isOutside,\n stop\n };\n}\n\nfunction useMousePressed(options = {}) {\n const {\n touch = true,\n drag = true,\n initialValue = false,\n window = defaultWindow\n } = options;\n const pressed = ref(initialValue);\n const sourceType = ref(null);\n if (!window) {\n return {\n pressed,\n sourceType\n };\n }\n const onPressed = (srcType) => () => {\n pressed.value = true;\n sourceType.value = srcType;\n };\n const onReleased = () => {\n pressed.value = false;\n sourceType.value = null;\n };\n const target = computed(() => unrefElement(options.target) || window);\n useEventListener(target, \"mousedown\", onPressed(\"mouse\"), { passive: true });\n useEventListener(window, \"mouseleave\", onReleased, { passive: true });\n useEventListener(window, \"mouseup\", onReleased, { passive: true });\n if (drag) {\n useEventListener(target, \"dragstart\", onPressed(\"mouse\"), { passive: true });\n useEventListener(window, \"drop\", onReleased, { passive: true });\n useEventListener(window, \"dragend\", onReleased, { passive: true });\n }\n if (touch) {\n useEventListener(target, \"touchstart\", onPressed(\"touch\"), { passive: true });\n useEventListener(window, \"touchend\", onReleased, { passive: true });\n useEventListener(window, \"touchcancel\", onReleased, { passive: true });\n }\n return {\n pressed,\n sourceType\n };\n}\n\nvar __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$9 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$9 = Object.prototype.propertyIsEnumerable;\nvar __objRest$2 = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$9.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$9)\n for (var prop of __getOwnPropSymbols$9(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$9.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction useMutationObserver(target, callback, options = {}) {\n const _a = options, { window = defaultWindow } = _a, mutationOptions = __objRest$2(_a, [\"window\"]);\n let observer;\n const isSupported = useSupported(() => window && \"MutationObserver\" in window);\n const cleanup = () => {\n if (observer) {\n observer.disconnect();\n observer = void 0;\n }\n };\n const stopWatch = watch(() => unrefElement(target), (el) => {\n cleanup();\n if (isSupported.value && window && el) {\n observer = new MutationObserver(callback);\n observer.observe(el, mutationOptions);\n }\n }, { immediate: true });\n const stop = () => {\n cleanup();\n stopWatch();\n };\n tryOnScopeDispose(stop);\n return {\n isSupported,\n stop\n };\n}\n\nconst useNavigatorLanguage = (options = {}) => {\n const { window = defaultWindow } = options;\n const navigator = window == null ? void 0 : window.navigator;\n const isSupported = useSupported(() => navigator && \"language\" in navigator);\n const language = ref(navigator == null ? void 0 : navigator.language);\n useEventListener(window, \"languagechange\", () => {\n if (navigator)\n language.value = navigator.language;\n });\n return {\n isSupported,\n language\n };\n};\n\nfunction useNetwork(options = {}) {\n const { window = defaultWindow } = options;\n const navigator = window == null ? void 0 : window.navigator;\n const isSupported = useSupported(() => navigator && \"connection\" in navigator);\n const isOnline = ref(true);\n const saveData = ref(false);\n const offlineAt = ref(void 0);\n const onlineAt = ref(void 0);\n const downlink = ref(void 0);\n const downlinkMax = ref(void 0);\n const rtt = ref(void 0);\n const effectiveType = ref(void 0);\n const type = ref(\"unknown\");\n const connection = isSupported.value && navigator.connection;\n function updateNetworkInformation() {\n if (!navigator)\n return;\n isOnline.value = navigator.onLine;\n offlineAt.value = isOnline.value ? void 0 : Date.now();\n onlineAt.value = isOnline.value ? Date.now() : void 0;\n if (connection) {\n downlink.value = connection.downlink;\n downlinkMax.value = connection.downlinkMax;\n effectiveType.value = connection.effectiveType;\n rtt.value = connection.rtt;\n saveData.value = connection.saveData;\n type.value = connection.type;\n }\n }\n if (window) {\n useEventListener(window, \"offline\", () => {\n isOnline.value = false;\n offlineAt.value = Date.now();\n });\n useEventListener(window, \"online\", () => {\n isOnline.value = true;\n onlineAt.value = Date.now();\n });\n }\n if (connection)\n useEventListener(connection, \"change\", updateNetworkInformation, false);\n updateNetworkInformation();\n return {\n isSupported,\n isOnline,\n saveData,\n offlineAt,\n onlineAt,\n downlink,\n downlinkMax,\n effectiveType,\n rtt,\n type\n };\n}\n\nvar __defProp$7 = Object.defineProperty;\nvar __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$8 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$8 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$7 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$8.call(b, prop))\n __defNormalProp$7(a, prop, b[prop]);\n if (__getOwnPropSymbols$8)\n for (var prop of __getOwnPropSymbols$8(b)) {\n if (__propIsEnum$8.call(b, prop))\n __defNormalProp$7(a, prop, b[prop]);\n }\n return a;\n};\nfunction useNow(options = {}) {\n const {\n controls: exposeControls = false,\n interval = \"requestAnimationFrame\"\n } = options;\n const now = ref(new Date());\n const update = () => now.value = new Date();\n const controls = interval === \"requestAnimationFrame\" ? useRafFn(update, { immediate: true }) : useIntervalFn(update, interval, { immediate: true });\n if (exposeControls) {\n return __spreadValues$7({\n now\n }, controls);\n } else {\n return now;\n }\n}\n\nfunction useObjectUrl(object) {\n const url = ref();\n const release = () => {\n if (url.value)\n URL.revokeObjectURL(url.value);\n url.value = void 0;\n };\n watch(() => unref(object), (newObject) => {\n release();\n if (newObject)\n url.value = URL.createObjectURL(newObject);\n }, { immediate: true });\n tryOnScopeDispose(release);\n return readonly(url);\n}\n\nfunction useClamp(value, min, max) {\n if (isFunction(value) || isReadonly(value))\n return computed(() => clamp(resolveUnref(value), resolveUnref(min), resolveUnref(max)));\n const _value = ref(value);\n return computed({\n get() {\n return _value.value = clamp(_value.value, resolveUnref(min), resolveUnref(max));\n },\n set(value2) {\n _value.value = clamp(value2, resolveUnref(min), resolveUnref(max));\n }\n });\n}\n\nfunction useOffsetPagination(options) {\n const {\n total = Infinity,\n pageSize = 10,\n page = 1,\n onPageChange = noop,\n onPageSizeChange = noop,\n onPageCountChange = noop\n } = options;\n const currentPageSize = useClamp(pageSize, 1, Infinity);\n const pageCount = computed(() => Math.max(1, Math.ceil(unref(total) / unref(currentPageSize))));\n const currentPage = useClamp(page, 1, pageCount);\n const isFirstPage = computed(() => currentPage.value === 1);\n const isLastPage = computed(() => currentPage.value === pageCount.value);\n if (isRef(page))\n syncRef(page, currentPage);\n if (isRef(pageSize))\n syncRef(pageSize, currentPageSize);\n function prev() {\n currentPage.value--;\n }\n function next() {\n currentPage.value++;\n }\n const returnValue = {\n currentPage,\n currentPageSize,\n pageCount,\n isFirstPage,\n isLastPage,\n prev,\n next\n };\n watch(currentPage, () => {\n onPageChange(reactive(returnValue));\n });\n watch(currentPageSize, () => {\n onPageSizeChange(reactive(returnValue));\n });\n watch(pageCount, () => {\n onPageCountChange(reactive(returnValue));\n });\n return returnValue;\n}\n\nfunction useOnline(options = {}) {\n const { isOnline } = useNetwork(options);\n return isOnline;\n}\n\nfunction usePageLeave(options = {}) {\n const { window = defaultWindow } = options;\n const isLeft = ref(false);\n const handler = (event) => {\n if (!window)\n return;\n event = event || window.event;\n const from = event.relatedTarget || event.toElement;\n isLeft.value = !from;\n };\n if (window) {\n useEventListener(window, \"mouseout\", handler, { passive: true });\n useEventListener(window.document, \"mouseleave\", handler, { passive: true });\n useEventListener(window.document, \"mouseenter\", handler, { passive: true });\n }\n return isLeft;\n}\n\nfunction useParallax(target, options = {}) {\n const {\n deviceOrientationTiltAdjust = (i) => i,\n deviceOrientationRollAdjust = (i) => i,\n mouseTiltAdjust = (i) => i,\n mouseRollAdjust = (i) => i,\n window = defaultWindow\n } = options;\n const orientation = reactive(useDeviceOrientation({ window }));\n const {\n elementX: x,\n elementY: y,\n elementWidth: width,\n elementHeight: height\n } = useMouseInElement(target, { handleOutside: false, window });\n const source = computed(() => {\n if (orientation.isSupported && (orientation.alpha != null && orientation.alpha !== 0 || orientation.gamma != null && orientation.gamma !== 0))\n return \"deviceOrientation\";\n return \"mouse\";\n });\n const roll = computed(() => {\n if (source.value === \"deviceOrientation\") {\n const value = -orientation.beta / 90;\n return deviceOrientationRollAdjust(value);\n } else {\n const value = -(y.value - height.value / 2) / height.value;\n return mouseRollAdjust(value);\n }\n });\n const tilt = computed(() => {\n if (source.value === \"deviceOrientation\") {\n const value = orientation.gamma / 90;\n return deviceOrientationTiltAdjust(value);\n } else {\n const value = (x.value - width.value / 2) / width.value;\n return mouseTiltAdjust(value);\n }\n });\n return { roll, tilt, source };\n}\n\nfunction useParentElement(element = useCurrentElement()) {\n const parentElement = shallowRef();\n const update = () => {\n const el = unrefElement(element);\n if (el)\n parentElement.value = el.parentElement;\n };\n tryOnMounted(update);\n watch(() => resolveUnref(element), update);\n return parentElement;\n}\n\nvar __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$7 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$7 = Object.prototype.propertyIsEnumerable;\nvar __objRest$1 = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$7.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$7)\n for (var prop of __getOwnPropSymbols$7(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$7.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction usePerformanceObserver(options, callback) {\n const _a = options, {\n window = defaultWindow,\n immediate = true\n } = _a, performanceOptions = __objRest$1(_a, [\n \"window\",\n \"immediate\"\n ]);\n const isSupported = useSupported(() => window && \"PerformanceObserver\" in window);\n let observer;\n const stop = () => {\n observer == null ? void 0 : observer.disconnect();\n };\n const start = () => {\n if (isSupported.value) {\n stop();\n observer = new PerformanceObserver(callback);\n observer.observe(performanceOptions);\n }\n };\n tryOnScopeDispose(stop);\n if (immediate)\n start();\n return {\n isSupported,\n start,\n stop\n };\n}\n\nvar __defProp$6 = Object.defineProperty;\nvar __defProps$2 = Object.defineProperties;\nvar __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$6 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$6 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$6 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$6.call(b, prop))\n __defNormalProp$6(a, prop, b[prop]);\n if (__getOwnPropSymbols$6)\n for (var prop of __getOwnPropSymbols$6(b)) {\n if (__propIsEnum$6.call(b, prop))\n __defNormalProp$6(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));\nconst defaultState = {\n x: 0,\n y: 0,\n pointerId: 0,\n pressure: 0,\n tiltX: 0,\n tiltY: 0,\n width: 0,\n height: 0,\n twist: 0,\n pointerType: null\n};\nconst keys = /* @__PURE__ */ Object.keys(defaultState);\nfunction usePointer(options = {}) {\n const {\n target = defaultWindow\n } = options;\n const isInside = ref(false);\n const state = ref(options.initialValue || {});\n Object.assign(state.value, defaultState, state.value);\n const handler = (event) => {\n isInside.value = true;\n if (options.pointerTypes && !options.pointerTypes.includes(event.pointerType))\n return;\n state.value = objectPick(event, keys, false);\n };\n if (target) {\n useEventListener(target, \"pointerdown\", handler, { passive: true });\n useEventListener(target, \"pointermove\", handler, { passive: true });\n useEventListener(target, \"pointerleave\", () => isInside.value = false, { passive: true });\n }\n return __spreadProps$2(__spreadValues$6({}, toRefs(state)), {\n isInside\n });\n}\n\nfunction usePointerLock(target, options = {}) {\n const { document = defaultDocument, pointerLockOptions } = options;\n const isSupported = useSupported(() => document && \"pointerLockElement\" in document);\n const element = ref();\n const triggerElement = ref();\n let targetElement;\n if (isSupported.value) {\n useEventListener(document, \"pointerlockchange\", () => {\n var _a;\n const currentElement = (_a = document.pointerLockElement) != null ? _a : element.value;\n if (targetElement && currentElement === targetElement) {\n element.value = document.pointerLockElement;\n if (!element.value)\n targetElement = triggerElement.value = null;\n }\n });\n useEventListener(document, \"pointerlockerror\", () => {\n var _a;\n const currentElement = (_a = document.pointerLockElement) != null ? _a : element.value;\n if (targetElement && currentElement === targetElement) {\n const action = document.pointerLockElement ? \"release\" : \"acquire\";\n throw new Error(`Failed to ${action} pointer lock.`);\n }\n });\n }\n async function lock(e, options2) {\n var _a;\n if (!isSupported.value)\n throw new Error(\"Pointer Lock API is not supported by your browser.\");\n triggerElement.value = e instanceof Event ? e.currentTarget : null;\n targetElement = e instanceof Event ? (_a = unrefElement(target)) != null ? _a : triggerElement.value : unrefElement(e);\n if (!targetElement)\n throw new Error(\"Target element undefined.\");\n targetElement.requestPointerLock(options2 != null ? options2 : pointerLockOptions);\n return await until(element).toBe(targetElement);\n }\n async function unlock() {\n if (!element.value)\n return false;\n document.exitPointerLock();\n await until(element).toBeNull();\n return true;\n }\n return {\n isSupported,\n element,\n triggerElement,\n lock,\n unlock\n };\n}\n\nfunction usePointerSwipe(target, options = {}) {\n const targetRef = resolveRef(target);\n const {\n threshold = 50,\n onSwipe,\n onSwipeEnd,\n onSwipeStart\n } = options;\n const posStart = reactive({ x: 0, y: 0 });\n const updatePosStart = (x, y) => {\n posStart.x = x;\n posStart.y = y;\n };\n const posEnd = reactive({ x: 0, y: 0 });\n const updatePosEnd = (x, y) => {\n posEnd.x = x;\n posEnd.y = y;\n };\n const distanceX = computed(() => posStart.x - posEnd.x);\n const distanceY = computed(() => posStart.y - posEnd.y);\n const { max, abs } = Math;\n const isThresholdExceeded = computed(() => max(abs(distanceX.value), abs(distanceY.value)) >= threshold);\n const isSwiping = ref(false);\n const isPointerDown = ref(false);\n const direction = computed(() => {\n if (!isThresholdExceeded.value)\n return \"none\";\n if (abs(distanceX.value) > abs(distanceY.value)) {\n return distanceX.value > 0 ? \"left\" : \"right\";\n } else {\n return distanceY.value > 0 ? \"up\" : \"down\";\n }\n });\n const eventIsAllowed = (e) => {\n var _a, _b, _c;\n const isReleasingButton = e.buttons === 0;\n const isPrimaryButton = e.buttons === 1;\n return (_c = (_b = (_a = options.pointerTypes) == null ? void 0 : _a.includes(e.pointerType)) != null ? _b : isReleasingButton || isPrimaryButton) != null ? _c : true;\n };\n const stops = [\n useEventListener(target, \"pointerdown\", (e) => {\n var _a, _b;\n if (!eventIsAllowed(e))\n return;\n isPointerDown.value = true;\n (_b = (_a = targetRef.value) == null ? void 0 : _a.style) == null ? void 0 : _b.setProperty(\"touch-action\", \"none\");\n const eventTarget = e.target;\n eventTarget == null ? void 0 : eventTarget.setPointerCapture(e.pointerId);\n const { clientX: x, clientY: y } = e;\n updatePosStart(x, y);\n updatePosEnd(x, y);\n onSwipeStart == null ? void 0 : onSwipeStart(e);\n }),\n useEventListener(target, \"pointermove\", (e) => {\n if (!eventIsAllowed(e))\n return;\n if (!isPointerDown.value)\n return;\n const { clientX: x, clientY: y } = e;\n updatePosEnd(x, y);\n if (!isSwiping.value && isThresholdExceeded.value)\n isSwiping.value = true;\n if (isSwiping.value)\n onSwipe == null ? void 0 : onSwipe(e);\n }),\n useEventListener(target, \"pointerup\", (e) => {\n var _a, _b;\n if (!eventIsAllowed(e))\n return;\n if (isSwiping.value)\n onSwipeEnd == null ? void 0 : onSwipeEnd(e, direction.value);\n isPointerDown.value = false;\n isSwiping.value = false;\n (_b = (_a = targetRef.value) == null ? void 0 : _a.style) == null ? void 0 : _b.setProperty(\"touch-action\", \"initial\");\n })\n ];\n const stop = () => stops.forEach((s) => s());\n return {\n isSwiping: readonly(isSwiping),\n direction: readonly(direction),\n posStart: readonly(posStart),\n posEnd: readonly(posEnd),\n distanceX,\n distanceY,\n stop\n };\n}\n\nfunction usePreferredColorScheme(options) {\n const isLight = useMediaQuery(\"(prefers-color-scheme: light)\", options);\n const isDark = useMediaQuery(\"(prefers-color-scheme: dark)\", options);\n return computed(() => {\n if (isDark.value)\n return \"dark\";\n if (isLight.value)\n return \"light\";\n return \"no-preference\";\n });\n}\n\nfunction usePreferredContrast(options) {\n const isMore = useMediaQuery(\"(prefers-contrast: more)\", options);\n const isLess = useMediaQuery(\"(prefers-contrast: less)\", options);\n const isCustom = useMediaQuery(\"(prefers-contrast: custom)\", options);\n return computed(() => {\n if (isMore.value)\n return \"more\";\n if (isLess.value)\n return \"less\";\n if (isCustom.value)\n return \"custom\";\n return \"no-preference\";\n });\n}\n\nfunction usePreferredLanguages(options = {}) {\n const { window = defaultWindow } = options;\n if (!window)\n return ref([\"en\"]);\n const navigator = window.navigator;\n const value = ref(navigator.languages);\n useEventListener(window, \"languagechange\", () => {\n value.value = navigator.languages;\n });\n return value;\n}\n\nfunction usePreferredReducedMotion(options) {\n const isReduced = useMediaQuery(\"(prefers-reduced-motion: reduce)\", options);\n return computed(() => {\n if (isReduced.value)\n return \"reduce\";\n return \"no-preference\";\n });\n}\n\nfunction usePrevious(value, initialValue) {\n const previous = shallowRef(initialValue);\n watch(resolveRef(value), (_, oldValue) => {\n previous.value = oldValue;\n }, { flush: \"sync\" });\n return readonly(previous);\n}\n\nconst useScreenOrientation = (options = {}) => {\n const {\n window = defaultWindow\n } = options;\n const isSupported = useSupported(() => window && \"screen\" in window && \"orientation\" in window.screen);\n const screenOrientation = isSupported.value ? window.screen.orientation : {};\n const orientation = ref(screenOrientation.type);\n const angle = ref(screenOrientation.angle || 0);\n if (isSupported.value) {\n useEventListener(window, \"orientationchange\", () => {\n orientation.value = screenOrientation.type;\n angle.value = screenOrientation.angle;\n });\n }\n const lockOrientation = (type) => {\n if (!isSupported.value)\n return Promise.reject(new Error(\"Not supported\"));\n return screenOrientation.lock(type);\n };\n const unlockOrientation = () => {\n if (isSupported.value)\n screenOrientation.unlock();\n };\n return {\n isSupported,\n orientation,\n angle,\n lockOrientation,\n unlockOrientation\n };\n};\n\nconst topVarName = \"--vueuse-safe-area-top\";\nconst rightVarName = \"--vueuse-safe-area-right\";\nconst bottomVarName = \"--vueuse-safe-area-bottom\";\nconst leftVarName = \"--vueuse-safe-area-left\";\nfunction useScreenSafeArea() {\n const top = ref(\"\");\n const right = ref(\"\");\n const bottom = ref(\"\");\n const left = ref(\"\");\n if (isClient) {\n const topCssVar = useCssVar(topVarName);\n const rightCssVar = useCssVar(rightVarName);\n const bottomCssVar = useCssVar(bottomVarName);\n const leftCssVar = useCssVar(leftVarName);\n topCssVar.value = \"env(safe-area-inset-top, 0px)\";\n rightCssVar.value = \"env(safe-area-inset-right, 0px)\";\n bottomCssVar.value = \"env(safe-area-inset-bottom, 0px)\";\n leftCssVar.value = \"env(safe-area-inset-left, 0px)\";\n update();\n useEventListener(\"resize\", useDebounceFn(update));\n }\n function update() {\n top.value = getValue(topVarName);\n right.value = getValue(rightVarName);\n bottom.value = getValue(bottomVarName);\n left.value = getValue(leftVarName);\n }\n return {\n top,\n right,\n bottom,\n left,\n update\n };\n}\nfunction getValue(position) {\n return getComputedStyle(document.documentElement).getPropertyValue(position);\n}\n\nfunction useScriptTag(src, onLoaded = noop, options = {}) {\n const {\n immediate = true,\n manual = false,\n type = \"text/javascript\",\n async = true,\n crossOrigin,\n referrerPolicy,\n noModule,\n defer,\n document = defaultDocument,\n attrs = {}\n } = options;\n const scriptTag = ref(null);\n let _promise = null;\n const loadScript = (waitForScriptLoad) => new Promise((resolve, reject) => {\n const resolveWithElement = (el2) => {\n scriptTag.value = el2;\n resolve(el2);\n return el2;\n };\n if (!document) {\n resolve(false);\n return;\n }\n let shouldAppend = false;\n let el = document.querySelector(`script[src=\"${resolveUnref(src)}\"]`);\n if (!el) {\n el = document.createElement(\"script\");\n el.type = type;\n el.async = async;\n el.src = resolveUnref(src);\n if (defer)\n el.defer = defer;\n if (crossOrigin)\n el.crossOrigin = crossOrigin;\n if (noModule)\n el.noModule = noModule;\n if (referrerPolicy)\n el.referrerPolicy = referrerPolicy;\n Object.entries(attrs).forEach(([name, value]) => el == null ? void 0 : el.setAttribute(name, value));\n shouldAppend = true;\n } else if (el.hasAttribute(\"data-loaded\")) {\n resolveWithElement(el);\n }\n el.addEventListener(\"error\", (event) => reject(event));\n el.addEventListener(\"abort\", (event) => reject(event));\n el.addEventListener(\"load\", () => {\n el.setAttribute(\"data-loaded\", \"true\");\n onLoaded(el);\n resolveWithElement(el);\n });\n if (shouldAppend)\n el = document.head.appendChild(el);\n if (!waitForScriptLoad)\n resolveWithElement(el);\n });\n const load = (waitForScriptLoad = true) => {\n if (!_promise)\n _promise = loadScript(waitForScriptLoad);\n return _promise;\n };\n const unload = () => {\n if (!document)\n return;\n _promise = null;\n if (scriptTag.value)\n scriptTag.value = null;\n const el = document.querySelector(`script[src=\"${resolveUnref(src)}\"]`);\n if (el)\n document.head.removeChild(el);\n };\n if (immediate && !manual)\n tryOnMounted(load);\n if (!manual)\n tryOnUnmounted(unload);\n return { scriptTag, load, unload };\n}\n\nfunction checkOverflowScroll(ele) {\n const style = window.getComputedStyle(ele);\n if (style.overflowX === \"scroll\" || style.overflowY === \"scroll\" || style.overflowX === \"auto\" && ele.clientHeight < ele.scrollHeight || style.overflowY === \"auto\" && ele.clientWidth < ele.scrollWidth) {\n return true;\n } else {\n const parent = ele.parentNode;\n if (!parent || parent.tagName === \"BODY\")\n return false;\n return checkOverflowScroll(parent);\n }\n}\nfunction preventDefault(rawEvent) {\n const e = rawEvent || window.event;\n const _target = e.target;\n if (checkOverflowScroll(_target))\n return false;\n if (e.touches.length > 1)\n return true;\n if (e.preventDefault)\n e.preventDefault();\n return false;\n}\nfunction useScrollLock(element, initialState = false) {\n const isLocked = ref(initialState);\n let stopTouchMoveListener = null;\n let initialOverflow;\n watch(resolveRef(element), (el) => {\n if (el) {\n const ele = el;\n initialOverflow = ele.style.overflow;\n if (isLocked.value)\n ele.style.overflow = \"hidden\";\n }\n }, {\n immediate: true\n });\n const lock = () => {\n const ele = resolveUnref(element);\n if (!ele || isLocked.value)\n return;\n if (isIOS) {\n stopTouchMoveListener = useEventListener(ele, \"touchmove\", (e) => {\n preventDefault(e);\n }, { passive: false });\n }\n ele.style.overflow = \"hidden\";\n isLocked.value = true;\n };\n const unlock = () => {\n const ele = resolveUnref(element);\n if (!ele || !isLocked.value)\n return;\n isIOS && (stopTouchMoveListener == null ? void 0 : stopTouchMoveListener());\n ele.style.overflow = initialOverflow;\n isLocked.value = false;\n };\n tryOnScopeDispose(unlock);\n return computed({\n get() {\n return isLocked.value;\n },\n set(v) {\n if (v)\n lock();\n else\n unlock();\n }\n });\n}\n\nfunction useSessionStorage(key, initialValue, options = {}) {\n const { window = defaultWindow } = options;\n return useStorage(key, initialValue, window == null ? void 0 : window.sessionStorage, options);\n}\n\nvar __defProp$5 = Object.defineProperty;\nvar __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$5 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$5 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$5 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$5.call(b, prop))\n __defNormalProp$5(a, prop, b[prop]);\n if (__getOwnPropSymbols$5)\n for (var prop of __getOwnPropSymbols$5(b)) {\n if (__propIsEnum$5.call(b, prop))\n __defNormalProp$5(a, prop, b[prop]);\n }\n return a;\n};\nfunction useShare(shareOptions = {}, options = {}) {\n const { navigator = defaultNavigator } = options;\n const _navigator = navigator;\n const isSupported = useSupported(() => _navigator && \"canShare\" in _navigator);\n const share = async (overrideOptions = {}) => {\n if (isSupported.value) {\n const data = __spreadValues$5(__spreadValues$5({}, resolveUnref(shareOptions)), resolveUnref(overrideOptions));\n let granted = true;\n if (data.files && _navigator.canShare)\n granted = _navigator.canShare({ files: data.files });\n if (granted)\n return _navigator.share(data);\n }\n };\n return {\n isSupported,\n share\n };\n}\n\nconst defaultSortFn = (source, compareFn) => source.sort(compareFn);\nconst defaultCompare = (a, b) => a - b;\nfunction useSorted(...args) {\n var _a, _b, _c, _d;\n const [source] = args;\n let compareFn = defaultCompare;\n let options = {};\n if (args.length === 2) {\n if (typeof args[1] === \"object\") {\n options = args[1];\n compareFn = (_a = options.compareFn) != null ? _a : defaultCompare;\n } else {\n compareFn = (_b = args[1]) != null ? _b : defaultCompare;\n }\n } else if (args.length > 2) {\n compareFn = (_c = args[1]) != null ? _c : defaultCompare;\n options = (_d = args[2]) != null ? _d : {};\n }\n const {\n dirty = false,\n sortFn = defaultSortFn\n } = options;\n if (!dirty)\n return computed(() => sortFn([...unref(source)], compareFn));\n watchEffect(() => {\n const result = sortFn(unref(source), compareFn);\n if (isRef(source))\n source.value = result;\n else\n source.splice(0, source.length, ...result);\n });\n return source;\n}\n\nfunction useSpeechRecognition(options = {}) {\n const {\n interimResults = true,\n continuous = true,\n window = defaultWindow\n } = options;\n const lang = resolveRef(options.lang || \"en-US\");\n const isListening = ref(false);\n const isFinal = ref(false);\n const result = ref(\"\");\n const error = shallowRef(void 0);\n const toggle = (value = !isListening.value) => {\n isListening.value = value;\n };\n const start = () => {\n isListening.value = true;\n };\n const stop = () => {\n isListening.value = false;\n };\n const SpeechRecognition = window && (window.SpeechRecognition || window.webkitSpeechRecognition);\n const isSupported = useSupported(() => SpeechRecognition);\n let recognition;\n if (isSupported.value) {\n recognition = new SpeechRecognition();\n recognition.continuous = continuous;\n recognition.interimResults = interimResults;\n recognition.lang = unref(lang);\n recognition.onstart = () => {\n isFinal.value = false;\n };\n watch(lang, (lang2) => {\n if (recognition && !isListening.value)\n recognition.lang = lang2;\n });\n recognition.onresult = (event) => {\n const transcript = Array.from(event.results).map((result2) => {\n isFinal.value = result2.isFinal;\n return result2[0];\n }).map((result2) => result2.transcript).join(\"\");\n result.value = transcript;\n error.value = void 0;\n };\n recognition.onerror = (event) => {\n error.value = event;\n };\n recognition.onend = () => {\n isListening.value = false;\n recognition.lang = unref(lang);\n };\n watch(isListening, () => {\n if (isListening.value)\n recognition.start();\n else\n recognition.stop();\n });\n }\n tryOnScopeDispose(() => {\n isListening.value = false;\n });\n return {\n isSupported,\n isListening,\n isFinal,\n recognition,\n result,\n error,\n toggle,\n start,\n stop\n };\n}\n\nfunction useSpeechSynthesis(text, options = {}) {\n const {\n pitch = 1,\n rate = 1,\n volume = 1,\n window = defaultWindow\n } = options;\n const synth = window && window.speechSynthesis;\n const isSupported = useSupported(() => synth);\n const isPlaying = ref(false);\n const status = ref(\"init\");\n const spokenText = resolveRef(text || \"\");\n const lang = resolveRef(options.lang || \"en-US\");\n const error = shallowRef(void 0);\n const toggle = (value = !isPlaying.value) => {\n isPlaying.value = value;\n };\n const bindEventsForUtterance = (utterance2) => {\n utterance2.lang = unref(lang);\n utterance2.voice = unref(options.voice) || null;\n utterance2.pitch = pitch;\n utterance2.rate = rate;\n utterance2.volume = volume;\n utterance2.onstart = () => {\n isPlaying.value = true;\n status.value = \"play\";\n };\n utterance2.onpause = () => {\n isPlaying.value = false;\n status.value = \"pause\";\n };\n utterance2.onresume = () => {\n isPlaying.value = true;\n status.value = \"play\";\n };\n utterance2.onend = () => {\n isPlaying.value = false;\n status.value = \"end\";\n };\n utterance2.onerror = (event) => {\n error.value = event;\n };\n };\n const utterance = computed(() => {\n isPlaying.value = false;\n status.value = \"init\";\n const newUtterance = new SpeechSynthesisUtterance(spokenText.value);\n bindEventsForUtterance(newUtterance);\n return newUtterance;\n });\n const speak = () => {\n synth.cancel();\n utterance && synth.speak(utterance.value);\n };\n const stop = () => {\n synth.cancel();\n isPlaying.value = false;\n };\n if (isSupported.value) {\n bindEventsForUtterance(utterance.value);\n watch(lang, (lang2) => {\n if (utterance.value && !isPlaying.value)\n utterance.value.lang = lang2;\n });\n if (options.voice) {\n watch(options.voice, () => {\n synth.cancel();\n });\n }\n watch(isPlaying, () => {\n if (isPlaying.value)\n synth.resume();\n else\n synth.pause();\n });\n }\n tryOnScopeDispose(() => {\n isPlaying.value = false;\n });\n return {\n isSupported,\n isPlaying,\n status,\n utterance,\n error,\n stop,\n toggle,\n speak\n };\n}\n\nfunction useStepper(steps, initialStep) {\n const stepsRef = ref(steps);\n const stepNames = computed(() => Array.isArray(stepsRef.value) ? stepsRef.value : Object.keys(stepsRef.value));\n const index = ref(stepNames.value.indexOf(initialStep != null ? initialStep : stepNames.value[0]));\n const current = computed(() => at(index.value));\n const isFirst = computed(() => index.value === 0);\n const isLast = computed(() => index.value === stepNames.value.length - 1);\n const next = computed(() => stepNames.value[index.value + 1]);\n const previous = computed(() => stepNames.value[index.value - 1]);\n function at(index2) {\n if (Array.isArray(stepsRef.value))\n return stepsRef.value[index2];\n return stepsRef.value[stepNames.value[index2]];\n }\n function get(step) {\n if (!stepNames.value.includes(step))\n return;\n return at(stepNames.value.indexOf(step));\n }\n function goTo(step) {\n if (stepNames.value.includes(step))\n index.value = stepNames.value.indexOf(step);\n }\n function goToNext() {\n if (isLast.value)\n return;\n index.value++;\n }\n function goToPrevious() {\n if (isFirst.value)\n return;\n index.value--;\n }\n function goBackTo(step) {\n if (isAfter(step))\n goTo(step);\n }\n function isNext(step) {\n return stepNames.value.indexOf(step) === index.value + 1;\n }\n function isPrevious(step) {\n return stepNames.value.indexOf(step) === index.value - 1;\n }\n function isCurrent(step) {\n return stepNames.value.indexOf(step) === index.value;\n }\n function isBefore(step) {\n return index.value < stepNames.value.indexOf(step);\n }\n function isAfter(step) {\n return index.value > stepNames.value.indexOf(step);\n }\n return {\n steps: stepsRef,\n stepNames,\n index,\n current,\n next,\n previous,\n isFirst,\n isLast,\n at,\n get,\n goTo,\n goToNext,\n goToPrevious,\n goBackTo,\n isNext,\n isPrevious,\n isCurrent,\n isBefore,\n isAfter\n };\n}\n\nvar __defProp$4 = Object.defineProperty;\nvar __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$4 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$4 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$4 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$4.call(b, prop))\n __defNormalProp$4(a, prop, b[prop]);\n if (__getOwnPropSymbols$4)\n for (var prop of __getOwnPropSymbols$4(b)) {\n if (__propIsEnum$4.call(b, prop))\n __defNormalProp$4(a, prop, b[prop]);\n }\n return a;\n};\nfunction useStorageAsync(key, initialValue, storage, options = {}) {\n var _a;\n const {\n flush = \"pre\",\n deep = true,\n listenToStorageChanges = true,\n writeDefaults = true,\n mergeDefaults = false,\n shallow,\n window = defaultWindow,\n eventFilter,\n onError = (e) => {\n console.error(e);\n }\n } = options;\n const rawInit = resolveUnref(initialValue);\n const type = guessSerializerType(rawInit);\n const data = (shallow ? shallowRef : ref)(initialValue);\n const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type];\n if (!storage) {\n try {\n storage = getSSRHandler(\"getDefaultStorage\", () => {\n var _a2;\n return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage;\n })();\n } catch (e) {\n onError(e);\n }\n }\n async function read(event) {\n if (!storage || event && event.key !== key)\n return;\n try {\n const rawValue = event ? event.newValue : await storage.getItem(key);\n if (rawValue == null) {\n data.value = rawInit;\n if (writeDefaults && rawInit !== null)\n await storage.setItem(key, await serializer.write(rawInit));\n } else if (mergeDefaults) {\n const value = await serializer.read(rawValue);\n if (isFunction(mergeDefaults))\n data.value = mergeDefaults(value, rawInit);\n else if (type === \"object\" && !Array.isArray(value))\n data.value = __spreadValues$4(__spreadValues$4({}, rawInit), value);\n else\n data.value = value;\n } else {\n data.value = await serializer.read(rawValue);\n }\n } catch (e) {\n onError(e);\n }\n }\n read();\n if (window && listenToStorageChanges)\n useEventListener(window, \"storage\", (e) => setTimeout(() => read(e), 0));\n if (storage) {\n watchWithFilter(data, async () => {\n try {\n if (data.value == null)\n await storage.removeItem(key);\n else\n await storage.setItem(key, await serializer.write(data.value));\n } catch (e) {\n onError(e);\n }\n }, {\n flush,\n deep,\n eventFilter\n });\n }\n return data;\n}\n\nlet _id = 0;\nfunction useStyleTag(css, options = {}) {\n const isLoaded = ref(false);\n const {\n document = defaultDocument,\n immediate = true,\n manual = false,\n id = `vueuse_styletag_${++_id}`\n } = options;\n const cssRef = ref(css);\n let stop = () => {\n };\n const load = () => {\n if (!document)\n return;\n const el = document.getElementById(id) || document.createElement(\"style\");\n if (!el.isConnected) {\n el.type = \"text/css\";\n el.id = id;\n if (options.media)\n el.media = options.media;\n document.head.appendChild(el);\n }\n if (isLoaded.value)\n return;\n stop = watch(cssRef, (value) => {\n el.textContent = value;\n }, { immediate: true });\n isLoaded.value = true;\n };\n const unload = () => {\n if (!document || !isLoaded.value)\n return;\n stop();\n document.head.removeChild(document.getElementById(id));\n isLoaded.value = false;\n };\n if (immediate && !manual)\n tryOnMounted(load);\n if (!manual)\n tryOnScopeDispose(unload);\n return {\n id,\n css: cssRef,\n unload,\n load,\n isLoaded: readonly(isLoaded)\n };\n}\n\nfunction useSwipe(target, options = {}) {\n const {\n threshold = 50,\n onSwipe,\n onSwipeEnd,\n onSwipeStart,\n passive = true,\n window = defaultWindow\n } = options;\n const coordsStart = reactive({ x: 0, y: 0 });\n const coordsEnd = reactive({ x: 0, y: 0 });\n const diffX = computed(() => coordsStart.x - coordsEnd.x);\n const diffY = computed(() => coordsStart.y - coordsEnd.y);\n const { max, abs } = Math;\n const isThresholdExceeded = computed(() => max(abs(diffX.value), abs(diffY.value)) >= threshold);\n const isSwiping = ref(false);\n const direction = computed(() => {\n if (!isThresholdExceeded.value)\n return \"none\";\n if (abs(diffX.value) > abs(diffY.value)) {\n return diffX.value > 0 ? \"left\" : \"right\";\n } else {\n return diffY.value > 0 ? \"up\" : \"down\";\n }\n });\n const getTouchEventCoords = (e) => [e.touches[0].clientX, e.touches[0].clientY];\n const updateCoordsStart = (x, y) => {\n coordsStart.x = x;\n coordsStart.y = y;\n };\n const updateCoordsEnd = (x, y) => {\n coordsEnd.x = x;\n coordsEnd.y = y;\n };\n let listenerOptions;\n const isPassiveEventSupported = checkPassiveEventSupport(window == null ? void 0 : window.document);\n if (!passive)\n listenerOptions = isPassiveEventSupported ? { passive: false, capture: true } : { capture: true };\n else\n listenerOptions = isPassiveEventSupported ? { passive: true } : { capture: false };\n const onTouchEnd = (e) => {\n if (isSwiping.value)\n onSwipeEnd == null ? void 0 : onSwipeEnd(e, direction.value);\n isSwiping.value = false;\n };\n const stops = [\n useEventListener(target, \"touchstart\", (e) => {\n if (listenerOptions.capture && !listenerOptions.passive)\n e.preventDefault();\n const [x, y] = getTouchEventCoords(e);\n updateCoordsStart(x, y);\n updateCoordsEnd(x, y);\n onSwipeStart == null ? void 0 : onSwipeStart(e);\n }, listenerOptions),\n useEventListener(target, \"touchmove\", (e) => {\n const [x, y] = getTouchEventCoords(e);\n updateCoordsEnd(x, y);\n if (!isSwiping.value && isThresholdExceeded.value)\n isSwiping.value = true;\n if (isSwiping.value)\n onSwipe == null ? void 0 : onSwipe(e);\n }, listenerOptions),\n useEventListener(target, \"touchend\", onTouchEnd, listenerOptions),\n useEventListener(target, \"touchcancel\", onTouchEnd, listenerOptions)\n ];\n const stop = () => stops.forEach((s) => s());\n return {\n isPassiveEventSupported,\n isSwiping,\n direction,\n coordsStart,\n coordsEnd,\n lengthX: diffX,\n lengthY: diffY,\n stop\n };\n}\nfunction checkPassiveEventSupport(document) {\n if (!document)\n return false;\n let supportsPassive = false;\n const optionsBlock = {\n get passive() {\n supportsPassive = true;\n return false;\n }\n };\n document.addEventListener(\"x\", noop, optionsBlock);\n document.removeEventListener(\"x\", noop);\n return supportsPassive;\n}\n\nfunction useTemplateRefsList() {\n const refs = ref([]);\n refs.value.set = (el) => {\n if (el)\n refs.value.push(el);\n };\n onBeforeUpdate(() => {\n refs.value.length = 0;\n });\n return refs;\n}\n\nfunction useTextDirection(options = {}) {\n const {\n document = defaultDocument,\n selector = \"html\",\n observe = false,\n initialValue = \"ltr\"\n } = options;\n function getValue() {\n var _a, _b;\n return (_b = (_a = document == null ? void 0 : document.querySelector(selector)) == null ? void 0 : _a.getAttribute(\"dir\")) != null ? _b : initialValue;\n }\n const dir = ref(getValue());\n tryOnMounted(() => dir.value = getValue());\n if (observe && document) {\n useMutationObserver(document.querySelector(selector), () => dir.value = getValue(), { attributes: true });\n }\n return computed({\n get() {\n return dir.value;\n },\n set(v) {\n var _a, _b;\n dir.value = v;\n if (!document)\n return;\n if (dir.value)\n (_a = document.querySelector(selector)) == null ? void 0 : _a.setAttribute(\"dir\", dir.value);\n else\n (_b = document.querySelector(selector)) == null ? void 0 : _b.removeAttribute(\"dir\");\n }\n });\n}\n\nfunction getRangesFromSelection(selection) {\n var _a;\n const rangeCount = (_a = selection.rangeCount) != null ? _a : 0;\n const ranges = new Array(rangeCount);\n for (let i = 0; i < rangeCount; i++) {\n const range = selection.getRangeAt(i);\n ranges[i] = range;\n }\n return ranges;\n}\nfunction useTextSelection(options = {}) {\n const {\n window = defaultWindow\n } = options;\n const selection = ref(null);\n const text = computed(() => {\n var _a, _b;\n return (_b = (_a = selection.value) == null ? void 0 : _a.toString()) != null ? _b : \"\";\n });\n const ranges = computed(() => selection.value ? getRangesFromSelection(selection.value) : []);\n const rects = computed(() => ranges.value.map((range) => range.getBoundingClientRect()));\n function onSelectionChange() {\n selection.value = null;\n if (window)\n selection.value = window.getSelection();\n }\n if (window)\n useEventListener(window.document, \"selectionchange\", onSelectionChange);\n return {\n text,\n rects,\n ranges,\n selection\n };\n}\n\nfunction useTextareaAutosize(options) {\n const textarea = ref(options == null ? void 0 : options.element);\n const input = ref(options == null ? void 0 : options.input);\n const textareaScrollHeight = ref(1);\n function triggerResize() {\n var _a, _b;\n if (!textarea.value)\n return;\n let height = \"\";\n textarea.value.style.height = \"1px\";\n textareaScrollHeight.value = (_a = textarea.value) == null ? void 0 : _a.scrollHeight;\n if (options == null ? void 0 : options.styleTarget)\n unref(options.styleTarget).style.height = `${textareaScrollHeight.value}px`;\n else\n height = `${textareaScrollHeight.value}px`;\n textarea.value.style.height = height;\n (_b = options == null ? void 0 : options.onResize) == null ? void 0 : _b.call(options);\n }\n watch([input, textarea], triggerResize, { immediate: true });\n useResizeObserver(textarea, () => triggerResize());\n if (options == null ? void 0 : options.watch)\n watch(options.watch, triggerResize, { immediate: true, deep: true });\n return {\n textarea,\n input,\n triggerResize\n };\n}\n\nvar __defProp$3 = Object.defineProperty;\nvar __defProps$1 = Object.defineProperties;\nvar __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$3 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$3 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$3 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$3.call(b, prop))\n __defNormalProp$3(a, prop, b[prop]);\n if (__getOwnPropSymbols$3)\n for (var prop of __getOwnPropSymbols$3(b)) {\n if (__propIsEnum$3.call(b, prop))\n __defNormalProp$3(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));\nfunction useThrottledRefHistory(source, options = {}) {\n const { throttle = 200, trailing = true } = options;\n const filter = throttleFilter(throttle, trailing);\n const history = useRefHistory(source, __spreadProps$1(__spreadValues$3({}, options), { eventFilter: filter }));\n return __spreadValues$3({}, history);\n}\n\nvar __defProp$2 = Object.defineProperty;\nvar __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$2 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$2 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$2 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$2.call(b, prop))\n __defNormalProp$2(a, prop, b[prop]);\n if (__getOwnPropSymbols$2)\n for (var prop of __getOwnPropSymbols$2(b)) {\n if (__propIsEnum$2.call(b, prop))\n __defNormalProp$2(a, prop, b[prop]);\n }\n return a;\n};\nvar __objRest = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols$2)\n for (var prop of __getOwnPropSymbols$2(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nconst DEFAULT_UNITS = [\n { max: 6e4, value: 1e3, name: \"second\" },\n { max: 276e4, value: 6e4, name: \"minute\" },\n { max: 72e6, value: 36e5, name: \"hour\" },\n { max: 5184e5, value: 864e5, name: \"day\" },\n { max: 24192e5, value: 6048e5, name: \"week\" },\n { max: 28512e6, value: 2592e6, name: \"month\" },\n { max: Infinity, value: 31536e6, name: \"year\" }\n];\nconst DEFAULT_MESSAGES = {\n justNow: \"just now\",\n past: (n) => n.match(/\\d/) ? `${n} ago` : n,\n future: (n) => n.match(/\\d/) ? `in ${n}` : n,\n month: (n, past) => n === 1 ? past ? \"last month\" : \"next month\" : `${n} month${n > 1 ? \"s\" : \"\"}`,\n year: (n, past) => n === 1 ? past ? \"last year\" : \"next year\" : `${n} year${n > 1 ? \"s\" : \"\"}`,\n day: (n, past) => n === 1 ? past ? \"yesterday\" : \"tomorrow\" : `${n} day${n > 1 ? \"s\" : \"\"}`,\n week: (n, past) => n === 1 ? past ? \"last week\" : \"next week\" : `${n} week${n > 1 ? \"s\" : \"\"}`,\n hour: (n) => `${n} hour${n > 1 ? \"s\" : \"\"}`,\n minute: (n) => `${n} minute${n > 1 ? \"s\" : \"\"}`,\n second: (n) => `${n} second${n > 1 ? \"s\" : \"\"}`,\n invalid: \"\"\n};\nconst DEFAULT_FORMATTER = (date) => date.toISOString().slice(0, 10);\nfunction useTimeAgo(time, options = {}) {\n const {\n controls: exposeControls = false,\n updateInterval = 3e4\n } = options;\n const _a = useNow({ interval: updateInterval, controls: true }), { now } = _a, controls = __objRest(_a, [\"now\"]);\n const timeAgo = computed(() => formatTimeAgo(new Date(resolveUnref(time)), options, unref(now.value)));\n if (exposeControls) {\n return __spreadValues$2({\n timeAgo\n }, controls);\n } else {\n return timeAgo;\n }\n}\nfunction formatTimeAgo(from, options = {}, now = Date.now()) {\n var _a;\n const {\n max,\n messages = DEFAULT_MESSAGES,\n fullDateFormatter = DEFAULT_FORMATTER,\n units = DEFAULT_UNITS,\n showSecond = false,\n rounding = \"round\"\n } = options;\n const roundFn = typeof rounding === \"number\" ? (n) => +n.toFixed(rounding) : Math[rounding];\n const diff = +now - +from;\n const absDiff = Math.abs(diff);\n function getValue(diff2, unit) {\n return roundFn(Math.abs(diff2) / unit.value);\n }\n function format(diff2, unit) {\n const val = getValue(diff2, unit);\n const past = diff2 > 0;\n const str = applyFormat(unit.name, val, past);\n return applyFormat(past ? \"past\" : \"future\", str, past);\n }\n function applyFormat(name, val, isPast) {\n const formatter = messages[name];\n if (typeof formatter === \"function\")\n return formatter(val, isPast);\n return formatter.replace(\"{0}\", val.toString());\n }\n if (absDiff < 6e4 && !showSecond)\n return messages.justNow;\n if (typeof max === \"number\" && absDiff > max)\n return fullDateFormatter(new Date(from));\n if (typeof max === \"string\") {\n const unitMax = (_a = units.find((i) => i.name === max)) == null ? void 0 : _a.max;\n if (unitMax && absDiff > unitMax)\n return fullDateFormatter(new Date(from));\n }\n for (const [idx, unit] of units.entries()) {\n const val = getValue(diff, unit);\n if (val <= 0 && units[idx - 1])\n return format(diff, units[idx - 1]);\n if (absDiff < unit.max)\n return format(diff, unit);\n }\n return messages.invalid;\n}\n\nfunction useTimeoutPoll(fn, interval, timeoutPollOptions) {\n const { start } = useTimeoutFn(loop, interval);\n const isActive = ref(false);\n async function loop() {\n if (!isActive.value)\n return;\n await fn();\n start();\n }\n function resume() {\n if (!isActive.value) {\n isActive.value = true;\n loop();\n }\n }\n function pause() {\n isActive.value = false;\n }\n if (timeoutPollOptions == null ? void 0 : timeoutPollOptions.immediate)\n resume();\n tryOnScopeDispose(pause);\n return {\n isActive,\n pause,\n resume\n };\n}\n\nvar __defProp$1 = Object.defineProperty;\nvar __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;\nvar __hasOwnProp$1 = Object.prototype.hasOwnProperty;\nvar __propIsEnum$1 = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues$1 = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp$1.call(b, prop))\n __defNormalProp$1(a, prop, b[prop]);\n if (__getOwnPropSymbols$1)\n for (var prop of __getOwnPropSymbols$1(b)) {\n if (__propIsEnum$1.call(b, prop))\n __defNormalProp$1(a, prop, b[prop]);\n }\n return a;\n};\nfunction useTimestamp(options = {}) {\n const {\n controls: exposeControls = false,\n offset = 0,\n immediate = true,\n interval = \"requestAnimationFrame\",\n callback\n } = options;\n const ts = ref(timestamp() + offset);\n const update = () => ts.value = timestamp() + offset;\n const cb = callback ? () => {\n update();\n callback(ts.value);\n } : update;\n const controls = interval === \"requestAnimationFrame\" ? useRafFn(cb, { immediate }) : useIntervalFn(cb, interval, { immediate });\n if (exposeControls) {\n return __spreadValues$1({\n timestamp: ts\n }, controls);\n } else {\n return ts;\n }\n}\n\nfunction useTitle(newTitle = null, options = {}) {\n var _a, _b;\n const {\n document = defaultDocument\n } = options;\n const title = resolveRef((_a = newTitle != null ? newTitle : document == null ? void 0 : document.title) != null ? _a : null);\n const isReadonly = newTitle && isFunction(newTitle);\n function format(t) {\n if (!(\"titleTemplate\" in options))\n return t;\n const template = options.titleTemplate || \"%s\";\n return isFunction(template) ? template(t) : unref(template).replace(/%s/g, t);\n }\n watch(title, (t, o) => {\n if (t !== o && document)\n document.title = format(isString(t) ? t : \"\");\n }, { immediate: true });\n if (options.observe && !options.titleTemplate && document && !isReadonly) {\n useMutationObserver((_b = document.head) == null ? void 0 : _b.querySelector(\"title\"), () => {\n if (document && document.title !== title.value)\n title.value = format(document.title);\n }, { childList: true });\n }\n return title;\n}\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst _TransitionPresets = {\n easeInSine: [0.12, 0, 0.39, 0],\n easeOutSine: [0.61, 1, 0.88, 1],\n easeInOutSine: [0.37, 0, 0.63, 1],\n easeInQuad: [0.11, 0, 0.5, 0],\n easeOutQuad: [0.5, 1, 0.89, 1],\n easeInOutQuad: [0.45, 0, 0.55, 1],\n easeInCubic: [0.32, 0, 0.67, 0],\n easeOutCubic: [0.33, 1, 0.68, 1],\n easeInOutCubic: [0.65, 0, 0.35, 1],\n easeInQuart: [0.5, 0, 0.75, 0],\n easeOutQuart: [0.25, 1, 0.5, 1],\n easeInOutQuart: [0.76, 0, 0.24, 1],\n easeInQuint: [0.64, 0, 0.78, 0],\n easeOutQuint: [0.22, 1, 0.36, 1],\n easeInOutQuint: [0.83, 0, 0.17, 1],\n easeInExpo: [0.7, 0, 0.84, 0],\n easeOutExpo: [0.16, 1, 0.3, 1],\n easeInOutExpo: [0.87, 0, 0.13, 1],\n easeInCirc: [0.55, 0, 1, 0.45],\n easeOutCirc: [0, 0.55, 0.45, 1],\n easeInOutCirc: [0.85, 0, 0.15, 1],\n easeInBack: [0.36, 0, 0.66, -0.56],\n easeOutBack: [0.34, 1.56, 0.64, 1],\n easeInOutBack: [0.68, -0.6, 0.32, 1.6]\n};\nconst TransitionPresets = /* @__PURE__ */ Object.assign({}, { linear: identity }, _TransitionPresets);\nfunction createEasingFunction([p0, p1, p2, p3]) {\n const a = (a1, a2) => 1 - 3 * a2 + 3 * a1;\n const b = (a1, a2) => 3 * a2 - 6 * a1;\n const c = (a1) => 3 * a1;\n const calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t;\n const getSlope = (t, a1, a2) => 3 * a(a1, a2) * t * t + 2 * b(a1, a2) * t + c(a1);\n const getTforX = (x) => {\n let aGuessT = x;\n for (let i = 0; i < 4; ++i) {\n const currentSlope = getSlope(aGuessT, p0, p2);\n if (currentSlope === 0)\n return aGuessT;\n const currentX = calcBezier(aGuessT, p0, p2) - x;\n aGuessT -= currentX / currentSlope;\n }\n return aGuessT;\n };\n return (x) => p0 === p1 && p2 === p3 ? x : calcBezier(getTforX(x), p1, p3);\n}\nconst lerp = (a, b, alpha) => a + alpha * (b - a);\nconst toVec = (t) => (isNumber(t) ? [t] : t) || [];\nfunction executeTransition(source, from, to, options = {}) {\n var _a, _b;\n const fromVal = unref(from);\n const toVal = unref(to);\n const v1 = toVec(fromVal);\n const v2 = toVec(toVal);\n const duration = (_a = unref(options.duration)) != null ? _a : 1e3;\n const startedAt = Date.now();\n const endAt = Date.now() + duration;\n const trans = (_b = unref(options.transition)) != null ? _b : identity;\n const ease = isFunction(trans) ? trans : createEasingFunction(trans);\n return new Promise((resolve) => {\n source.value = fromVal;\n const tick = () => {\n var _a2;\n if ((_a2 = options.abort) == null ? void 0 : _a2.call(options)) {\n resolve();\n return;\n }\n const now = Date.now();\n const alpha = ease((now - startedAt) / duration);\n const arr = toVec(source.value).map((n, i) => lerp(v1[i], v2[i], alpha));\n if (Array.isArray(source.value))\n source.value = arr.map((n, i) => {\n var _a3, _b2;\n return lerp((_a3 = v1[i]) != null ? _a3 : 0, (_b2 = v2[i]) != null ? _b2 : 0, alpha);\n });\n else if (isNumber(source.value))\n source.value = arr[0];\n if (now < endAt) {\n requestAnimationFrame(tick);\n } else {\n source.value = toVal;\n resolve();\n }\n };\n tick();\n });\n}\nfunction useTransition(source, options = {}) {\n let currentId = 0;\n const sourceVal = () => {\n const v = resolveUnref(source);\n return isNumber(v) ? v : v.map(resolveUnref);\n };\n const outputRef = ref(sourceVal());\n watch(sourceVal, async (to) => {\n var _a, _b;\n if (unref(options.disabled))\n return;\n const id = ++currentId;\n if (options.delay)\n await promiseTimeout(unref(options.delay));\n if (id !== currentId)\n return;\n const toVal = Array.isArray(to) ? to.map(resolveUnref) : resolveUnref(to);\n (_a = options.onStarted) == null ? void 0 : _a.call(options);\n await executeTransition(outputRef, outputRef.value, toVal, __spreadProps(__spreadValues({}, options), {\n abort: () => {\n var _a2;\n return id !== currentId || ((_a2 = options.abort) == null ? void 0 : _a2.call(options));\n }\n }));\n (_b = options.onFinished) == null ? void 0 : _b.call(options);\n }, { deep: true });\n watch(() => unref(options.disabled), (disabled) => {\n if (disabled) {\n currentId++;\n outputRef.value = sourceVal();\n }\n });\n tryOnScopeDispose(() => {\n currentId++;\n });\n return computed(() => unref(options.disabled) ? sourceVal() : outputRef.value);\n}\n\nfunction useUrlSearchParams(mode = \"history\", options = {}) {\n const {\n initialValue = {},\n removeNullishValues = true,\n removeFalsyValues = false,\n write: enableWrite = true,\n window = defaultWindow\n } = options;\n if (!window)\n return reactive(initialValue);\n const state = reactive({});\n function getRawParams() {\n if (mode === \"history\") {\n return window.location.search || \"\";\n } else if (mode === \"hash\") {\n const hash = window.location.hash || \"\";\n const index = hash.indexOf(\"?\");\n return index > 0 ? hash.slice(index) : \"\";\n } else {\n return (window.location.hash || \"\").replace(/^#/, \"\");\n }\n }\n function constructQuery(params) {\n const stringified = params.toString();\n if (mode === \"history\")\n return `${stringified ? `?${stringified}` : \"\"}${window.location.hash || \"\"}`;\n if (mode === \"hash-params\")\n return `${window.location.search || \"\"}${stringified ? `#${stringified}` : \"\"}`;\n const hash = window.location.hash || \"#\";\n const index = hash.indexOf(\"?\");\n if (index > 0)\n return `${hash.slice(0, index)}${stringified ? `?${stringified}` : \"\"}`;\n return `${hash}${stringified ? `?${stringified}` : \"\"}`;\n }\n function read() {\n return new URLSearchParams(getRawParams());\n }\n function updateState(params) {\n const unusedKeys = new Set(Object.keys(state));\n for (const key of params.keys()) {\n const paramsForKey = params.getAll(key);\n state[key] = paramsForKey.length > 1 ? paramsForKey : params.get(key) || \"\";\n unusedKeys.delete(key);\n }\n Array.from(unusedKeys).forEach((key) => delete state[key]);\n }\n const { pause, resume } = pausableWatch(state, () => {\n const params = new URLSearchParams(\"\");\n Object.keys(state).forEach((key) => {\n const mapEntry = state[key];\n if (Array.isArray(mapEntry))\n mapEntry.forEach((value) => params.append(key, value));\n else if (removeNullishValues && mapEntry == null)\n params.delete(key);\n else if (removeFalsyValues && !mapEntry)\n params.delete(key);\n else\n params.set(key, mapEntry);\n });\n write(params);\n }, { deep: true });\n function write(params, shouldUpdate) {\n pause();\n if (shouldUpdate)\n updateState(params);\n window.history.replaceState(window.history.state, window.document.title, window.location.pathname + constructQuery(params));\n resume();\n }\n function onChanged() {\n if (!enableWrite)\n return;\n write(read(), true);\n }\n useEventListener(window, \"popstate\", onChanged, false);\n if (mode !== \"history\")\n useEventListener(window, \"hashchange\", onChanged, false);\n const initial = read();\n if (initial.keys().next().value)\n updateState(initial);\n else\n Object.assign(state, initialValue);\n return state;\n}\n\nfunction useUserMedia(options = {}) {\n var _a, _b;\n const enabled = ref((_a = options.enabled) != null ? _a : false);\n const autoSwitch = ref((_b = options.autoSwitch) != null ? _b : true);\n const videoDeviceId = ref(options.videoDeviceId);\n const audioDeviceId = ref(options.audioDeviceId);\n const constraints = ref(options.constraints);\n const { navigator = defaultNavigator } = options;\n const isSupported = useSupported(() => {\n var _a2;\n return (_a2 = navigator == null ? void 0 : navigator.mediaDevices) == null ? void 0 : _a2.getUserMedia;\n });\n const stream = shallowRef();\n function getDeviceOptions(type) {\n switch (type) {\n case \"video\": {\n if (constraints.value)\n return constraints.value.video || false;\n if (videoDeviceId.value === \"none\" || videoDeviceId.value === false)\n return false;\n if (videoDeviceId.value == null)\n return true;\n return { deviceId: videoDeviceId.value };\n }\n case \"audio\": {\n if (constraints.value)\n return constraints.value.audio || false;\n if (audioDeviceId.value === \"none\" || audioDeviceId.value === false)\n return false;\n if (audioDeviceId.value == null)\n return true;\n return { deviceId: audioDeviceId.value };\n }\n }\n }\n async function _start() {\n if (!isSupported.value || stream.value)\n return;\n stream.value = await navigator.mediaDevices.getUserMedia({\n video: getDeviceOptions(\"video\"),\n audio: getDeviceOptions(\"audio\")\n });\n return stream.value;\n }\n function _stop() {\n var _a2;\n (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => t.stop());\n stream.value = void 0;\n }\n function stop() {\n _stop();\n enabled.value = false;\n }\n async function start() {\n await _start();\n if (stream.value)\n enabled.value = true;\n return stream.value;\n }\n async function restart() {\n _stop();\n return await start();\n }\n watch(enabled, (v) => {\n if (v)\n _start();\n else\n _stop();\n }, { immediate: true });\n watch([videoDeviceId, audioDeviceId, constraints], () => {\n if (autoSwitch.value && stream.value)\n restart();\n }, { immediate: true });\n return {\n isSupported,\n stream,\n start,\n stop,\n restart,\n videoDeviceId,\n audioDeviceId,\n constraints,\n enabled,\n autoSwitch\n };\n}\n\nfunction useVModel(props, key, emit, options = {}) {\n var _a, _b, _c, _d, _e;\n const {\n clone = false,\n passive = false,\n eventName,\n deep = false,\n defaultValue,\n shouldEmit\n } = options;\n const vm = getCurrentInstance();\n const _emit = emit || (vm == null ? void 0 : vm.emit) || ((_a = vm == null ? void 0 : vm.$emit) == null ? void 0 : _a.bind(vm)) || ((_c = (_b = vm == null ? void 0 : vm.proxy) == null ? void 0 : _b.$emit) == null ? void 0 : _c.bind(vm == null ? void 0 : vm.proxy));\n let event = eventName;\n if (!key) {\n if (isVue2) {\n const modelOptions = (_e = (_d = vm == null ? void 0 : vm.proxy) == null ? void 0 : _d.$options) == null ? void 0 : _e.model;\n key = (modelOptions == null ? void 0 : modelOptions.value) || \"value\";\n if (!eventName)\n event = (modelOptions == null ? void 0 : modelOptions.event) || \"input\";\n } else {\n key = \"modelValue\";\n }\n }\n event = eventName || event || `update:${key.toString()}`;\n const cloneFn = (val) => !clone ? val : isFunction(clone) ? clone(val) : cloneFnJSON(val);\n const getValue = () => isDef(props[key]) ? cloneFn(props[key]) : defaultValue;\n const triggerEmit = (value) => {\n if (shouldEmit) {\n if (shouldEmit(value))\n _emit(event, value);\n } else {\n _emit(event, value);\n }\n };\n if (passive) {\n const initialValue = getValue();\n const proxy = ref(initialValue);\n watch(() => props[key], (v) => proxy.value = cloneFn(v));\n watch(proxy, (v) => {\n if (v !== props[key] || deep)\n triggerEmit(v);\n }, { deep });\n return proxy;\n } else {\n return computed({\n get() {\n return getValue();\n },\n set(value) {\n triggerEmit(value);\n }\n });\n }\n}\n\nfunction useVModels(props, emit, options = {}) {\n const ret = {};\n for (const key in props)\n ret[key] = useVModel(props, key, emit, options);\n return ret;\n}\n\nfunction useVibrate(options) {\n const {\n pattern = [],\n interval = 0,\n navigator = defaultNavigator\n } = options || {};\n const isSupported = useSupported(() => typeof navigator !== \"undefined\" && \"vibrate\" in navigator);\n const patternRef = resolveRef(pattern);\n let intervalControls;\n const vibrate = (pattern2 = patternRef.value) => {\n if (isSupported.value)\n navigator.vibrate(pattern2);\n };\n const stop = () => {\n if (isSupported.value)\n navigator.vibrate(0);\n intervalControls == null ? void 0 : intervalControls.pause();\n };\n if (interval > 0) {\n intervalControls = useIntervalFn(vibrate, interval, {\n immediate: false,\n immediateCallback: false\n });\n }\n return {\n isSupported,\n pattern,\n intervalControls,\n vibrate,\n stop\n };\n}\n\nfunction useVirtualList(list, options) {\n const { containerStyle, wrapperProps, scrollTo, calculateRange, currentList, containerRef } = \"itemHeight\" in options ? useVerticalVirtualList(options, list) : useHorizontalVirtualList(options, list);\n return {\n list: currentList,\n scrollTo,\n containerProps: {\n ref: containerRef,\n onScroll: () => {\n calculateRange();\n },\n style: containerStyle\n },\n wrapperProps\n };\n}\nfunction useVirtualListResources(list) {\n const containerRef = ref(null);\n const size = useElementSize(containerRef);\n const currentList = ref([]);\n const source = shallowRef(list);\n const state = ref({ start: 0, end: 10 });\n return { state, source, currentList, size, containerRef };\n}\nfunction createGetViewCapacity(state, source, itemSize) {\n return (containerSize) => {\n if (typeof itemSize === \"number\")\n return Math.ceil(containerSize / itemSize);\n const { start = 0 } = state.value;\n let sum = 0;\n let capacity = 0;\n for (let i = start; i < source.value.length; i++) {\n const size = itemSize(i);\n sum += size;\n capacity = i;\n if (sum > containerSize)\n break;\n }\n return capacity - start;\n };\n}\nfunction createGetOffset(source, itemSize) {\n return (scrollDirection) => {\n if (typeof itemSize === \"number\")\n return Math.floor(scrollDirection / itemSize) + 1;\n let sum = 0;\n let offset = 0;\n for (let i = 0; i < source.value.length; i++) {\n const size = itemSize(i);\n sum += size;\n if (sum >= scrollDirection) {\n offset = i;\n break;\n }\n }\n return offset + 1;\n };\n}\nfunction createCalculateRange(type, overscan, getOffset, getViewCapacity, { containerRef, state, currentList, source }) {\n return () => {\n const element = containerRef.value;\n if (element) {\n const offset = getOffset(type === \"vertical\" ? element.scrollTop : element.scrollLeft);\n const viewCapacity = getViewCapacity(type === \"vertical\" ? element.clientHeight : element.clientWidth);\n const from = offset - overscan;\n const to = offset + viewCapacity + overscan;\n state.value = {\n start: from < 0 ? 0 : from,\n end: to > source.value.length ? source.value.length : to\n };\n currentList.value = source.value.slice(state.value.start, state.value.end).map((ele, index) => ({\n data: ele,\n index: index + state.value.start\n }));\n }\n };\n}\nfunction createGetDistance(itemSize, source) {\n return (index) => {\n if (typeof itemSize === \"number\") {\n const size2 = index * itemSize;\n return size2;\n }\n const size = source.value.slice(0, index).reduce((sum, _, i) => sum + itemSize(i), 0);\n return size;\n };\n}\nfunction useWatchForSizes(size, list, calculateRange) {\n watch([size.width, size.height, list], () => {\n calculateRange();\n });\n}\nfunction createComputedTotalSize(itemSize, source) {\n return computed(() => {\n if (typeof itemSize === \"number\")\n return source.value.length * itemSize;\n return source.value.reduce((sum, _, index) => sum + itemSize(index), 0);\n });\n}\nconst scrollToDictionaryForElementScrollKey = {\n horizontal: \"scrollLeft\",\n vertical: \"scrollTop\"\n};\nfunction createScrollTo(type, calculateRange, getDistance, containerRef) {\n return (index) => {\n if (containerRef.value) {\n containerRef.value[scrollToDictionaryForElementScrollKey[type]] = getDistance(index);\n calculateRange();\n }\n };\n}\nfunction useHorizontalVirtualList(options, list) {\n const resources = useVirtualListResources(list);\n const { state, source, currentList, size, containerRef } = resources;\n const containerStyle = { overflowX: \"auto\" };\n const { itemWidth, overscan = 5 } = options;\n const getViewCapacity = createGetViewCapacity(state, source, itemWidth);\n const getOffset = createGetOffset(source, itemWidth);\n const calculateRange = createCalculateRange(\"horizontal\", overscan, getOffset, getViewCapacity, resources);\n const getDistanceLeft = createGetDistance(itemWidth, source);\n const offsetLeft = computed(() => getDistanceLeft(state.value.start));\n const totalWidth = createComputedTotalSize(itemWidth, source);\n useWatchForSizes(size, list, calculateRange);\n const scrollTo = createScrollTo(\"horizontal\", calculateRange, getDistanceLeft, containerRef);\n const wrapperProps = computed(() => {\n return {\n style: {\n height: \"100%\",\n width: `${totalWidth.value - offsetLeft.value}px`,\n marginLeft: `${offsetLeft.value}px`,\n display: \"flex\"\n }\n };\n });\n return {\n scrollTo,\n calculateRange,\n wrapperProps,\n containerStyle,\n currentList,\n containerRef\n };\n}\nfunction useVerticalVirtualList(options, list) {\n const resources = useVirtualListResources(list);\n const { state, source, currentList, size, containerRef } = resources;\n const containerStyle = { overflowY: \"auto\" };\n const { itemHeight, overscan = 5 } = options;\n const getViewCapacity = createGetViewCapacity(state, source, itemHeight);\n const getOffset = createGetOffset(source, itemHeight);\n const calculateRange = createCalculateRange(\"vertical\", overscan, getOffset, getViewCapacity, resources);\n const getDistanceTop = createGetDistance(itemHeight, source);\n const offsetTop = computed(() => getDistanceTop(state.value.start));\n const totalHeight = createComputedTotalSize(itemHeight, source);\n useWatchForSizes(size, list, calculateRange);\n const scrollTo = createScrollTo(\"vertical\", calculateRange, getDistanceTop, containerRef);\n const wrapperProps = computed(() => {\n return {\n style: {\n width: \"100%\",\n height: `${totalHeight.value - offsetTop.value}px`,\n marginTop: `${offsetTop.value}px`\n }\n };\n });\n return {\n calculateRange,\n scrollTo,\n containerStyle,\n wrapperProps,\n currentList,\n containerRef\n };\n}\n\nconst useWakeLock = (options = {}) => {\n const {\n navigator = defaultNavigator,\n document = defaultDocument\n } = options;\n let wakeLock;\n const isSupported = useSupported(() => navigator && \"wakeLock\" in navigator);\n const isActive = ref(false);\n async function onVisibilityChange() {\n if (!isSupported.value || !wakeLock)\n return;\n if (document && document.visibilityState === \"visible\")\n wakeLock = await navigator.wakeLock.request(\"screen\");\n isActive.value = !wakeLock.released;\n }\n if (document)\n useEventListener(document, \"visibilitychange\", onVisibilityChange, { passive: true });\n async function request(type) {\n if (!isSupported.value)\n return;\n wakeLock = await navigator.wakeLock.request(type);\n isActive.value = !wakeLock.released;\n }\n async function release() {\n if (!isSupported.value || !wakeLock)\n return;\n await wakeLock.release();\n isActive.value = !wakeLock.released;\n wakeLock = null;\n }\n return {\n isSupported,\n isActive,\n request,\n release\n };\n};\n\nconst useWebNotification = (defaultOptions = {}) => {\n const {\n window = defaultWindow\n } = defaultOptions;\n const isSupported = useSupported(() => !!window && \"Notification\" in window);\n const notification = ref(null);\n const requestPermission = async () => {\n if (!isSupported.value)\n return;\n if (\"permission\" in Notification && Notification.permission !== \"denied\")\n await Notification.requestPermission();\n };\n const { on: onClick, trigger: clickTrigger } = createEventHook();\n const { on: onShow, trigger: showTrigger } = createEventHook();\n const { on: onError, trigger: errorTrigger } = createEventHook();\n const { on: onClose, trigger: closeTrigger } = createEventHook();\n const show = async (overrides) => {\n if (!isSupported.value)\n return;\n await requestPermission();\n const options = Object.assign({}, defaultOptions, overrides);\n notification.value = new Notification(options.title || \"\", options);\n notification.value.onclick = clickTrigger;\n notification.value.onshow = showTrigger;\n notification.value.onerror = errorTrigger;\n notification.value.onclose = closeTrigger;\n return notification.value;\n };\n const close = () => {\n if (notification.value)\n notification.value.close();\n notification.value = null;\n };\n tryOnMounted(async () => {\n if (isSupported.value)\n await requestPermission();\n });\n tryOnScopeDispose(close);\n if (isSupported.value && window) {\n const document = window.document;\n useEventListener(document, \"visibilitychange\", (e) => {\n e.preventDefault();\n if (document.visibilityState === \"visible\") {\n close();\n }\n });\n }\n return {\n isSupported,\n notification,\n show,\n close,\n onClick,\n onShow,\n onError,\n onClose\n };\n};\n\nconst DEFAULT_PING_MESSAGE = \"ping\";\nfunction resolveNestedOptions(options) {\n if (options === true)\n return {};\n return options;\n}\nfunction useWebSocket(url, options = {}) {\n const {\n onConnected,\n onDisconnected,\n onError,\n onMessage,\n immediate = true,\n autoClose = true,\n protocols = []\n } = options;\n const data = ref(null);\n const status = ref(\"CLOSED\");\n const wsRef = ref();\n const urlRef = resolveRef(url);\n let heartbeatPause;\n let heartbeatResume;\n let explicitlyClosed = false;\n let retried = 0;\n let bufferedData = [];\n let pongTimeoutWait;\n const close = (code = 1e3, reason) => {\n if (!wsRef.value)\n return;\n explicitlyClosed = true;\n heartbeatPause == null ? void 0 : heartbeatPause();\n wsRef.value.close(code, reason);\n };\n const _sendBuffer = () => {\n if (bufferedData.length && wsRef.value && status.value === \"OPEN\") {\n for (const buffer of bufferedData)\n wsRef.value.send(buffer);\n bufferedData = [];\n }\n };\n const resetHeartbeat = () => {\n clearTimeout(pongTimeoutWait);\n pongTimeoutWait = void 0;\n };\n const send = (data2, useBuffer = true) => {\n if (!wsRef.value || status.value !== \"OPEN\") {\n if (useBuffer)\n bufferedData.push(data2);\n return false;\n }\n _sendBuffer();\n wsRef.value.send(data2);\n return true;\n };\n const _init = () => {\n if (explicitlyClosed || typeof urlRef.value === \"undefined\")\n return;\n const ws = new WebSocket(urlRef.value, protocols);\n wsRef.value = ws;\n status.value = \"CONNECTING\";\n ws.onopen = () => {\n status.value = \"OPEN\";\n onConnected == null ? void 0 : onConnected(ws);\n heartbeatResume == null ? void 0 : heartbeatResume();\n _sendBuffer();\n };\n ws.onclose = (ev) => {\n status.value = \"CLOSED\";\n wsRef.value = void 0;\n onDisconnected == null ? void 0 : onDisconnected(ws, ev);\n if (!explicitlyClosed && options.autoReconnect) {\n const {\n retries = -1,\n delay = 1e3,\n onFailed\n } = resolveNestedOptions(options.autoReconnect);\n retried += 1;\n if (typeof retries === \"number\" && (retries < 0 || retried < retries))\n setTimeout(_init, delay);\n else if (typeof retries === \"function\" && retries())\n setTimeout(_init, delay);\n else\n onFailed == null ? void 0 : onFailed();\n }\n };\n ws.onerror = (e) => {\n onError == null ? void 0 : onError(ws, e);\n };\n ws.onmessage = (e) => {\n if (options.heartbeat) {\n resetHeartbeat();\n const {\n message = DEFAULT_PING_MESSAGE\n } = resolveNestedOptions(options.heartbeat);\n if (e.data === message)\n return;\n }\n data.value = e.data;\n onMessage == null ? void 0 : onMessage(ws, e);\n };\n };\n if (options.heartbeat) {\n const {\n message = DEFAULT_PING_MESSAGE,\n interval = 1e3,\n pongTimeout = 1e3\n } = resolveNestedOptions(options.heartbeat);\n const { pause, resume } = useIntervalFn(() => {\n send(message, false);\n if (pongTimeoutWait != null)\n return;\n pongTimeoutWait = setTimeout(() => {\n close();\n }, pongTimeout);\n }, interval, { immediate: false });\n heartbeatPause = pause;\n heartbeatResume = resume;\n }\n if (autoClose) {\n useEventListener(window, \"beforeunload\", () => close());\n tryOnScopeDispose(close);\n }\n const open = () => {\n close();\n explicitlyClosed = false;\n retried = 0;\n _init();\n };\n if (immediate)\n watch(urlRef, open, { immediate: true });\n return {\n data,\n status,\n close,\n send,\n open,\n ws: wsRef\n };\n}\n\nfunction useWebWorker(arg0, workerOptions, options) {\n const {\n window = defaultWindow\n } = options != null ? options : {};\n const data = ref(null);\n const worker = shallowRef();\n const post = function post2(val) {\n if (!worker.value)\n return;\n worker.value.postMessage(val);\n };\n const terminate = function terminate2() {\n if (!worker.value)\n return;\n worker.value.terminate();\n };\n if (window) {\n if (isString(arg0))\n worker.value = new Worker(arg0, workerOptions);\n else if (isFunction(arg0))\n worker.value = arg0();\n else\n worker.value = arg0;\n worker.value.onmessage = (e) => {\n data.value = e.data;\n };\n tryOnScopeDispose(() => {\n if (worker.value)\n worker.value.terminate();\n });\n }\n return {\n data,\n post,\n terminate,\n worker\n };\n}\n\nconst jobRunner = (userFunc) => (e) => {\n const userFuncArgs = e.data[0];\n return Promise.resolve(userFunc.apply(void 0, userFuncArgs)).then((result) => {\n postMessage([\"SUCCESS\", result]);\n }).catch((error) => {\n postMessage([\"ERROR\", error]);\n });\n};\n\nconst depsParser = (deps) => {\n if (deps.length === 0)\n return \"\";\n const depsString = deps.map((dep) => `'${dep}'`).toString();\n return `importScripts(${depsString})`;\n};\n\nconst createWorkerBlobUrl = (fn, deps) => {\n const blobCode = `${depsParser(deps)}; onmessage=(${jobRunner})(${fn})`;\n const blob = new Blob([blobCode], { type: \"text/javascript\" });\n const url = URL.createObjectURL(blob);\n return url;\n};\n\nconst useWebWorkerFn = (fn, options = {}) => {\n const {\n dependencies = [],\n timeout,\n window = defaultWindow\n } = options;\n const worker = ref();\n const workerStatus = ref(\"PENDING\");\n const promise = ref({});\n const timeoutId = ref();\n const workerTerminate = (status = \"PENDING\") => {\n if (worker.value && worker.value._url && window) {\n worker.value.terminate();\n URL.revokeObjectURL(worker.value._url);\n promise.value = {};\n worker.value = void 0;\n window.clearTimeout(timeoutId.value);\n workerStatus.value = status;\n }\n };\n workerTerminate();\n tryOnScopeDispose(workerTerminate);\n const generateWorker = () => {\n const blobUrl = createWorkerBlobUrl(fn, dependencies);\n const newWorker = new Worker(blobUrl);\n newWorker._url = blobUrl;\n newWorker.onmessage = (e) => {\n const { resolve = () => {\n }, reject = () => {\n } } = promise.value;\n const [status, result] = e.data;\n switch (status) {\n case \"SUCCESS\":\n resolve(result);\n workerTerminate(status);\n break;\n default:\n reject(result);\n workerTerminate(\"ERROR\");\n break;\n }\n };\n newWorker.onerror = (e) => {\n const { reject = () => {\n } } = promise.value;\n reject(e);\n workerTerminate(\"ERROR\");\n };\n if (timeout) {\n timeoutId.value = setTimeout(() => workerTerminate(\"TIMEOUT_EXPIRED\"), timeout);\n }\n return newWorker;\n };\n const callWorker = (...fnArgs) => new Promise((resolve, reject) => {\n promise.value = {\n resolve,\n reject\n };\n worker.value && worker.value.postMessage([[...fnArgs]]);\n workerStatus.value = \"RUNNING\";\n });\n const workerFn = (...fnArgs) => {\n if (workerStatus.value === \"RUNNING\") {\n console.error(\"[useWebWorkerFn] You can only run one instance of the worker at a time.\");\n return Promise.reject();\n }\n worker.value = generateWorker();\n return callWorker(...fnArgs);\n };\n return {\n workerFn,\n workerStatus,\n workerTerminate\n };\n};\n\nfunction useWindowFocus({ window = defaultWindow } = {}) {\n if (!window)\n return ref(false);\n const focused = ref(window.document.hasFocus());\n useEventListener(window, \"blur\", () => {\n focused.value = false;\n });\n useEventListener(window, \"focus\", () => {\n focused.value = true;\n });\n return focused;\n}\n\nfunction useWindowScroll({ window = defaultWindow } = {}) {\n if (!window) {\n return {\n x: ref(0),\n y: ref(0)\n };\n }\n const x = ref(window.scrollX);\n const y = ref(window.scrollY);\n useEventListener(window, \"scroll\", () => {\n x.value = window.scrollX;\n y.value = window.scrollY;\n }, {\n capture: false,\n passive: true\n });\n return { x, y };\n}\n\nfunction useWindowSize(options = {}) {\n const {\n window = defaultWindow,\n initialWidth = Infinity,\n initialHeight = Infinity,\n listenOrientation = true,\n includeScrollbar = true\n } = options;\n const width = ref(initialWidth);\n const height = ref(initialHeight);\n const update = () => {\n if (window) {\n if (includeScrollbar) {\n width.value = window.innerWidth;\n height.value = window.innerHeight;\n } else {\n width.value = window.document.documentElement.clientWidth;\n height.value = window.document.documentElement.clientHeight;\n }\n }\n };\n update();\n tryOnMounted(update);\n useEventListener(\"resize\", update, { passive: true });\n if (listenOrientation)\n useEventListener(\"orientationchange\", update, { passive: true });\n return { width, height };\n}\n\nexport { DefaultMagicKeysAliasMap, StorageSerializers, TransitionPresets, computedAsync as asyncComputed, breakpointsAntDesign, breakpointsBootstrapV5, breakpointsMasterCss, breakpointsQuasar, breakpointsSematic, breakpointsTailwind, breakpointsVuetify, cloneFnJSON, computedAsync, computedInject, createFetch, createUnrefFn, customStorageEventName, defaultDocument, defaultLocation, defaultNavigator, defaultWindow, executeTransition, formatTimeAgo, getSSRHandler, mapGamepadToXbox360Controller, onClickOutside, onKeyDown, onKeyPressed, onKeyStroke, onKeyUp, onLongPress, onStartTyping, setSSRHandler, templateRef, unrefElement, useActiveElement, useAsyncQueue, useAsyncState, useBase64, useBattery, useBluetooth, useBreakpoints, useBroadcastChannel, useBrowserLocation, useCached, useClipboard, useCloned, useColorMode, useConfirmDialog, useCssVar, useCurrentElement, useCycleList, useDark, useDebouncedRefHistory, useDeviceMotion, useDeviceOrientation, useDevicePixelRatio, useDevicesList, useDisplayMedia, useDocumentVisibility, useDraggable, useDropZone, useElementBounding, useElementByPoint, useElementHover, useElementSize, useElementVisibility, useEventBus, useEventListener, useEventSource, useEyeDropper, useFavicon, useFetch, useFileDialog, useFileSystemAccess, useFocus, useFocusWithin, useFps, useFullscreen, useGamepad, useGeolocation, useIdle, useImage, useInfiniteScroll, useIntersectionObserver, useKeyModifier, useLocalStorage, useMagicKeys, useManualRefHistory, useMediaControls, useMediaQuery, useMemoize, useMemory, useMounted, useMouse, useMouseInElement, useMousePressed, useMutationObserver, useNavigatorLanguage, useNetwork, useNow, useObjectUrl, useOffsetPagination, useOnline, usePageLeave, useParallax, useParentElement, usePerformanceObserver, usePermission, usePointer, usePointerLock, usePointerSwipe, usePreferredColorScheme, usePreferredContrast, usePreferredDark, usePreferredLanguages, usePreferredReducedMotion, usePrevious, useRafFn, useRefHistory, useResizeObserver, useScreenOrientation, useScreenSafeArea, useScriptTag, useScroll, useScrollLock, useSessionStorage, useShare, useSorted, useSpeechRecognition, useSpeechSynthesis, useStepper, useStorage, useStorageAsync, useStyleTag, useSupported, useSwipe, useTemplateRefsList, useTextDirection, useTextSelection, useTextareaAutosize, useThrottledRefHistory, useTimeAgo, useTimeoutPoll, useTimestamp, useTitle, useTransition, useUrlSearchParams, useUserMedia, useVModel, useVModels, useVibrate, useVirtualList, useWakeLock, useWebNotification, useWebSocket, useWebWorker, useWebWorkerFn, useWindowFocus, useWindowScroll, useWindowSize };\n","\n\n\n\n","\n\n\n\n","\n\n\n\n","\n\n\n\n","export default \"__VITE_PUBLIC_ASSET__420f1010__\"","export default \"__VITE_PUBLIC_ASSET__2d7e23d2__\"","export default \"__VITE_PUBLIC_ASSET__e9dace51__\"","\n\n\n\n","\n\n","import { defineComponent, ref, onMounted, h } from 'vue-demi';\n\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\nvar defer = function defer() {\n var state = false; // Resolved or not\n\n var callbacks = [];\n\n var resolve = function resolve() {\n if (state) {\n return;\n }\n\n state = true;\n\n for (var i = 0, len = callbacks.length; i < len; i++) {\n callbacks[i]();\n }\n };\n\n var then = function then(cb) {\n if (!state) {\n callbacks.push(cb);\n return;\n }\n\n cb();\n };\n\n var deferred = {\n resolved: function resolved() {\n return state;\n },\n resolve: resolve,\n promise: {\n then: then\n }\n };\n return deferred;\n};\n\nvar ownProp = Object.prototype.hasOwnProperty;\nfunction createRecaptcha() {\n var deferred = defer();\n return {\n notify: function notify() {\n deferred.resolve();\n },\n wait: function wait() {\n return deferred.promise;\n },\n render: function render(ele, options, cb) {\n this.wait().then(function () {\n cb(window.grecaptcha.render(ele, options));\n });\n },\n reset: function reset(widgetId) {\n if (typeof widgetId === 'undefined') {\n return;\n }\n\n this.assertLoaded();\n this.wait().then(function () {\n return window.grecaptcha.reset(widgetId);\n });\n },\n execute: function execute(widgetId) {\n if (typeof widgetId === 'undefined') {\n return;\n }\n\n this.assertLoaded();\n this.wait().then(function () {\n return window.grecaptcha.execute(widgetId);\n });\n },\n checkRecaptchaLoad: function checkRecaptchaLoad() {\n if (ownProp.call(window, 'grecaptcha') && ownProp.call(window.grecaptcha, 'render')) {\n this.notify();\n }\n },\n assertLoaded: function assertLoaded() {\n if (!deferred.resolved()) {\n throw new Error('ReCAPTCHA has not been loaded');\n }\n }\n };\n}\nvar recaptcha = createRecaptcha();\n\nif (typeof window !== 'undefined') {\n window.vueRecaptchaApiLoaded = recaptcha.notify;\n}\n\nvar Recaptcha = defineComponent({\n name: 'VueRecaptcha',\n props: {\n sitekey: {\n type: String,\n required: true\n },\n theme: {\n type: String\n },\n badge: {\n type: String\n },\n type: {\n type: String\n },\n size: {\n type: String\n },\n tabindex: {\n type: String\n },\n loadRecaptchaScript: {\n type: Boolean,\n \"default\": true\n },\n recaptchaScriptId: {\n type: String,\n \"default\": '__RECAPTCHA_SCRIPT'\n },\n recaptchaHost: {\n type: String,\n \"default\": 'www.google.com'\n },\n language: {\n type: String,\n \"default\": ''\n }\n },\n emits: ['render', 'verify', 'expired', 'error'],\n setup: function setup(props, _ref) {\n var slots = _ref.slots,\n emit = _ref.emit;\n var root = ref(null);\n var widgetId = ref(null);\n\n var emitVerify = function emitVerify(response) {\n emit('verify', response);\n };\n\n var emitExpired = function emitExpired() {\n emit('expired');\n };\n\n var emitError = function emitError() {\n emit('error');\n };\n\n onMounted(function () {\n recaptcha.checkRecaptchaLoad();\n\n if (props.loadRecaptchaScript) {\n if (!document.getElementById(props.recaptchaScriptId)) {\n // Note: vueRecaptchaApiLoaded load callback name is per the latest documentation\n var script = document.createElement('script');\n script.id = props.recaptchaScriptId;\n script.src = \"https://\" + props.recaptchaHost + \"/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit&hl=\" + props.language;\n script.async = true;\n script.defer = true;\n document.head.appendChild(script);\n }\n }\n\n var opts = _extends({}, props, {\n callback: emitVerify,\n 'expired-callback': emitExpired,\n 'error-callback': emitError\n });\n\n var $root = root.value;\n var container = slots[\"default\"] ? $root.children[0] : $root;\n recaptcha.render(container, opts, function (id) {\n widgetId.value = id;\n emit('render', id);\n });\n });\n return {\n root: root,\n widgetId: widgetId,\n reset: function reset() {\n recaptcha.reset(widgetId.value);\n },\n execute: function execute() {\n recaptcha.execute(widgetId.value);\n }\n };\n },\n render: function render() {\n var defaultSlot = this.$slots[\"default\"];\n var defaultContent;\n\n if (typeof defaultSlot === 'function') {\n defaultContent = defaultSlot();\n } else {\n defaultContent = defaultSlot;\n }\n\n return h('div', {\n ref: 'root'\n }, defaultContent);\n }\n});\n\nexport { Recaptcha as VueRecaptcha };\n","export const checkBehavior = (behavior) => {\n return behavior === undefined || behavior === \"auto\" || behavior === \"instant\" || behavior === \"smooth\";\n};\nexport function elementScrollXY(x, y) {\n this.scrollLeft = x;\n this.scrollTop = y;\n}\nexport const failedExecute = (method, object, reason = \"cannot convert to dictionary.\") => `Failed to execute '${method}' on '${object}': ${reason}`;\nexport const failedExecuteInvalidEnumValue = (method, object, value) => failedExecute(method, object, `The provided value '${value}' is not a valid enum value of type ScrollBehavior.`);\n/* eslint-disable */\nexport const backupMethod = (proto, method, fallback) => {\n var _a;\n const backup = `__SEAMLESS.BACKUP$${method}`;\n if (!proto[backup] && proto[method] && !((_a = proto[method]) === null || _a === void 0 ? void 0 : _a.__isPolyfill)) {\n proto[backup] = proto[method];\n }\n return proto[backup] || fallback;\n};\n/* eslint-enable */\nexport const isObject = (value) => {\n const type = typeof value;\n return value !== null && (type === \"object\" || type === \"function\");\n};\nexport const isScrollBehaviorSupported = (config) => \"scrollBehavior\" in window.document.documentElement.style && (config === null || config === void 0 ? void 0 : config.forcePolyfill) !== true;\nexport const markPolyfill = (method) => {\n Object.defineProperty(method, \"__isPolyfill\", { value: true });\n};\nexport const modifyPrototypes = (prop, func) => {\n markPolyfill(func);\n [HTMLElement.prototype, SVGElement.prototype, Element.prototype].forEach((prototype) => {\n backupMethod(prototype, prop);\n prototype[prop] = func;\n });\n};\n/**\n * - On Chrome and Firefox, document.scrollingElement will return the element.\n * - Safari, document.scrollingElement will return the element.\n * - On Edge, document.scrollingElement will return the element.\n * - IE11 does not support document.scrollingElement, but you can assume its .\n */\nexport const scrollingElement = (element) => element.ownerDocument.scrollingElement || element.ownerDocument.documentElement;\n//# sourceMappingURL=common.js.map","export function scrollEndEvent(bubbles) {\n if (typeof Event === \"function\") {\n return new Event(\"scrollend\", {\n bubbles,\n cancelable: false,\n });\n }\n const event = document.createEvent(\"Event\");\n event.initEvent(\"scrollend\", bubbles, false);\n return event;\n}\n//# sourceMappingURL=scroll-end-event.js.map","const ease = (k) => {\n return 0.5 * (1 - Math.cos(Math.PI * k));\n};\n/* eslint-disable */\nexport function now() {\n var _a;\n let fn;\n if ((_a = window.performance) === null || _a === void 0 ? void 0 : _a.now) {\n fn = () => window.performance.now();\n }\n else {\n fn = () => window.Date.now();\n }\n // @ts-ignore\n now = fn;\n return fn();\n}\n/* eslint-enable */\nconst DURATION = 500;\nexport const step = (context) => {\n const currentTime = now();\n const elapsed = (currentTime - context.timeStamp) / (context.duration || DURATION);\n if (elapsed > 1) {\n context.method(context.targetX, context.targetY);\n context.callback();\n return;\n }\n const value = (context.timingFunc || ease)(elapsed);\n const currentX = context.startX + (context.targetX - context.startX) * value;\n const currentY = context.startY + (context.targetY - context.startY) * value;\n context.method(currentX, currentY);\n context.rafId = window.requestAnimationFrame(() => {\n step(context);\n });\n};\n//# sourceMappingURL=scroll-step.js.map","import { backupMethod, checkBehavior, elementScrollXY, failedExecute, failedExecuteInvalidEnumValue, isObject, scrollingElement, } from \"./common.js\";\nimport { scrollEndEvent } from \"./scroll-end-event.js\";\nimport { now, step } from \"./scroll-step.js\";\n// https://drafts.csswg.org/cssom-view/#normalize-non-finite-values\nconst nonFinite = (value) => {\n if (!isFinite(value)) {\n return 0;\n }\n return Number(value);\n};\nconst isConnected = (node) => {\n var _a;\n return ((_a = node.isConnected) !== null && _a !== void 0 ? _a : (!node.ownerDocument ||\n // eslint-disable-next-line no-bitwise\n !(node.ownerDocument.compareDocumentPosition(node) & /** DOCUMENT_POSITION_DISCONNECTED */ 1)));\n};\nconst scrollWithOptions = (element, options, config) => {\n var _a, _b;\n if (!isConnected(element)) {\n return;\n }\n const startX = element.scrollLeft;\n const startY = element.scrollTop;\n const targetX = nonFinite((_a = options.left) !== null && _a !== void 0 ? _a : startX);\n const targetY = nonFinite((_b = options.top) !== null && _b !== void 0 ? _b : startY);\n if (targetX === startX && targetY === startY) {\n return;\n }\n const fallback = backupMethod(HTMLElement.prototype, \"scroll\", elementScrollXY);\n const method = backupMethod(Object.getPrototypeOf(element), \"scroll\", fallback).bind(element);\n if (options.behavior !== \"smooth\") {\n method(targetX, targetY);\n return;\n }\n const removeEventListener = () => {\n window.removeEventListener(\"wheel\", cancelScroll);\n window.removeEventListener(\"touchmove\", cancelScroll);\n };\n const callback = () => {\n removeEventListener();\n const isDocument = element.nodeType === /** Node.DOCUMENT_NODE */ 9;\n element.dispatchEvent(scrollEndEvent(isDocument));\n };\n const context = Object.assign(Object.assign({}, config), { timeStamp: now(), startX,\n startY,\n targetX,\n targetY, rafId: 0, method,\n callback });\n const cancelScroll = () => {\n window.cancelAnimationFrame(context.rafId);\n removeEventListener();\n };\n window.addEventListener(\"wheel\", cancelScroll, {\n passive: true,\n once: true,\n });\n window.addEventListener(\"touchmove\", cancelScroll, {\n passive: true,\n once: true,\n });\n step(context);\n};\nconst isWindow = (obj) => obj.window === obj;\nconst createScroll = (scrollName) => (target, scrollOptions, config) => {\n const [element, scrollType] = isWindow(target)\n ? [scrollingElement(target.document.documentElement), \"Window\"]\n : [target, \"Element\"];\n const options = scrollOptions !== null && scrollOptions !== void 0 ? scrollOptions : {};\n if (!isObject(options)) {\n throw new TypeError(failedExecute(scrollName, scrollType));\n }\n if (!checkBehavior(options.behavior)) {\n throw new TypeError(failedExecuteInvalidEnumValue(scrollName, scrollType, options.behavior));\n }\n if (scrollName === \"scrollBy\") {\n options.left = nonFinite(options.left) + element.scrollLeft;\n options.top = nonFinite(options.top) + element.scrollTop;\n }\n scrollWithOptions(element, options, config);\n};\nexport const scroll = /* #__PURE__ */ createScroll(\"scroll\");\nexport const scrollTo = /* #__PURE__ */ createScroll(\"scrollTo\");\nexport const scrollBy = /* #__PURE__ */ createScroll(\"scrollBy\");\nexport const elementScroll = scroll;\nexport const elementScrollTo = scrollTo;\nexport const elementScrollBy = scrollBy;\nexport const windowScroll = scroll;\nexport const windowScrollTo = scrollTo;\nexport const windowScrollBy = scrollBy;\n//# sourceMappingURL=scroll.js.map","/* eslint-disable no-bitwise */\nimport { checkBehavior, failedExecuteInvalidEnumValue, scrollingElement } from \"./common.js\";\nimport { elementScroll } from \"./scroll.js\";\n// https://drafts.csswg.org/css-writing-modes-4/#block-flow\nconst normalizeWritingMode = (writingMode) => {\n switch (writingMode) {\n case \"horizontal-tb\":\n case \"lr\":\n case \"lr-tb\":\n case \"rl\":\n case \"rl-tb\":\n return 0 /* WritingMode.HorizontalTb */;\n case \"vertical-rl\":\n case \"tb\":\n case \"tb-rl\":\n return 1 /* WritingMode.VerticalRl */;\n case \"vertical-lr\":\n case \"tb-lr\":\n return 2 /* WritingMode.VerticalLr */;\n case \"sideways-rl\":\n return 3 /* WritingMode.SidewaysRl */;\n case \"sideways-lr\":\n return 4 /* WritingMode.SidewaysLr */;\n }\n return 0 /* WritingMode.HorizontalTb */;\n};\nconst calcPhysicalAxis = (writingMode, isLTR, hPos, vPos) => {\n /** 0b{vertical}{horizontal} 0: normal, 1: reverse */\n let layout = 0b00;\n /**\n * WritingMode.VerticalLr: ↓→\n * | 1 | 4 | |\n * | 2 | 5 | |\n * | 3 | | |\n *\n * RTL: ↑→\n * | 3 | | |\n * | 2 | 5 | |\n * | 1 | 4 | |\n */\n if (!isLTR) {\n layout ^= 2 /* OP.ReverseVertical */;\n }\n switch (writingMode) {\n /**\n * ↓→\n * | 1 | 2 | 3 |\n * | 4 | 5 | |\n * | | | |\n *\n * RTL: ↓←\n * | 3 | 2 | 1 |\n * | | 5 | 4 |\n * | | | |\n */\n case 0 /* WritingMode.HorizontalTb */:\n // swap horizontal and vertical\n layout = (layout >> 1) | ((layout & 1) << 1);\n [hPos, vPos] = [vPos, hPos];\n break;\n /**\n * ↓←\n * | | 4 | 1 |\n * | | 5 | 2 |\n * | | | 3 |\n *\n * RTL: ↑←\n * | | | 3 |\n * | | 5 | 2 |\n * | | 4 | 1 |\n */\n case 1 /* WritingMode.VerticalRl */:\n case 3 /* WritingMode.SidewaysRl */:\n // reverse horizontal\n layout ^= 1 /* OP.ReverseHorizontal */;\n break;\n /**\n * ↑→\n * | 3 | | |\n * | 2 | 5 | |\n * | 1 | 4 | |\n *\n * RTL: ↓→\n * | 1 | 4 | |\n * | 2 | 5 | |\n * | 3 | | |\n */\n case 4 /* WritingMode.SidewaysLr */:\n // reverse vertical\n layout ^= 2 /* OP.ReverseVertical */;\n break;\n }\n return [layout, hPos, vPos];\n};\nconst isXReversed = (computedStyle) => {\n const layout = calcPhysicalAxis(normalizeWritingMode(computedStyle.writingMode), computedStyle.direction !== \"rtl\", undefined, undefined)[0];\n return (layout & 1) === 1;\n};\n// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/dom/element.cc;l=1097-1189;drc=6a7533d4a1e9f2372223a9d912a9e53a6fa35ae0\nconst toPhysicalAlignment = (options, writingMode, isLTR) => {\n const [layout, hPos, vPos] = calcPhysicalAxis(writingMode, isLTR, options.block || \"start\", options.inline || \"nearest\");\n return [hPos, vPos].map((value, index) => {\n switch (value) {\n case \"center\":\n return 1 /* ScrollAlignment.CenterAlways */;\n case \"nearest\":\n return 0 /* ScrollAlignment.ToEdgeIfNeeded */;\n default: {\n const reverse = (layout >> index) & 1;\n return (value === \"start\") === !reverse ? 2 /* ScrollAlignment.LeftOrTop */ : 3 /* ScrollAlignment.RightOrBottom */;\n }\n }\n });\n};\n// code from stipsan/compute-scroll-into-view\n// https://github.com/stipsan/compute-scroll-into-view/blob/5396c6b78af5d0bbce11a7c4e93cc3146546fcd3/src/index.ts\n/**\n * Find out which edge to align against when logical scroll position is \"nearest\"\n * Interesting fact: \"nearest\" works similarily to \"if-needed\", if the element is fully visible it will not scroll it\n *\n * Legends:\n * ┌────────┐ ┏ ━ ━ ━ ┓\n * │ target │ frame\n * └────────┘ ┗ ━ ━ ━ ┛\n */\nconst mapNearest = (align, scrollingEdgeStart, scrollingEdgeEnd, scrollingSize, elementEdgeStart, elementEdgeEnd, elementSize) => {\n if (align !== 0 /* ScrollAlignment.ToEdgeIfNeeded */) {\n return align;\n }\n /**\n * If element edge A and element edge B are both outside scrolling box edge A and scrolling box edge B\n *\n * ┌──┐\n * ┏━│━━│━┓\n * │ │\n * ┃ │ │ ┃ do nothing\n * │ │\n * ┗━│━━│━┛\n * └──┘\n *\n * If element edge C and element edge D are both outside scrolling box edge C and scrolling box edge D\n *\n * ┏ ━ ━ ━ ━ ┓\n * ┌───────────┐\n * │┃ ┃│ do nothing\n * └───────────┘\n * ┗ ━ ━ ━ ━ ┛\n */\n if ((elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd) ||\n (elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd)) {\n return null;\n }\n /**\n * If element edge A is outside scrolling box edge A and element height is less than scrolling box height\n *\n * ┌──┐\n * ┏━│━━│━┓ ┏━┌━━┐━┓\n * └──┘ │ │\n * from ┃ ┃ to ┃ └──┘ ┃\n *\n * ┗━ ━━ ━┛ ┗━ ━━ ━┛\n *\n * If element edge B is outside scrolling box edge B and element height is greater than scrolling box height\n *\n * ┏━ ━━ ━┓ ┏━┌━━┐━┓\n * │ │\n * from ┃ ┌──┐ ┃ to ┃ │ │ ┃\n * │ │ │ │\n * ┗━│━━│━┛ ┗━│━━│━┛\n * │ │ └──┘\n * │ │\n * └──┘\n *\n * If element edge C is outside scrolling box edge C and element width is less than scrolling box width\n *\n * from to\n * ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓\n * ┌───┐ ┌───┐\n * │ ┃ │ ┃ ┃ │ ┃\n * └───┘ └───┘\n * ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛\n *\n * If element edge D is outside scrolling box edge D and element width is greater than scrolling box width\n *\n * from to\n * ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓\n * ┌───────────┐ ┌───────────┐\n * ┃ │ ┃ │ ┃ ┃ │\n * └───────────┘ └───────────┘\n * ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛\n */\n if ((elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize) ||\n (elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize)) {\n return 2 /* ScrollAlignment.LeftOrTop */;\n }\n /**\n * If element edge B is outside scrolling box edge B and element height is less than scrolling box height\n *\n * ┏━ ━━ ━┓ ┏━ ━━ ━┓\n *\n * from ┃ ┃ to ┃ ┌──┐ ┃\n * ┌──┐ │ │\n * ┗━│━━│━┛ ┗━└━━┘━┛\n * └──┘\n *\n * If element edge A is outside scrolling box edge A and element height is greater than scrolling box height\n *\n * ┌──┐\n * │ │\n * │ │ ┌──┐\n * ┏━│━━│━┓ ┏━│━━│━┓\n * │ │ │ │\n * from ┃ └──┘ ┃ to ┃ │ │ ┃\n * │ │\n * ┗━ ━━ ━┛ ┗━└━━┘━┛\n *\n * If element edge C is outside scrolling box edge C and element width is greater than scrolling box width\n *\n * from to\n * ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓\n * ┌───────────┐ ┌───────────┐\n * │ ┃ │ ┃ │ ┃ ┃\n * └───────────┘ └───────────┘\n * ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛\n *\n * If element edge D is outside scrolling box edge D and element width is less than scrolling box width\n *\n * from to\n * ┏ ━ ━ ━ ━ ┓ ┏ ━ ━ ━ ━ ┓\n * ┌───┐ ┌───┐\n * ┃ │ ┃ │ ┃ │ ┃\n * └───┘ └───┘\n * ┗ ━ ━ ━ ━ ┛ ┗ ━ ━ ━ ━ ┛\n *\n */\n if ((elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize) ||\n (elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize)) {\n return 3 /* ScrollAlignment.RightOrBottom */;\n }\n return null;\n};\nconst canOverflow = (overflow) => {\n return overflow !== \"visible\" && overflow !== \"clip\";\n};\nconst getFrameElement = (element) => {\n var _a;\n try {\n return ((_a = element.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement) || null;\n }\n catch (_b) {\n return null;\n }\n};\nconst isScrollable = (element, computedStyle) => {\n if (element.clientHeight < element.scrollHeight || element.clientWidth < element.scrollWidth) {\n return (canOverflow(computedStyle.overflowY) ||\n canOverflow(computedStyle.overflowX) ||\n element === scrollingElement(element));\n }\n return false;\n};\nconst parentElement = (element) => {\n const pNode = element.parentNode;\n const pElement = element.parentElement;\n if (pElement === null && pNode !== null) {\n if (pNode.nodeType === /** Node.DOCUMENT_FRAGMENT_NODE */ 11) {\n return pNode.host;\n }\n if (pNode.nodeType === /** Node.DOCUMENT_NODE */ 9) {\n return getFrameElement(element);\n }\n }\n return pElement;\n};\nconst clamp = (value, min, max) => {\n if (value < min) {\n return min;\n }\n if (value > max) {\n return max;\n }\n return value;\n};\nconst getSupportedScrollMarginProperty = (ownerDocument) => {\n // Webkit uses \"scroll-snap-margin\" https://bugs.webkit.org/show_bug.cgi?id=189265.\n return [\"scroll-margin\", \"scroll-snap-margin\"].filter((property) => property in ownerDocument.documentElement.style)[0];\n};\nconst getElementScrollSnapArea = (element, elementRect, computedStyle) => {\n const { top, right, bottom, left } = elementRect;\n const scrollProperty = getSupportedScrollMarginProperty(element.ownerDocument);\n if (!scrollProperty) {\n return [top, right, bottom, left];\n }\n const scrollMarginValue = (edge) => {\n const value = computedStyle.getPropertyValue(`${scrollProperty}-${edge}`);\n return parseInt(value, 10) || 0;\n };\n return [\n top - scrollMarginValue(\"top\"),\n right + scrollMarginValue(\"right\"),\n bottom + scrollMarginValue(\"bottom\"),\n left - scrollMarginValue(\"left\"),\n ];\n};\nconst calcAlignEdge = (align, start, end) => {\n switch (align) {\n case 1 /* ScrollAlignment.CenterAlways */:\n return (start + end) / 2;\n case 3 /* ScrollAlignment.RightOrBottom */:\n return end;\n case 2 /* ScrollAlignment.LeftOrTop */:\n case 0 /* ScrollAlignment.ToEdgeIfNeeded */:\n return start;\n }\n};\nconst getFrameViewport = (frame, frameRect) => {\n var _a, _b, _c;\n const visualViewport = (_a = frame.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.visualViewport;\n const [x, y, width, height] = frame === scrollingElement(frame)\n ? [0, 0, (_b = visualViewport === null || visualViewport === void 0 ? void 0 : visualViewport.width) !== null && _b !== void 0 ? _b : frame.clientWidth, (_c = visualViewport === null || visualViewport === void 0 ? void 0 : visualViewport.height) !== null && _c !== void 0 ? _c : frame.clientHeight]\n : [frameRect.left, frameRect.top, frame.clientWidth, frame.clientHeight];\n const left = x + frame.clientLeft;\n const top = y + frame.clientTop;\n const right = left + width;\n const bottom = top + height;\n return [top, right, bottom, left];\n};\nconst computeScrollIntoView = (element, options) => {\n // Collect all the scrolling boxes, as defined in the spec: https://drafts.csswg.org/cssom-view/#scrolling-box\n const actions = [];\n let ownerDocument = element.ownerDocument;\n let ownerWindow = ownerDocument.defaultView;\n if (!ownerWindow) {\n return actions;\n }\n const computedStyle = window.getComputedStyle(element);\n const isLTR = computedStyle.direction !== \"rtl\";\n const writingMode = normalizeWritingMode(computedStyle.writingMode ||\n computedStyle.getPropertyValue(\"-webkit-writing-mode\") ||\n computedStyle.getPropertyValue(\"-ms-writing-mode\"));\n const [alignH, alignV] = toPhysicalAlignment(options, writingMode, isLTR);\n let [top, right, bottom, left] = getElementScrollSnapArea(element, element.getBoundingClientRect(), computedStyle);\n for (let frame = parentElement(element); frame !== null; frame = parentElement(frame)) {\n if (ownerDocument !== frame.ownerDocument) {\n ownerDocument = frame.ownerDocument;\n ownerWindow = ownerDocument.defaultView;\n if (!ownerWindow) {\n break;\n }\n const { left: dX, top: dY } = frame.getBoundingClientRect();\n top += dY;\n right += dX;\n bottom += dY;\n left += dX;\n }\n const frameStyle = ownerWindow.getComputedStyle(frame);\n if (frameStyle.position === \"fixed\") {\n break;\n }\n if (!isScrollable(frame, frameStyle)) {\n continue;\n }\n const frameRect = frame.getBoundingClientRect();\n const [frameTop, frameRight, frameBottom, frameLeft] = getFrameViewport(frame, frameRect);\n const eAlignH = mapNearest(alignH, frameLeft, frameRight, frame.clientWidth, left, right, right - left);\n const eAlignV = mapNearest(alignV, frameTop, frameBottom, frame.clientHeight, top, bottom, bottom - top);\n const diffX = eAlignH === null ? 0 : calcAlignEdge(eAlignH, left, right) - calcAlignEdge(eAlignH, frameLeft, frameRight);\n const diffY = eAlignV === null ? 0 : calcAlignEdge(eAlignV, top, bottom) - calcAlignEdge(eAlignV, frameTop, frameBottom);\n const moveX = isXReversed(frameStyle)\n ? clamp(diffX, -frame.scrollWidth + frame.clientWidth - frame.scrollLeft, -frame.scrollLeft)\n : clamp(diffX, -frame.scrollLeft, frame.scrollWidth - frame.clientWidth - frame.scrollLeft);\n const moveY = clamp(diffY, -frame.scrollTop, frame.scrollHeight - frame.clientHeight - frame.scrollTop);\n actions.push([\n frame,\n { left: frame.scrollLeft + moveX, top: frame.scrollTop + moveY, behavior: options.behavior },\n ]);\n top = Math.max(top - moveY, frameTop);\n right = Math.min(right - moveX, frameRight);\n bottom = Math.min(bottom - moveY, frameBottom);\n left = Math.max(left - moveX, frameLeft);\n }\n return actions;\n};\nexport const scrollIntoView = (element, scrollIntoViewOptions, config) => {\n const options = scrollIntoViewOptions || {};\n if (!checkBehavior(options.behavior)) {\n throw new TypeError(failedExecuteInvalidEnumValue(\"scrollIntoView\", \"Element\", options.behavior));\n }\n const actions = computeScrollIntoView(element, options);\n actions.forEach(([frame, scrollToOptions]) => {\n elementScroll(frame, scrollToOptions, config);\n });\n};\nexport const elementScrollIntoView = scrollIntoView;\n//# sourceMappingURL=scrollIntoView.js.map","\n\n","\n\n\n\n\n","export default \"__VITE_PUBLIC_ASSET__02dafa23__\"","export default \"__VITE_PUBLIC_ASSET__9a1768f9__\"","\n\n\n\n\n","export default \"__VITE_PUBLIC_ASSET__c3c1e733__\"","\n\n\n\n","\n\n\n\n\n","","// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isError(wat) {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat, className) {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isErrorEvent(wat) {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMError(wat) {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMException(wat) {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isString(wat) {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPrimitive(wat) {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPlainObject(wat) {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isEvent(wat) {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isElement(wat) {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isRegExp(wat) {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nfunction isThenable(wat) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isSyntheticEvent(wat) {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isNaN(wat) {\n return typeof wat === 'number' && wat !== wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nfunction isInstanceOf(wat, base) {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\nexport { isDOMError, isDOMException, isElement, isError, isErrorEvent, isEvent, isInstanceOf, isNaN, isPlainObject, isPrimitive, isRegExp, isString, isSyntheticEvent, isThenable };\n//# sourceMappingURL=is.js.map\n","/** Internal global with common properties and Sentry extensions */\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj) {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nconst GLOBAL_OBJ =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function () {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nfunction getGlobalObject() {\n return GLOBAL_OBJ ;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nfunction getGlobalSingleton(name, creator, obj) {\n const gbl = (obj || GLOBAL_OBJ) ;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n\nexport { GLOBAL_OBJ, getGlobalObject, getGlobalSingleton };\n//# sourceMappingURL=worldwide.js.map\n","import { isString } from './is.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction htmlTreeAsString(\n elem,\n options = {},\n) {\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el, keyAttrs) {\n const elem = el\n\n;\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && keyAttrPairs.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nfunction getLocationHref() {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getDomElement(selector) {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) ;\n }\n return null;\n}\n\nexport { getDomElement, getLocationHref, htmlTreeAsString };\n//# sourceMappingURL=browser.js.map\n","/** An error emitted by Sentry SDKs and related utilities. */\nclass SentryError extends Error {\n /** Display name of this error instance. */\n\n constructor( message, logLevel = 'warn') {\n super(message);this.message = message;\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n\nexport { SentryError };\n//# sourceMappingURL=error.js.map\n","import { SentryError } from './error.js';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol) {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nfunction dsnToString(dsn, withPassword = false) {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents\n */\nfunction dsnFromString(str) {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new SentryError(`Invalid Sentry Dsn: ${str}`);\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() ;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });\n}\n\nfunction dsnFromComponents(components) {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn) {\n if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n return;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];\n requiredComponents.forEach(component => {\n if (!dsn[component]) {\n throw new SentryError(`Invalid Sentry Dsn: ${component} missing`);\n }\n });\n\n if (!projectId.match(/^\\d+$/)) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n }\n\n if (!isValidProtocol(protocol)) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n throw new SentryError(`Invalid Sentry Dsn: Invalid port ${port}`);\n }\n\n return true;\n}\n\n/** The Sentry Dsn, identifying a Sentry instance and project. */\nfunction makeDsn(from) {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n validateDsn(components);\n return components;\n}\n\nexport { dsnFromString, dsnToString, makeDsn };\n//# sourceMappingURL=dsn.js.map\n","import { getGlobalSingleton, GLOBAL_OBJ } from './worldwide.js';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nconst CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ;\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nfunction consoleSandbox(callback) {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const originalConsole = GLOBAL_OBJ.console ;\n const wrappedLevels = {};\n\n // Restore all wrapped console methods\n CONSOLE_LEVELS.forEach(level => {\n // TODO(v7): Remove this check as it's only needed for Node 6\n const originalWrappedFunc =\n originalConsole[level] && (originalConsole[level] ).__sentry_original__;\n if (level in originalConsole && originalWrappedFunc) {\n wrappedLevels[level] = originalConsole[level] ;\n originalConsole[level] = originalWrappedFunc ;\n }\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level ];\n });\n }\n}\n\nfunction makeLogger() {\n let enabled = false;\n const logger = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n };\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger ;\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nlet logger;\nif ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n logger = getGlobalSingleton('logger', makeLogger);\n} else {\n logger = makeLogger();\n}\n\nexport { CONSOLE_LEVELS, consoleSandbox, logger };\n//# sourceMappingURL=logger.js.map\n","import { isString, isRegExp } from './is.js';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nfunction truncate(str, max = 0) {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction safeJoin(input, delimiter) {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nfunction isMatchingPattern(\n value,\n pattern,\n requireExactStringMatch = false,\n) {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nfunction stringMatchesSomePattern(\n testString,\n patterns = [],\n requireExactStringMatch = false,\n) {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n\nexport { isMatchingPattern, safeJoin, snipLine, stringMatchesSomePattern, truncate };\n//# sourceMappingURL=string.js.map\n","import { htmlTreeAsString } from './browser.js';\nimport { isError, isEvent, isInstanceOf, isElement, isPlainObject, isPrimitive } from './is.js';\nimport { truncate } from './string.js';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nfunction fill(source, name, replacementFactory) {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] ;\n const wrapped = replacementFactory(original) ;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n markFunctionWrapped(wrapped, original);\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nfunction addNonEnumerableProperty(obj, name, value) {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nfunction markFunctionWrapped(wrapped, original) {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nfunction getOriginalFunction(func) {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nfunction urlEncode(object) {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nfunction convertToPlainObject(value)\n\n {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj\n\n = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target) {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj) {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj )[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nfunction extractExceptionKeysForMessage(exception, maxLength = 40) {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nfunction dropUndefinedKeys(inputValue) {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue, memoizationMap) {\n if (isPlainObject(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue ;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue ;\n }\n\n return inputValue;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nfunction objectify(wat) {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat ).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n\nexport { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify, urlEncode };\n//# sourceMappingURL=object.js.map\n","import { node } from './node-stack-trace.js';\n\nconst STACKTRACE_FRAME_LIMIT = 50;\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nfunction createStackParser(...parsers) {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack, skipFirst = 0) => {\n const frames = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; i < lines.length; i++) {\n const line = lines[i];\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nfunction stackParserFromStackParserOptions(stackParser) {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nfunction stripSentryFramesAndReverse(stack) {\n if (!stack.length) {\n return [];\n }\n\n const localStack = stack.slice(0, STACKTRACE_FRAME_LIMIT);\n\n const lastFrameFunction = localStack[localStack.length - 1].function;\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (lastFrameFunction && /sentryWrapped/.test(lastFrameFunction)) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n const firstFrameFunction = localStack[localStack.length - 1].function;\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (firstFrameFunction && /captureMessage|captureException/.test(firstFrameFunction)) {\n localStack.pop();\n }\n\n return localStack.map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nfunction getFunctionName(fn) {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nfunction nodeStackLineParser(getModule) {\n return [90, node(getModule)];\n}\n\nexport { createStackParser, getFunctionName, nodeStackLineParser, stackParserFromStackParserOptions, stripSentryFramesAndReverse };\n//# sourceMappingURL=stacktrace.js.map\n","import { logger } from './logger.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMException() {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsFetch() {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFetch(func) {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nfunction supportsNativeFetch() {\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement ) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReportingObserver() {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' ,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexport { isNativeFetch, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver };\n//# sourceMappingURL=supports.js.map\n","import { getGlobalObject } from '../worldwide.js';\n\n// Based on https://github.com/angular/angular.js/pull/13945/files\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsHistory() {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (WINDOW ).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n\nexport { supportsHistory };\n//# sourceMappingURL=supportsHistory.js.map\n","import { isString } from './is.js';\nimport { logger, CONSOLE_LEVELS } from './logger.js';\nimport { fill } from './object.js';\nimport { getFunctionName } from './stacktrace.js';\nimport { supportsNativeFetch } from './supports.js';\nimport { getGlobalObject } from './worldwide.js';\nimport { supportsHistory } from './vendor/supportsHistory.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst SENTRY_XHR_DATA_KEY = '__sentry_xhr_v2__';\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers = {};\nconst instrumented = {};\n\n/** Instruments given API */\nfunction instrument(type) {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addInstrumentationHandler(type, callback) {\n handlers[type] = handlers[type] || [];\n (handlers[type] ).push(callback);\n instrument(type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type, data) {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole() {\n if (!('console' in WINDOW)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level) {\n if (!(level in WINDOW.console)) {\n return;\n }\n\n fill(WINDOW.console, level, function (originalConsoleMethod) {\n return function (...args) {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleMethod) {\n originalConsoleMethod.apply(WINDOW.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch() {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(WINDOW, 'fetch', function (originalFetch) {\n return function (...args) {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(WINDOW, args).then(\n (response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nfunction hasProp(obj, prop) {\n return !!obj && typeof obj === 'object' && !!(obj )[prop];\n}\n\nfunction getUrlFromResource(resource) {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request\n */\nfunction parseFetchArgs(fetchArgs) {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs ;\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg ),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\n/** JSDoc */\nfunction instrumentXHR() {\n if (!('XMLHttpRequest' in WINDOW)) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen) {\n return function ( ...args) {\n const url = args[1];\n const xhrInfo = (this[SENTRY_XHR_DATA_KEY] = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n request_headers: {},\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n this.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args: args ,\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr: this,\n } );\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original) {\n return function ( ...readyStateArgs) {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n fill(this, 'setRequestHeader', function (original) {\n return function ( ...setRequestHeaderArgs) {\n const [header, value] = setRequestHeaderArgs ;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend) {\n return function ( ...args) {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n if (sentryXhrData && args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref;\n\n/** JSDoc */\nfunction instrumentHistory() {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function ( ...args) {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction) {\n return function ( ...args) {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID;\nlet lastCapturedEvent;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous, current) {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event) {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target ;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler, globalListener = false) {\n return (event) => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\n/** JSDoc */\nfunction instrumentDOM() {\n if (!('document' in WINDOW)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW )[target] && (WINDOW )[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function (\n\n type,\n listener,\n options,\n ) {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this ;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener) {\n return function (\n\n type,\n listener,\n options,\n ) {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this ;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler = null;\n/** JSDoc */\nfunction instrumentError() {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg, url, line, column, error) {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n WINDOW.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nlet _oldOnUnhandledRejectionHandler = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e) {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n WINDOW.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { SENTRY_XHR_DATA_KEY, addInstrumentationHandler, parseFetchArgs };\n//# sourceMappingURL=instrument.js.map\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Helper to decycle json objects\n */\nfunction memoBuilder() {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner = hasWeakSet ? new WeakSet() : [];\n function memoize(obj) {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj) {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n\nexport { memoBuilder };\n//# sourceMappingURL=memo.js.map\n","import { addNonEnumerableProperty } from './object.js';\nimport { snipLine } from './string.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nfunction uuid4() {\n const gbl = GLOBAL_OBJ ;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n\n const getRandomByte =\n crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16;\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event) {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nfunction getEventDescription(event) {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nfunction addExceptionTypeValue(event, value, type) {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nfunction addExceptionMechanism(event, newMechanism) {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nfunction parseSemver(input) {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nfunction addContextToFrame(lines, frame, linesOfContext = 5) {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nfunction checkOrSetAlreadyCaught(exception) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception ).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception , '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nfunction arrayify(maybeArray) {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, arrayify, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 };\n//# sourceMappingURL=misc.js.map\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nfunction isBrowserBundle() {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nfunction getSDKSource() {\n // @ts-ignore \"npm\" is injected by rollup during build process\n return \"npm\";\n}\n\nexport { getSDKSource, isBrowserBundle };\n//# sourceMappingURL=env.js.map\n","import { isBrowserBundle } from './env.js';\n\n/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nfunction isNodeEnv() {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nfunction dynamicRequire(mod, request) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nfunction loadModule(moduleName) {\n let mod;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n\nexport { dynamicRequire, isNodeEnv, loadModule };\n//# sourceMappingURL=node.js.map\n","import { isNaN, isSyntheticEvent } from './is.js';\nimport { memoBuilder } from './memo.js';\nimport { convertToPlainObject } from './object.js';\nimport { getFunctionName } from './stacktrace.js';\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normallized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalize(input, depth = +Infinity, maxProperties = +Infinity) {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nfunction normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object,\n // Default Node.js REPL depth\n depth = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize = 100 * 1024,\n) {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized ;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key,\n value,\n depth = +Infinity,\n maxProperties = +Infinity,\n memo = memoBuilder(),\n) {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(value))) {\n return value ;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value )['__sentry_skip_normalization__']) {\n return value ;\n }\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n let overriddenDepth = depth;\n\n if (typeof (value )['__sentry_override_normalization_depth__'] === 'number') {\n overriddenDepth = (value )['__sentry_override_normalization_depth__'] ;\n }\n\n // We're also done if we've reached the max depth\n if (overriddenDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value ;\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, overriddenDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) ;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value );\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, overriddenDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value,\n) {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value )._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own)\n if (value === void 0) {\n return '[undefined]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n return `[object ${getConstructorName(value)}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n\nfunction getConstructorName(value) {\n const prototype = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value) {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value) {\n return utf8Length(JSON.stringify(value));\n}\n\nexport { normalize, normalizeToSize, visit as walk };\n//# sourceMappingURL=normalize.js.map\n","import { isThenable } from './is.js';\n\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n\n/** SyncPromise internal states */\nvar States; (function (States) {\n /** Pending */\n const PENDING = 0; States[States[\"PENDING\"] = PENDING] = \"PENDING\";\n /** Resolved / OK */\n const RESOLVED = 1; States[States[\"RESOLVED\"] = RESOLVED] = \"RESOLVED\";\n /** Rejected / Error */\n const REJECTED = 2; States[States[\"REJECTED\"] = REJECTED] = \"REJECTED\";\n})(States || (States = {}));\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nfunction resolvedSyncPromise(value) {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nfunction rejectedSyncPromise(reason) {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise {\n __init() {this._state = States.PENDING;}\n __init2() {this._handlers = [];}\n\n constructor(\n executor,\n ) {SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this);\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n then(\n onfulfilled,\n onrejected,\n ) {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result );\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** JSDoc */\n catch(\n onrejected,\n ) {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n finally(onfinally) {\n return new SyncPromise((resolve, reject) => {\n let val;\n let isRejected;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val );\n });\n });\n }\n\n /** JSDoc */\n __init3() {this._resolve = (value) => {\n this._setResult(States.RESOLVED, value);\n };}\n\n /** JSDoc */\n __init4() {this._reject = (reason) => {\n this._setResult(States.REJECTED, reason);\n };}\n\n /** JSDoc */\n __init5() {this._setResult = (state, value) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value ).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };}\n\n /** JSDoc */\n __init6() {this._executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler[1](this._value );\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n };}\n}\n\nexport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise };\n//# sourceMappingURL=syncpromise.js.map\n","import { SentryError } from './error.js';\nimport { rejectedSyncPromise, SyncPromise, resolvedSyncPromise } from './syncpromise.js';\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nfunction makePromiseBuffer(limit) {\n const buffer = [];\n\n function isReady() {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task) {\n return buffer.splice(buffer.indexOf(task), 1)[0];\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer) {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout) {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n\nexport { makePromiseBuffer };\n//# sourceMappingURL=promisebuffer.js.map\n","/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nfunction parseUrl(url) {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nfunction stripUrlQueryAndFragment(urlPath) {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nfunction getNumberOfUrlSegments(url) {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nfunction getSanitizedUrlString(url) {\n const { protocol, host, path } = url;\n\n const filteredHost =\n (host &&\n host\n // Always filter out authority\n .replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n .replace(':80', '')\n .replace(':443', '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n\nexport { getNumberOfUrlSegments, getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment };\n//# sourceMappingURL=url.js.map\n","// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nconst validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nfunction severityFromString(level) {\n return severityLevelFromString(level) ;\n}\n\n/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nfunction severityLevelFromString(level) {\n return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ;\n}\n\nexport { severityFromString, severityLevelFromString, validSeverityLevels };\n//# sourceMappingURL=severity.js.map\n","import { isNodeEnv, dynamicRequire } from './node.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance() {\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance() {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') ;\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nconst dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nconst timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource);\n\n// Re-exported with an old name for backwards-compatibility.\nconst timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nconst usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nlet _browserPerformanceTimeOriginMode;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nconst browserPerformanceTimeOrigin = (() => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n\nexport { _browserPerformanceTimeOriginMode, browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds, timestampWithMs, usingPerformanceAPI };\n//# sourceMappingURL=time.js.map\n","const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nfunction extractTraceparentData(traceparent) {\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n\n if (!traceparent || !matches) {\n // empty string or no matches is invalid traceparent data\n return undefined;\n }\n\n let parentSampled;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\nexport { TRACEPARENT_REGEXP, extractTraceparentData };\n//# sourceMappingURL=tracing.js.map\n","import { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { dropUndefinedKeys } from './object.js';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction createEnvelope(headers, items = []) {\n return [headers, items] ;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction addItemToEnvelope(envelope, newItem) {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] ;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nfunction forEachEnvelopeItem(\n envelope,\n callback,\n) {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nfunction envelopeContainsItemType(envelope, types) {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8.\n */\nfunction encodeUTF8(input, textEncoder) {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope, textEncoder) {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts = JSON.stringify(envHeaders);\n\n function append(next) {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers) {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\n/**\n * Parses an envelope\n */\nfunction parseEnvelope(\n env,\n textEncoder,\n textDecoder,\n) {\n let buffer = typeof env === 'string' ? textEncoder.encode(env) : env;\n\n function readBinary(length) {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson() {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(textDecoder.decode(readBinary(i))) ;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(\n attachment,\n textEncoder,\n) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nfunction envelopeItemTypeToDataCategory(type) {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent || !metadataOrEvent.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nfunction createEventEnvelopeHeaders(\n event,\n sdkInfo,\n tunnel,\n dsn,\n) {\n const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;\n return {\n event_id: event.event_id ,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { createEnvelope } from './envelope.js';\nimport { dateTimestampInSeconds } from './time.js';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nfunction createClientReportEnvelope(\n discarded_events,\n dsn,\n timestamp,\n) {\n const clientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n\nexport { createClientReportEnvelope };\n//# sourceMappingURL=clientreport.js.map\n","// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\n\nconst DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nfunction parseRetryAfterHeader(header, now = Date.now()) {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nfunction disabledUntil(limits, category) {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, category, now = Date.now()) {\n return disabledUntil(limits, category) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nfunction updateRateLimits(\n limits,\n { statusCode, headers },\n now = Date.now(),\n) {\n const updatedRateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && headers['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n\nexport { DEFAULT_RETRY_AFTER, disabledUntil, isRateLimited, parseRetryAfterHeader, updateRateLimits };\n//# sourceMappingURL=ratelimit.js.map\n","import { isString } from './is.js';\nimport { logger } from './logger.js';\n\nconst BAGGAGE_HEADER_NAME = 'baggage';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nconst MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nfunction baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader,\n) {\n if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject = {};\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n baggageObject = baggageHeader.reduce((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n return {\n ...acc,\n ...currBaggageObject,\n };\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext ;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nfunction dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext,\n) {\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader) {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object) {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n\nexport { BAGGAGE_HEADER_NAME, MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader };\n//# sourceMappingURL=baggage.js.map\n","const DEFAULT_ENVIRONMENT = 'production';\n\nexport { DEFAULT_ENVIRONMENT };\n//# sourceMappingURL=constants.js.map\n","import { timestampInSeconds, uuid4, dropUndefinedKeys } from '@sentry/utils';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nfunction makeSession(context) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nfunction updateSession(session, context = {}) {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nfunction closeSession(session, status) {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session) {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n\nexport { closeSession, makeSession, updateSession };\n//# sourceMappingURL=session.js.map\n","import { isPlainObject, dateTimestampInSeconds, SyncPromise, logger, isThenable, arrayify, getGlobalSingleton } from '@sentry/utils';\nimport { updateSession } from './session.js';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nclass Scope {\n /** Flag if notifying is happening. */\n\n /** Callback for client to receive scope changes. */\n\n /** Callback list that will be called after {@link applyToEvent}. */\n\n /** Array of breadcrumbs. */\n\n /** User */\n\n /** Tags */\n\n /** Extra */\n\n /** Contexts */\n\n /** Attachments */\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n\n /** Fingerprint */\n\n /** Severity */\n // eslint-disable-next-line deprecation/deprecation\n\n /** Transaction Name */\n\n /** Span */\n\n /** Session */\n\n /** Request Mode Session Status */\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n }\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n static clone(scope) {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n newScope._attachments = [...scope._attachments];\n newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata };\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n addScopeListener(callback) {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n addEventProcessor(callback) {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n this._user = user || {};\n if (this._session) {\n updateSession(this._session, { user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getUser() {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n getRequestSession() {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n setRequestSession(requestSession) {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setFingerprint(fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level,\n ) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTransactionName(name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setSpan(span) {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSpan() {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n getTransaction() {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\n */\n setSession(session) {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSession() {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n update(captureContext) {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext )(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext ;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n clear() {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getLastBreadcrumb() {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n clearBreadcrumbs() {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addAttachment(attachment) {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getAttachments() {\n return this._attachments;\n }\n\n /**\n * @inheritDoc\n */\n clearAttachments() {\n this._attachments = [];\n return this;\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n */\n applyToEvent(event, hint = {}) {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transaction = this._span.transaction;\n if (transaction) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: transaction.getDynamicSamplingContext(),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata };\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry\n */\n setSDKProcessingMetadata(newData) {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n _notifyEventProcessors(\n processors,\n event,\n hint,\n index = 0,\n ) {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) ;\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n processor.id &&\n result === null &&\n logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n _notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n _applyFingerprint(event) {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors() {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nfunction addGlobalEventProcessor(callback) {\n getGlobalEventProcessors().push(callback);\n}\n\nexport { Scope, addGlobalEventProcessor };\n//# sourceMappingURL=scope.js.map\n","import { uuid4, dateTimestampInSeconds, consoleSandbox, logger, GLOBAL_OBJ, getGlobalSingleton } from '@sentry/utils';\nimport { DEFAULT_ENVIRONMENT } from './constants.js';\nimport { Scope } from './scope.js';\nimport { closeSession, makeSession, updateSession } from './session.js';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nconst API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * @inheritDoc\n */\nclass Hub {\n /** Is a {@link Layer}[] containing the client and scope */\n\n /** Contains the last event id of a captured event. */\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n constructor(client, scope = new Scope(), _version = API_VERSION) {this._version = _version;\n this._stack = [{ scope }];\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n isOlderThan(version) {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n bindClient(client) {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n pushScope() {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n popScope() {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n withScope(callback) {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n getClient() {\n return this.getStackTop().client ;\n }\n\n /** Returns the scope of the top stack. */\n getScope() {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n getStack() {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n getStackTop() {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n captureException(exception, hint) {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n this._withClient((client, scope) => {\n client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level,\n hint,\n ) {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n this._withClient((client, scope) => {\n client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n\n this._withClient((client, scope) => {\n client.captureEvent(event, { ...hint, event_id: eventId }, scope);\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n lastEventId() {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, hint) {\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) )\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n this.getScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n this.getScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n this.getScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this.getScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n this.getScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setContext(name, context) {\n this.getScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n configureScope(callback) {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n run(callback) {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n getIntegration(integration) {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n startTransaction(context, customSamplingContext) {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && !result) {\n // eslint-disable-next-line no-console\n console.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n */\n traceHeaders() {\n return this._callExtensionMethod('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n captureSession(endSession = false) {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n endSession() {\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n */\n startSession(context) {\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n */\n shouldSendDefaultPii() {\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n _sendSessionUpdate() {\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n _withClient(callback) {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(client, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _callExtensionMethod(method, ...args) {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nfunction getMainCarrier() {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nfunction makeMain(hub) {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nfunction getCurrentHub() {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\nfunction getGlobalHub(registry = getMainCarrier()) {\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\nfunction ensureHubOnCarrier(carrier, parent = getGlobalHub()) {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(carrier) || getHubFromCarrier(carrier).isOlderThan(API_VERSION)) {\n const globalHubTopStack = parent.getStackTop();\n setHubOnCarrier(carrier, new Hub(globalHubTopStack.client, Scope.clone(globalHubTopStack.scope)));\n }\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nfunction setAsyncContextStrategy(strategy) {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nfunction runWithAsyncContext(callback, options = {}) {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier) {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nfunction getHubFromCarrier(carrier) {\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nfunction setHubOnCarrier(carrier, hub) {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n\nexport { API_VERSION, Hub, ensureHubOnCarrier, getCurrentHub, getHubFromCarrier, getMainCarrier, makeMain, runWithAsyncContext, setAsyncContextStrategy, setHubOnCarrier };\n//# sourceMappingURL=hub.js.map\n","import { getCurrentHub } from '../hub.js';\n\n// Treeshakable guard to remove all code related to tracing\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nfunction hasTracingEnabled(\n maybeOptions,\n) {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getCurrentHub().getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n\nexport { hasTracingEnabled };\n//# sourceMappingURL=hasTracingEnabled.js.map\n","import { getCurrentHub } from '../hub.js';\nexport { TRACEPARENT_REGEXP, extractTraceparentData, stripUrlQueryAndFragment } from '@sentry/utils';\n\n/** Grabs active transaction off scope, if any */\nfunction getActiveTransaction(maybeHub) {\n const hub = maybeHub || getCurrentHub();\n const scope = hub.getScope();\n return scope.getTransaction() ;\n}\n\nexport { getActiveTransaction };\n//# sourceMappingURL=utils.js.map\n","import { addInstrumentationHandler, logger } from '@sentry/utils';\nimport { getActiveTransaction } from './utils.js';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nfunction registerErrorInstrumentation() {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addInstrumentationHandler('error', errorCallback);\n addInstrumentationHandler('unhandledrejection', errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback() {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status = 'internal_error';\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n\nexport { registerErrorInstrumentation };\n//# sourceMappingURL=errors.js.map\n","import { uuid4, timestampWithMs, logger, dropUndefinedKeys } from '@sentry/utils';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nclass SpanRecorder {\n __init() {this.spans = [];}\n\n constructor(maxlen = 1000) {SpanRecorder.prototype.__init.call(this);\n this._maxlen = maxlen;\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n add(span) {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nclass Span {\n /**\n * @inheritDoc\n */\n __init2() {this.traceId = uuid4();}\n\n /**\n * @inheritDoc\n */\n __init3() {this.spanId = uuid4().substring(16);}\n\n /**\n * @inheritDoc\n */\n\n /**\n * Internal keeper of the status\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * Timestamp in seconds when the span was created.\n */\n __init4() {this.startTimestamp = timestampWithMs();}\n\n /**\n * Timestamp in seconds when the span ended.\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n __init5() {this.tags = {};}\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n __init6() {this.data = {};}\n\n /**\n * List of spans that were finalized\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * The instrumenter that created this span.\n */\n __init7() {this.instrumenter = 'sentry';}\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(spanContext) {Span.prototype.__init2.call(this);Span.prototype.__init3.call(this);Span.prototype.__init4.call(this);Span.prototype.__init5.call(this);Span.prototype.__init6.call(this);Span.prototype.__init7.call(this);\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n if (spanContext.instrumenter) {\n this.instrumenter = spanContext.instrumenter;\n }\n }\n\n /**\n * @inheritDoc\n */\n startChild(\n spanContext,\n ) {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && childSpan.transaction) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = childSpan.transaction.name || '< unknown name >';\n const idStr = childSpan.transaction.spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage };\n logger.log(logMessage);\n }\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n setData(key, value) {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setStatus(value) {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setHttpStatus(httpStatus) {\n this.setTag('http.status_code', String(httpStatus));\n const spanStatus = spanStatusfromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n isSuccess() {\n return this.status === 'ok';\n }\n\n /**\n * @inheritDoc\n */\n finish(endTimestamp) {\n if (\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n // Don't call this for transactions\n this.transaction &&\n this.transaction.spanId !== this.spanId\n ) {\n const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId];\n if (logMessage) {\n logger.log((logMessage ).replace('Starting', 'Finishing'));\n }\n }\n\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n }\n\n /**\n * @inheritDoc\n */\n toTraceparent() {\n let sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return `${this.traceId}-${this.spanId}${sampledString}`;\n }\n\n /**\n * @inheritDoc\n */\n toContext() {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n updateWithContext(spanContext) {\n this.data = spanContext.data || {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId || this.spanId;\n this.startTimestamp = spanContext.startTimestamp || this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags || {};\n this.traceId = spanContext.traceId || this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getTraceContext() {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n toJSON()\n\n {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n }\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nfunction spanStatusfromHttpCode(httpStatus) {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\nexport { Span, SpanRecorder, spanStatusfromHttpCode };\n//# sourceMappingURL=span.js.map\n","import { logger, dropUndefinedKeys } from '@sentry/utils';\nimport { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getCurrentHub } from '../hub.js';\nimport { Span, SpanRecorder } from './span.js';\n\n/** JSDoc */\nclass Transaction extends Span {\n\n /**\n * The reference to the current hub.\n */\n\n __init() {this._measurements = {};}\n\n __init2() {this._contexts = {};}\n\n __init3() {this._frozenDynamicSamplingContext = undefined;}\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(transactionContext, hub) {\n super(transactionContext);Transaction.prototype.__init.call(this);Transaction.prototype.__init2.call(this);Transaction.prototype.__init3.call(this);\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this.metadata = {\n source: 'custom',\n ...transactionContext.metadata,\n spanMetadata: {},\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n /** Getter for `name` property */\n get name() {\n return this._name;\n }\n\n /** Setter for `name` property, which also sets `source` as custom */\n set name(newName) {\n this.setName(newName);\n }\n\n /**\n * JSDoc\n */\n setName(name, source = 'custom') {\n this._name = name;\n this.metadata.source = source;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n initSpanRecorder(maxlen = 1000) {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * @inheritDoc\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n }\n\n /**\n * @inheritDoc\n */\n setMeasurement(name, value, unit = '') {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * @inheritDoc\n */\n setMetadata(newMetadata) {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n finish(endTimestamp) {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Transaction has no name, falling back to ``.');\n this.name = '';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev, current) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const metadata = this.metadata;\n\n const transaction = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n dynamicSamplingContext: this.getDynamicSamplingContext(),\n },\n ...(metadata.source && {\n transaction_info: {\n source: metadata.source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n toContext() {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n updateWithContext(transactionContext) {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name || '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n */\n getDynamicSamplingContext() {\n if (this._frozenDynamicSamplingContext) {\n return this._frozenDynamicSamplingContext;\n }\n\n const hub = this._hub || getCurrentHub();\n const client = hub && hub.getClient();\n\n if (!client) return {};\n\n const { environment, release } = client.getOptions() || {};\n const { publicKey: public_key } = client.getDsn() || {};\n\n const maybeSampleRate = this.metadata.sampleRate;\n const sample_rate = maybeSampleRate !== undefined ? maybeSampleRate.toString() : undefined;\n\n const { segment: user_segment } = hub.getScope().getUser() || {};\n\n const source = this.metadata.source;\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const transaction = source && source !== 'url' ? this.name : undefined;\n\n const dsc = dropUndefinedKeys({\n environment: environment || DEFAULT_ENVIRONMENT,\n release,\n transaction,\n user_segment,\n public_key,\n trace_id: this.traceId,\n sample_rate,\n });\n\n // Uncomment if we want to make DSC immutable\n // this._frozenDynamicSamplingContext = dsc;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n setHub(hub) {\n this._hub = hub;\n }\n}\n\nexport { Transaction };\n//# sourceMappingURL=transaction.js.map\n","import { logger, timestampWithMs } from '@sentry/utils';\nimport { SpanRecorder } from './span.js';\nimport { Transaction } from './transaction.js';\n\nconst TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nclass IdleTransactionSpanRecorder extends SpanRecorder {\n constructor(\n _pushActivity,\n _popActivity,\n transactionSpanId,\n maxlen,\n ) {\n super(maxlen);this._pushActivity = _pushActivity;this._popActivity = _popActivity;this.transactionSpanId = transactionSpanId; }\n\n /**\n * @inheritDoc\n */\n add(span) {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nclass IdleTransaction extends Transaction {\n // Activities store a list of active spans\n __init() {this.activities = {};}\n\n // Track state of activities in previous heartbeat\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n __init2() {this._heartbeatCounter = 0;}\n\n // We should not use heartbeat if we finished a transaction\n __init3() {this._finished = false;}\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n __init4() {this._idleTimeoutCanceledPermanently = false;}\n\n __init5() {this._beforeFinishCallbacks = [];}\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n\n __init6() {this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];}\n\n constructor(\n transactionContext,\n _idleHub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n _idleTimeout = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n _finalTimeout = TRACING_DEFAULTS.finalTimeout,\n _heartbeatInterval = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n _onScope = false,\n ) {\n super(transactionContext, _idleHub);this._idleHub = _idleHub;this._idleTimeout = _idleTimeout;this._finalTimeout = _finalTimeout;this._heartbeatInterval = _heartbeatInterval;this._onScope = _onScope;IdleTransaction.prototype.__init.call(this);IdleTransaction.prototype.__init2.call(this);IdleTransaction.prototype.__init3.call(this);IdleTransaction.prototype.__init4.call(this);IdleTransaction.prototype.__init5.call(this);IdleTransaction.prototype.__init6.call(this);\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._restartIdleTimeout();\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.finish();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n finish(endTimestamp = timestampWithMs()) {\n this._finished = true;\n this.activities = {};\n\n if (this.op === 'ui.action.click') {\n this.setTag(FINISH_REASON_TAG, this._finishReason);\n }\n\n if (this.spanRecorder) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus('cancelled');\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n '[Tracing] discarding Span since it happened after Transaction was finished',\n JSON.stringify(span, undefined, 2),\n );\n }\n return keepSpan;\n });\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n const scope = this._idleHub.getScope();\n if (scope.getTransaction() === this) {\n scope.setSpan(undefined);\n }\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n registerBeforeFinishCallback(callback) {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n initSpanRecorder(maxlen) {\n if (!this.spanRecorder) {\n const pushActivity = (id) => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id) => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n cancelIdleTimeout(\n endTimestamp,\n {\n restartOnChildSpanChange,\n }\n\n = {\n restartOnChildSpanChange: true,\n },\n ) {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n setFinishReason(reason) {\n this._finishReason = reason;\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n _restartIdleTimeout(endTimestamp) {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.finish(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n _pushActivity(spanId) {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n _popActivity(spanId) {\n if (this.activities[spanId]) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampWithMs();\n if (this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampWithMs is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n _beat() {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n _pingHeartbeat() {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n\nexport { IdleTransaction, IdleTransactionSpanRecorder, TRACING_DEFAULTS };\n//# sourceMappingURL=idletransaction.js.map\n","import { logger, isNaN } from '@sentry/utils';\nimport { getMainCarrier } from '../hub.js';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled.js';\nimport { registerErrorInstrumentation } from './errors.js';\nimport { IdleTransaction } from './idletransaction.js';\nimport { Transaction } from './transaction.js';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders() {\n const scope = this.getScope();\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': span.toTraceparent(),\n }\n : {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param transaction: The transaction needing a sampling decision\n * @param options: The current client's options, so we can access `tracesSampleRate` and/or `tracesSampler`\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample(\n transaction,\n options,\n samplingContext,\n) {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n sampleRate: Number(transaction.sampled),\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setMetadata({\n sampleRate,\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate );\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate) {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n\n transactionContext,\n customSamplingContext,\n) {\n const client = this.getClient();\n const options = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n transactionContext.sampled = false;\n }\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans ));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nfunction startIdleTransaction(\n hub,\n transactionContext,\n idleTimeout,\n finalTimeout,\n onScope,\n customSamplingContext,\n heartbeatInterval,\n) {\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans ));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nfunction addTracingExtensions() {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n\nexport { addTracingExtensions, startIdleTransaction };\n//# sourceMappingURL=hubextensions.js.map\n","import { getCurrentHub } from './hub.js';\n\n// Note: All functions in this file are typed with a return value of `ReturnType`,\n// where HUB_FUNCTION is some method on the Hub class.\n//\n// This is done to make sure the top level SDK methods stay in sync with the hub methods.\n// Although every method here has an explicit return type, some of them (that map to void returns) do not\n// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable.\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @param captureContext Additional scope data to apply to exception event.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nfunction captureException(exception, captureContext) {\n return getCurrentHub().captureException(exception, { captureContext });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param Severity Define the level of the message.\n * @returns The generated eventId.\n */\nfunction captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n captureContext,\n) {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentHub().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nfunction captureEvent(event, hint) {\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nfunction configureScope(callback) {\n getCurrentHub().configureScope(callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nfunction addBreadcrumb(breadcrumb) {\n getCurrentHub().addBreadcrumb(breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setContext(name, context) {\n getCurrentHub().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nfunction setExtras(extras) {\n getCurrentHub().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nfunction setExtra(key, extra) {\n getCurrentHub().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nfunction setTags(tags) {\n getCurrentHub().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nfunction setTag(key, value) {\n getCurrentHub().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nfunction setUser(user) {\n getCurrentHub().setUser(user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nfunction withScope(callback) {\n getCurrentHub().withScope(callback);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nfunction startTransaction(\n context,\n customSamplingContext,\n) {\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\n}\n\nexport { addBreadcrumb, captureEvent, captureException, captureMessage, configureScope, setContext, setExtra, setExtras, setTag, setTags, setUser, startTransaction, withScope };\n//# sourceMappingURL=exports.js.map\n","import { makeDsn, dsnToString, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn) {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn) {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn, sdkInfo) {\n return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nfunction getEnvelopeEndpointWithUrlEncodedAuth(\n dsn,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions = {} ,\n) {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(\n dsnLike,\n dialogOptions\n\n,\n) {\n const dsn = makeDsn(dsnLike);\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint };\n//# sourceMappingURL=api.js.map\n","import { getSdkMetadataForEnvelopeHeader, dsnToString, createEnvelope, createEventEnvelopeHeaders } from '@sentry/utils';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event, sdkInfo) {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates an envelope from a Session */\nfunction createSessionEnvelope(\n session,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session];\n\n return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nfunction createEventEnvelope(\n event,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjut a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n enhanceEventWithSdkInfo(event, metadata && metadata.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem = [{ type: eventType }, event];\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n\nexport { createEventEnvelope, createSessionEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { arrayify, logger } from '@sentry/utils';\nimport { getCurrentHub } from './hub.js';\nimport { addGlobalEventProcessor } from './scope.js';\n\nconst installedIntegrations = [];\n\n/** Map of integrations assigned to a client */\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preseve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations) {\n const integrationsByName = {};\n\n integrations.forEach(currentInstance => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.keys(integrationsByName).map(k => integrationsByName[k]);\n}\n\n/** Gets integrations to install */\nfunction getIntegrationsToSetup(options) {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach(integration => {\n integration.isDefaultInstance = true;\n });\n\n let integrations;\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nfunction setupIntegrations(integrations) {\n const integrationIndex = {};\n\n integrations.forEach(integration => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/** Setup a single integration. */\nfunction setupIntegration(integration, integrationIndex) {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Integration installed: ${integration.name}`);\n }\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr, callback) {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\nexport { getIntegrationsToSetup, installedIntegrations, setupIntegration, setupIntegrations };\n//# sourceMappingURL=integration.js.map\n","import { uuid4, dateTimestampInSeconds, resolvedSyncPromise, truncate, GLOBAL_OBJ, normalize } from '@sentry/utils';\nimport { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { Scope } from '../scope.js';\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nfunction prepareEvent(\n options,\n event,\n hint,\n scope,\n) {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;\n const prepared = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n // Only apply debug metadata to error events.\n if (event.type === undefined) {\n applyDebugMetadata(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n //\n // We need to check for the existence of `finalScope.getAttachments`\n // because `getAttachments` can be undefined if users are using an older version\n // of `@sentry/core` that does not have the `getAttachments` method.\n // See: https://github.com/getsentry/sentry-javascript/issues/5229\n if (finalScope) {\n // Collect attachments from the hint and scope\n if (finalScope.getAttachments) {\n const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()];\n\n if (attachments.length) {\n hint.attachments = attachments;\n }\n }\n\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event, options) {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap();\n\n/**\n * Applies debug metadata images to the event in order to apply source maps by looking up their debug ID.\n */\nfunction applyDebugMetadata(event, stackParser) {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce((acc, debugIdStackTrace) => {\n let parsedStack;\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n // Get a Set of filenames in the stack trace\n const errorFileNames = new Set();\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace.frames.forEach(frame => {\n if (frame.filename) {\n errorFileNames.add(frame.filename);\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n errorFileNames.forEach(filename => {\n if (filenameDebugIdMap[filename]) {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\n });\n }\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event, integrationNames) {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event, depth, maxBreadth) {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable\n if (span.data) {\n span.data = normalize(span.data, depth, maxBreadth);\n }\n return span;\n });\n }\n\n return normalized;\n}\n\nexport { applyDebugMetadata, prepareEvent };\n//# sourceMappingURL=prepareEvent.js.map\n","import { makeDsn, logger, checkOrSetAlreadyCaught, isPrimitive, resolvedSyncPromise, addItemToEnvelope, createAttachmentEnvelopeItem, SyncPromise, rejectedSyncPromise, SentryError, isThenable, isPlainObject } from '@sentry/utils';\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api.js';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope.js';\nimport { setupIntegrations, setupIntegration } from './integration.js';\nimport { updateSession } from './session.js';\nimport { prepareEvent } from './utils/prepareEvent.js';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass BaseClient {\n /** Options passed to the SDK. */\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n\n /** Array of set up integrations. */\n __init() {this._integrations = {};}\n\n /** Indicates whether this client's integrations have been set up. */\n __init2() {this._integrationsInitialized = false;}\n\n /** Number of calls being processed */\n __init3() {this._numProcessing = 0;}\n\n /** Holds flushable */\n __init4() {this._outcomes = {};}\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n __init5() {this._hooks = {};}\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n constructor(options) {BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this);BaseClient.prototype.__init5.call(this);\n this._options = options;\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('No DSN provided, client will not do anything.');\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n captureException(exception, hint, scope) {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level,\n hint,\n scope,\n ) {\n let eventId = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint, scope) {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureSession(session) {\n if (!this._isEnabled()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Discarded session because of missing or non-string release');\n } else {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n flush(timeout) {\n const transport = this._transport;\n if (transport) {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * @inheritDoc\n */\n close(timeout) {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n setupIntegrations() {\n if (this._isEnabled() && !this._integrationsInitialized) {\n this._integrations = setupIntegrations(this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n getIntegrationById(integrationId) {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n getIntegration(integration) {\n try {\n return (this._integrations[integration.id] ) || null;\n } catch (_oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n addIntegration(integration) {\n setupIntegration(integration, this._integrations);\n }\n\n /**\n * @inheritDoc\n */\n sendEvent(event, hint = {}) {\n if (this._dsn) {\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\n }\n\n const promise = this._sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n }\n\n /**\n * @inheritDoc\n */\n sendSession(session) {\n if (this._dsn) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n void this._sendEnvelope(env);\n }\n }\n\n /**\n * @inheritDoc\n */\n recordDroppedEvent(reason, category, _event) {\n // Note: we use `event` in replay, where we overwrite this hook.\n\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n on(hook, callback) {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-ignore We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n emit(hook, ...rest) {\n if (this._hooks[hook]) {\n // @ts-ignore we cannot enforce the callback to match the hook\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /** Updates existing session based on the provided event */\n _updateSessionFromEvent(session, event) {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n _isClientDoneProcessing(timeout) {\n return new SyncPromise(resolve => {\n let ticked = 0;\n const tick = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n _isEnabled() {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n _prepareEvent(event, hint, scope) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n return prepareEvent(options, event, hint, scope);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n _captureEvent(event, hint = {}, scope) {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n const sentryError = reason ;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n _processEvent(event, hint, scope) {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n if (!this._isEnabled()) {\n return rejectedSyncPromise(new SentryError('SDK not enabled, will not capture event.', 'log'));\n }\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory = eventType === 'replay_event' ? 'replay' : eventType;\n\n return this._prepareEvent(event, hint, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data ).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n _process(promise) {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * @inheritdoc\n */\n _sendEnvelope(envelope) {\n if (this._transport && this._dsn) {\n this.emit('beforeEnvelope', envelope);\n\n return this._transport.send(envelope).then(null, reason => {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Error while sending event:', reason);\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Transport disabled');\n }\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n _clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult,\n beforeSendLabel,\n) {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\nexport { BaseClient };\n//# sourceMappingURL=baseclient.js.map\n","import { logger } from '@sentry/utils';\nimport { getCurrentHub } from './hub.js';\n\n/** A class object that can instantiate Client objects. */\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nfunction initAndBind(\n clientClass,\n options,\n) {\n if (options.debug === true) {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n }\n }\n const hub = getCurrentHub();\n const scope = hub.getScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n\nexport { initAndBind };\n//# sourceMappingURL=sdk.js.map\n","import { makePromiseBuffer, forEachEnvelopeItem, envelopeItemTypeToDataCategory, isRateLimited, resolvedSyncPromise, createEnvelope, SentryError, logger, serializeEnvelope, updateRateLimits } from '@sentry/utils';\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nfunction createTransport(\n options,\n makeRequest,\n buffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n) {\n let rateLimits = {};\n const flush = (timeout) => buffer.drain(timeout);\n\n function send(envelope) {\n const filteredEnvelopeItems = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason) => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = () =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise();\n } else {\n throw error;\n }\n },\n );\n }\n\n // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item, type) {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item )[1] : undefined;\n}\n\nexport { DEFAULT_TRANSPORT_BUFFER_SIZE, createTransport };\n//# sourceMappingURL=base.js.map\n","const SDK_VERSION = '7.48.0';\n\nexport { SDK_VERSION };\n//# sourceMappingURL=version.js.map\n","import { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString;\n\n/** Patch toString calls to return proper name for wrapped functions */\nclass FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'FunctionToString';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = FunctionToString.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function ( ...args) {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n }\n} FunctionToString.__initStatic();\n\nexport { FunctionToString };\n//# sourceMappingURL=functiontostring.js.map\n","import { logger, getEventDescription, stringMatchesSomePattern } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\n/** Options for the InboundFilters integration */\n\n/** Inbound filters configurable by the user */\nclass InboundFilters {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'InboundFilters';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = InboundFilters.id;}\n\n constructor( _options = {}) {this._options = _options;InboundFilters.prototype.__init.call(this);}\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n const eventProcess = (event) => {\n const hub = getCurrentHub();\n if (hub) {\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n const options = _mergeOptions(self._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n }\n return event;\n };\n\n eventProcess.id = this.name;\n addGlobalEventProcessor(eventProcess);\n }\n} InboundFilters.__initStatic();\n\n/** JSDoc */\nfunction _mergeOptions(\n internalOptions = {},\n clientOptions = {},\n) {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...DEFAULT_IGNORE_ERRORS,\n ],\n ignoreTransactions: [...(internalOptions.ignoreTransactions || []), ...(clientOptions.ignoreTransactions || [])],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(event, options) {\n if (options.ignoreInternal && _isSentryError(event)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event, ignoreErrors) {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return _getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event, ignoreTransactions) {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event, denyUrls) {\n // TODO: Use Glob instead?\n if (!denyUrls || !denyUrls.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event, allowUrls) {\n // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event) {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n try {\n const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n}\n\nfunction _isSentryError(event) {\n try {\n // @ts-ignore can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames = []) {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event) {\n try {\n let frames;\n try {\n // @ts-ignore we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nexport { InboundFilters, _mergeOptions, _shouldDropEvent };\n//# sourceMappingURL=inboundfilters.js.map\n","import { withScope, captureException } from '@sentry/core';\nimport { GLOBAL_OBJ, getOriginalFunction, markFunctionWrapped, addNonEnumerableProperty, addExceptionTypeValue, addExceptionMechanism } from '@sentry/utils';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nlet ignoreOnError = 0;\n\n/**\n * @hidden\n */\nfunction shouldIgnoreOnError() {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nfunction ignoreNextOnError() {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nfunction wrap(\n fn,\n options\n\n = {},\n before,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n if (typeof fn !== 'function') {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = fn.__sentry_wrapped__;\n if (wrapper) {\n return wrapper;\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function () {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const wrappedArguments = args.map((arg) => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope((scope) => {\n scope.addEventProcessor((event) => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n };\n /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property] = fn[property];\n }\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name') ;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get() {\n return fn.name;\n },\n });\n }\n // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\n\nexport { WINDOW, ignoreNextOnError, shouldIgnoreOnError, wrap };\n//# sourceMappingURL=helpers.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { addExceptionMechanism, resolvedSyncPromise, isErrorEvent, isDOMError, isDOMException, addExceptionTypeValue, isError, isPlainObject, isEvent, extractExceptionKeysForMessage, normalizeToSize } from '@sentry/utils';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nfunction exceptionFromError(stackParser, ex) {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception = {\n type: ex && ex.name,\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\n/**\n * @hidden\n */\nfunction eventFromPlainObject(\n stackParser,\n exception,\n syntheticException,\n isUnhandledRejection,\n) {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\n\n const event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: `Non-Error ${\n isUnhandledRejection ? 'promise rejection' : 'exception'\n } captured with keys: ${extractExceptionKeysForMessage(exception)}`,\n },\n ],\n },\n extra: {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n },\n };\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n (event.exception ).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\n */\nfunction eventFromError(stackParser, ex) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nfunction parseStackFrames(\n stackParser,\n ex,\n) {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\nfunction getPopSize(ex) {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex) {\n const message = ex && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nfunction eventFromException(\n stackParser,\n exception,\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n // eslint-disable-next-line deprecation/deprecation\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && hint.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nfunction eventFromUnknownInput(\n stackParser,\n exception,\n syntheticException,\n attachStacktrace,\n isUnhandledRejection,\n) {\n let event;\n\n if (isErrorEvent(exception ) && (exception ).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception ;\n return eventFromError(stackParser, errorEvent.error );\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception ) || isDOMException(exception )) {\n const domException = exception ;\n\n if ('stack' in (exception )) {\n event = eventFromError(stackParser, exception );\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception ;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception , syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\n/**\n * @hidden\n */\nfunction eventFromString(\n stackParser,\n input,\n syntheticException,\n attachStacktrace,\n) {\n const event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: input, stacktrace: { frames } }],\n };\n }\n }\n\n return event;\n}\n\nexport { eventFromError, eventFromException, eventFromMessage, eventFromPlainObject, eventFromString, eventFromUnknownInput, exceptionFromError, parseStackFrames };\n//# sourceMappingURL=eventbuilder.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { addInstrumentationHandler, getEventDescription, severityLevelFromString, safeJoin, SENTRY_XHR_DATA_KEY, parseUrl, logger, htmlTreeAsString } from '@sentry/utils';\nimport { WINDOW } from '../helpers.js';\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst BREADCRUMB_INTEGRATION_ID = 'Breadcrumbs';\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nclass Breadcrumbs {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = BREADCRUMB_INTEGRATION_ID;}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Breadcrumbs.id;}\n\n /**\n * Options of the breadcrumbs integration.\n */\n // This field is public, because we use it in the browser client to check if the `sentry` option is enabled.\n\n /**\n * @inheritDoc\n */\n constructor(options) {Breadcrumbs.prototype.__init.call(this);\n this.options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n setupOnce() {\n if (this.options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this.options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this.options.dom));\n }\n if (this.options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this.options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this.options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n }\n\n /**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\n addSentryBreadcrumb(event) {\n if (this.options.sentry) {\n getCurrentHub().addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n }\n }\n} Breadcrumbs.__initStatic();\n\n/**\n * A HOC that creaes a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _domBreadcrumb(dom) {\n function _innerDomBreadcrumb(handlerData) {\n let target;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event ;\n target = _isEvent(event)\n ? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })\n : htmlTreeAsString(event, { keyAttrs, maxStringLength });\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _consoleBreadcrumb(handlerData) {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/6010\n // see: https://github.com/getsentry/sentry-javascript/issues/5916\n for (let i = 0; i < handlerData.args.length; i++) {\n if (handlerData.args[i] === 'ref=Ref<') {\n handlerData.args[i + 1] = 'viewRef';\n break;\n }\n }\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _xhrBreadcrumb(handlerData) {\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data = {\n method,\n url,\n status_code,\n };\n\n const hint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _fetchBreadcrumb(handlerData) {\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n if (handlerData.error) {\n const data = handlerData.fetchData;\n const hint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const data = {\n ...handlerData.fetchData,\n status_code: handlerData.response && handlerData.response.status,\n };\n const hint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp,\n endTimestamp,\n };\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _historyBreadcrumb(handlerData) {\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = parseUrl(from);\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n\nfunction _isEvent(event) {\n return event && !!(event ).target;\n}\n\nexport { BREADCRUMB_INTEGRATION_ID, Breadcrumbs };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { dsnToString, createEnvelope } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nfunction createUserFeedbackEnvelope(\n feedback,\n {\n metadata,\n tunnel,\n dsn,\n }\n\n,\n) {\n const headers = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback) {\n const feedbackHeaders = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n\nexport { createUserFeedbackEnvelope };\n//# sourceMappingURL=userfeedback.js.map\n","import { BaseClient, SDK_VERSION } from '@sentry/core';\nimport { getSDKSource, logger, createClientReportEnvelope, dsnToString } from '@sentry/utils';\nimport { eventFromException, eventFromMessage } from './eventbuilder.js';\nimport { WINDOW } from './helpers.js';\nimport { BREADCRUMB_INTEGRATION_ID } from './integrations/breadcrumbs.js';\nimport { createUserFeedbackEnvelope } from './userfeedback.js';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types Options for more information.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nclass BrowserClient extends BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: `${sdkSource}:@sentry/browser`,\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n eventFromException(exception, hint) {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n eventFromMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level = 'info',\n hint,\n ) {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n sendEvent(event, hint) {\n // We only want to add the sentry event breadcrumb when the user has the breadcrumb integration installed and\n // activated its `sentry` option.\n // We also do not want to use the `Breadcrumbs` class here directly, because we do not want it to be included in\n // bundles, if it is not used by the SDK.\n // This all sadly is a bit ugly, but we currently don't have a \"pre-send\" hook on the integrations so we do it this\n // way for now.\n const breadcrumbIntegration = this.getIntegrationById(BREADCRUMB_INTEGRATION_ID) ;\n // We check for definedness of `addSentryBreadcrumb` in case users provided their own integration with id\n // \"Breadcrumbs\" that does not have this function.\n if (breadcrumbIntegration && breadcrumbIntegration.addSentryBreadcrumb) {\n breadcrumbIntegration.addSentryBreadcrumb(event);\n }\n\n super.sendEvent(event, hint);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n captureUserFeedback(feedback) {\n if (!this._isEnabled()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n void this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(event, hint, scope) {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n _flushOutcomes() {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('No outcomes to send');\n return;\n }\n\n if (!this._dsn) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n void this._sendEnvelope(envelope);\n }\n}\n\nexport { BrowserClient };\n//# sourceMappingURL=client.js.map\n","import { isNativeFetch, logger } from '@sentry/utils';\nimport { WINDOW } from '../helpers.js';\n\nlet cachedFetchImpl = undefined;\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nfunction getNativeFetchImplementation() {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nfunction clearCachedFetchImplementation() {\n cachedFetchImpl = undefined;\n}\n\nexport { clearCachedFetchImplementation, getNativeFetchImplementation };\n//# sourceMappingURL=utils.js.map\n","import { createTransport } from '@sentry/core';\nimport { rejectedSyncPromise } from '@sentry/utils';\nimport { getNativeFetchImplementation, clearCachedFetchImplementation } from './utils.js';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nfunction makeFetchTransport(\n options,\n nativeFetch = getNativeFetchImplementation(),\n) {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request) {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. whenfinishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeFetchTransport };\n//# sourceMappingURL=fetch.js.map\n","import { createTransport } from '@sentry/core';\nimport { SyncPromise } from '@sentry/utils';\n\n/**\n * The DONE ready state for XmlHttpRequest\n *\n * Defining it here as a constant b/c XMLHttpRequest.DONE is not always defined\n * (e.g. during testing, it is `undefined`)\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState}\n */\nconst XHR_READYSTATE_DONE = 4;\n\n/**\n * Creates a Transport that uses the XMLHttpRequest API to send events to Sentry.\n */\nfunction makeXHRTransport(options) {\n function makeRequest(request) {\n return new SyncPromise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n\n xhr.onerror = reject;\n\n xhr.onreadystatechange = () => {\n if (xhr.readyState === XHR_READYSTATE_DONE) {\n resolve({\n statusCode: xhr.status,\n headers: {\n 'x-sentry-rate-limits': xhr.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': xhr.getResponseHeader('Retry-After'),\n },\n });\n }\n };\n\n xhr.open('POST', options.url);\n\n for (const header in options.headers) {\n if (Object.prototype.hasOwnProperty.call(options.headers, header)) {\n xhr.setRequestHeader(header, options.headers[header]);\n }\n }\n\n xhr.send(request.body);\n });\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeXHRTransport };\n//# sourceMappingURL=xhr.js.map\n","import { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename, func, lineno, colno) {\n const frame = {\n filename,\n function: func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.*\\).*?|.*?) ?\\((?:address at )?)?(?:async )?((?:file|https?|blob|chrome-extension|address|native|eval|webpack||[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome = line => {\n const parts = chromeRegex.exec(line);\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nconst chromeStackLineParser = [CHROME_PRIORITY, chrome];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|safari-extension|safari-web-extension|capacitor)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko = line => {\n const parts = geckoREgex.exec(line);\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nconst geckoStackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex =\n /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs = line => {\n const parts = winjsRegex.exec(line);\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nconst winjsStackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10 = line => {\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nconst opera10StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11 = line => {\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nconst opera11StackLineParser = [OPERA11_PRIORITY, opera11];\n\nconst defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser, winjsStackLineParser];\n\nconst defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func, filename) => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n\nexport { chromeStackLineParser, defaultStackLineParsers, defaultStackParser, geckoStackLineParser, opera10StackLineParser, opera11StackLineParser, winjsStackLineParser };\n//# sourceMappingURL=stack-parsers.js.map\n","import { getCurrentHub } from '@sentry/core';\nimport { addInstrumentationHandler, isString, isPrimitive, isErrorEvent, getLocationHref, logger, addExceptionMechanism } from '@sentry/utils';\nimport { eventFromUnknownInput } from '../eventbuilder.js';\nimport { shouldIgnoreOnError } from '../helpers.js';\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n/** Global handlers */\nclass GlobalHandlers {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'GlobalHandlers';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = GlobalHandlers.id;}\n\n /** JSDoc */\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n __init2() {this._installFunc = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };}\n\n /** JSDoc */\n constructor(options) {GlobalHandlers.prototype.__init.call(this);GlobalHandlers.prototype.__init2.call(this);\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n }\n /**\n * @inheritDoc\n */\n setupOnce() {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key ];\n if (installFunc && options[key ]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key ] = undefined;\n }\n }\n }\n} GlobalHandlers.__initStatic();\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler() {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler() {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in e) {\n error = e.reason;\n }\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason) {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg, url, line, column) {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event, url, line, column) {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub, error, event, type) {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndOptions() {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return [hub, options.stackParser, options.attachStacktrace];\n}\n\nexport { GlobalHandlers };\n//# sourceMappingURL=globalhandlers.js.map\n","import { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\nimport { WINDOW, wrap } from '../helpers.js';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nclass TryCatch {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'TryCatch';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = TryCatch.id;}\n\n /** JSDoc */\n\n /**\n * @inheritDoc\n */\n constructor(options) {TryCatch.prototype.__init.call(this);\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n setupOnce() {\n if (this._options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n} TryCatch.__initStatic();\n\n/** JSDoc */\nfunction _wrapTimeFunction(original) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function ( ...args) {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: true,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function ( callback) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\n/** JSDoc */\nfunction _wrapXHR(originalSend) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function ( ...args) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(xhr, prop, function (original) {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: true,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before TryCatch, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\n/** JSDoc */\nfunction _wrapEventTarget(target) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW ;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original)\n\n {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n eventName,\n fn,\n options,\n ) {\n try {\n if (typeof fn.handleEvent === 'function') {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n });\n }\n } catch (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n wrap(fn , {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: true,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n eventName,\n fn,\n options,\n ) {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n const wrappedEventHandler = fn ;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);\n };\n },\n );\n}\n\nexport { TryCatch };\n//# sourceMappingURL=trycatch.js.map\n","import { getCurrentHub, addGlobalEventProcessor } from '@sentry/core';\nimport { isInstanceOf } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder.js';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\n/** Adds SDK info to an event. */\nclass LinkedErrors {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'LinkedErrors';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = LinkedErrors.id;}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {LinkedErrors.prototype.__init.call(this);\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n const client = getCurrentHub().getClient();\n if (!client) {\n return;\n }\n addGlobalEventProcessor((event, hint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n return self ? _handler(client.getOptions().stackParser, self._key, self._limit, event, hint) : event;\n });\n }\n} LinkedErrors.__initStatic();\n\n/**\n * @inheritDoc\n */\nfunction _handler(\n parser,\n key,\n limit,\n event,\n hint,\n) {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return event;\n }\n const linkedErrors = _walkErrorTree(parser, limit, hint.originalException , key);\n event.exception.values = [...linkedErrors, ...event.exception.values];\n return event;\n}\n\n/**\n * JSDOC\n */\nfunction _walkErrorTree(\n parser,\n limit,\n error,\n key,\n stack = [],\n) {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {\n return stack;\n }\n const exception = exceptionFromError(parser, error[key]);\n return _walkErrorTree(parser, limit, error[key], key, [exception, ...stack]);\n}\n\nexport { LinkedErrors, _handler, _walkErrorTree };\n//# sourceMappingURL=linkederrors.js.map\n","import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { WINDOW } from '../helpers.js';\n\n/** HttpContext integration collects information about HTTP request headers */\nclass HttpContext {constructor() { HttpContext.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'HttpContext';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = HttpContext.id;}\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n addGlobalEventProcessor((event) => {\n if (getCurrentHub().getIntegration(HttpContext)) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return event;\n }\n\n // grab as much info as exists and add it to the event\n const url = (event.request && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n return { ...event, request };\n }\n return event;\n });\n }\n} HttpContext.__initStatic();\n\nexport { HttpContext };\n//# sourceMappingURL=httpcontext.js.map\n","import { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nclass Dedupe {constructor() { Dedupe.prototype.__init.call(this); }\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Dedupe';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Dedupe.id;}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor, getCurrentHub) {\n const eventProcessor = currentEvent => {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, self._previousEvent)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n };\n\n eventProcessor.id = this.name;\n addGlobalEventProcessor(eventProcessor);\n }\n} Dedupe.__initStatic();\n\n/** JSDoc */\nfunction _shouldDropEvent(currentEvent, previousEvent) {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\n/** JSDoc */\nfunction _isSameMessageEvent(currentEvent, previousEvent) {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameExceptionEvent(currentEvent, previousEvent) {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameStacktrace(currentEvent, previousEvent) {\n let currentFrames = _getFramesFromEvent(currentEvent);\n let previousFrames = _getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames ;\n previousFrames = previousFrames ;\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/** JSDoc */\nfunction _isSameFingerprint(currentEvent, previousEvent) {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint ;\n previousFingerprint = previousFingerprint ;\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\n/** JSDoc */\nfunction _getExceptionFromEvent(event) {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event) {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n\nexport { Dedupe };\n//# sourceMappingURL=dedupe.js.map\n","import { Integrations, getIntegrationsToSetup, initAndBind, getReportDialogEndpoint, getCurrentHub } from '@sentry/core';\nimport { stackParserFromStackParserOptions, supportsFetch, logger, resolvedSyncPromise, addInstrumentationHandler } from '@sentry/utils';\nimport { BrowserClient } from './client.js';\nimport { WINDOW, wrap as wrap$1 } from './helpers.js';\nimport { GlobalHandlers } from './integrations/globalhandlers.js';\nimport { TryCatch } from './integrations/trycatch.js';\nimport { Breadcrumbs } from './integrations/breadcrumbs.js';\nimport { LinkedErrors } from './integrations/linkederrors.js';\nimport { HttpContext } from './integrations/httpcontext.js';\nimport { Dedupe } from './integrations/dedupe.js';\nimport { defaultStackParser } from './stack-parsers.js';\nimport { makeFetchTransport } from './transports/fetch.js';\nimport { makeXHRTransport } from './transports/xhr.js';\n\nconst defaultIntegrations = [\n new Integrations.InboundFilters(),\n new Integrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new HttpContext(),\n];\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nfunction init(options = {}) {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nfunction showReportDialog(options = {}, hub = getCurrentHub()) {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n options.eventId = hub.lastEventId();\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nfunction lastEventId() {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction forceLoad() {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction onLoad(callback) {\n callback();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nfunction flush(timeout) {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Cannot flush events. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nfunction close(timeout) {\n const client = getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return resolvedSyncPromise(false);\n}\n\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrap(fn) {\n return wrap$1(fn)();\n}\n\nfunction startSessionOnHub(hub) {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking() {\n if (typeof WINDOW.document === 'undefined') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (!(from === undefined || from === to)) {\n startSessionOnHub(getCurrentHub());\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nfunction captureUserFeedback(feedback) {\n const client = getCurrentHub().getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n\nexport { captureUserFeedback, close, defaultIntegrations, flush, forceLoad, init, lastEventId, onLoad, showReportDialog, wrap };\n//# sourceMappingURL=sdk.js.map\n","import { getCurrentHub, addBreadcrumb, addGlobalEventProcessor, prepareEvent, setContext, captureException } from '@sentry/core';\nimport { GLOBAL_OBJ, logger, uuid4, normalize, htmlTreeAsString, SENTRY_XHR_DATA_KEY, dropUndefinedKeys, addInstrumentationHandler, browserPerformanceTimeOrigin, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, isNodeEnv } from '@sentry/utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nconst WINDOW = GLOBAL_OBJ ;\n\nconst REPLAY_SESSION_KEY = 'sentryReplaySession';\nconst REPLAY_EVENT_NAME = 'replay_event';\nconst UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session\nconst SESSION_IDLE_DURATION = 300000; // 5 minutes in ms\n\n// The maximum length of a session\nconst MAX_SESSION_LIFE = 3600000; // 60 minutes\n\n/** Default flush delays */\nconst DEFAULT_FLUSH_MIN_DELAY = 5000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nconst DEFAULT_FLUSH_MAX_DELAY = 5500;\n\n/* How long to wait for error checkouts */\nconst ERROR_CHECKOUT_TIME = 60000;\n\nconst RETRY_BASE_INTERVAL = 5000;\nconst RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be dropped. */\nconst NETWORK_BODY_MAX_SIZE = 300000;\n\nvar NodeType$1;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType$1 || (NodeType$1 = {}));\n\nfunction isElement(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const host = n === null || n === void 0 ? void 0 : n.host;\n return Boolean(host && host.shadowRoot && host.shadowRoot === n);\n}\nfunction isInputTypeMasked({ maskInputOptions, tagName, type, }) {\n if (tagName.toLowerCase() === 'option') {\n tagName = 'select';\n }\n const actualType = typeof type === 'string' ? type.toLowerCase() : undefined;\n return (maskInputOptions[tagName.toLowerCase()] ||\n (actualType && maskInputOptions[actualType]) ||\n actualType === 'password' ||\n (tagName === 'input' && !type && maskInputOptions['text']));\n}\nfunction hasInputMaskOptions({ tagName, type, maskInputOptions, maskInputSelector, }) {\n return (maskInputSelector || isInputTypeMasked({ maskInputOptions, tagName, type }));\n}\nfunction maskInputValue({ input, maskInputSelector, unmaskInputSelector, maskInputOptions, tagName, type, value, maskInputFn, }) {\n let text = value || '';\n if (unmaskInputSelector && input.matches(unmaskInputSelector)) {\n return text;\n }\n if (input.hasAttribute('rr_is_password')) {\n type = 'password';\n }\n if (isInputTypeMasked({ maskInputOptions, tagName, type }) ||\n (maskInputSelector && input.matches(maskInputSelector))) {\n if (maskInputFn) {\n text = maskInputFn(text);\n }\n else {\n text = '*'.repeat(text.length);\n }\n }\n return text;\n}\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext('2d');\n if (!ctx)\n return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n : getImageData;\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\n if (pixelBuffer.some((pixel) => pixel !== 0))\n return false;\n }\n }\n return true;\n}\n\nlet _id = 1;\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\nconst IGNORED_NODE = -2;\nfunction defaultMaskFn(str) {\n return str ? str.replace(/[\\S]/g, '*') : '';\n}\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return 'form';\n }\n const processedTagName = element.tagName.toLowerCase().trim();\n if (tagNameRegex.test(processedTagName)) {\n return 'div';\n }\n return processedTagName;\n}\nfunction getCssRulesString(s) {\n try {\n const rules = s.rules || s.cssRules;\n return rules ? Array.from(rules).map(getCssRuleString).join('') : null;\n }\n catch (error) {\n return null;\n }\n}\nfunction getCssRuleString(rule) {\n let cssStringified = rule.cssText;\n if (isCSSImportRule(rule)) {\n try {\n cssStringified = getCssRulesString(rule.styleSheet) || cssStringified;\n }\n catch (_a) {\n }\n }\n return cssStringified;\n}\nfunction isCSSImportRule(rule) {\n return 'styleSheet' in rule;\n}\nfunction stringifyStyleSheet(sheet) {\n return sheet.cssRules\n ? Array.from(sheet.cssRules)\n .map((rule) => rule.cssText || '')\n .join('')\n : '';\n}\nfunction extractOrigin(url) {\n let origin = '';\n if (url.indexOf('//') > -1) {\n origin = url.split('/').slice(0, 3).join('/');\n }\n else {\n origin = url.split('/')[0];\n }\n origin = origin.split('?')[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst RELATIVE_PATH = /^(?!www\\.|(?:http|ftp)s?:\\/\\/|[A-Za-z]:\\\\|\\/\\/|#).*/;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || '';\n if (!filePath) {\n return origin;\n }\n if (!RELATIVE_PATH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === '/') {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split('/');\n const parts = filePath.split('/');\n stack.pop();\n for (const part of parts) {\n if (part === '.') {\n continue;\n }\n else if (part === '..') {\n stack.pop();\n }\n else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\n });\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === '') {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars;\n let match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars = match[0];\n pos += chars.length;\n return chars;\n }\n return '';\n }\n let output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === ',') {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n }\n else {\n let descriptorsStr = '';\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n let c = attributeValue.charAt(pos);\n if (c === '') {\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (!inParens) {\n if (c === ',') {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (c === '(') {\n inParens = true;\n }\n }\n else {\n if (c === ')') {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(', ');\n}\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === '') {\n return attributeValue;\n }\n const a = doc.createElement('a');\n a.href = attributeValue;\n return a.href;\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\n}\nfunction getHref() {\n const a = document.createElement('a');\n a.href = '';\n return a.href;\n}\nfunction transformAttribute(doc, element, _tagName, _name, value, maskAllText, unmaskTextSelector, maskTextFn) {\n if (!value) {\n return value;\n }\n const name = _name.toLowerCase();\n const tagName = _tagName.toLowerCase();\n if (name === 'src' || name === 'href') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'xlink:href' && value[0] !== '#') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'background' &&\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'srcset') {\n return getAbsoluteSrcsetString(doc, value);\n }\n else if (name === 'style') {\n return absoluteToStylesheet(value, getHref());\n }\n else if (tagName === 'object' && name === 'data') {\n return absoluteToDoc(doc, value);\n }\n else if (maskAllText &&\n _shouldMaskAttribute(element, name, tagName, unmaskTextSelector)) {\n return maskTextFn ? maskTextFn(value) : defaultMaskFn(value);\n }\n return value;\n}\nfunction _shouldMaskAttribute(element, attribute, tagName, unmaskTextSelector) {\n if (unmaskTextSelector && element.matches(unmaskTextSelector)) {\n return false;\n }\n return (['placeholder', 'title', 'aria-label'].indexOf(attribute) > -1 ||\n (tagName === 'input' &&\n attribute === 'value' &&\n element.hasAttribute('type') &&\n ['submit', 'button'].indexOf(element.getAttribute('type').toLowerCase()) > -1));\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === 'string') {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < element.classList.length; eIndex++) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n return false;\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) {\n if (!node) {\n return false;\n }\n if (node.nodeType !== node.ELEMENT_NODE) {\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n }\n if (unmaskTextSelector) {\n if (node.matches(unmaskTextSelector) ||\n node.closest(unmaskTextSelector)) {\n return false;\n }\n }\n if (maskAllText) {\n return true;\n }\n if (typeof maskTextClass === 'string') {\n if (node.classList.contains(maskTextClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = 0; eIndex < node.classList.length; eIndex++) {\n const className = node.classList[eIndex];\n if (maskTextClass.test(className)) {\n return true;\n }\n }\n }\n if (maskTextSelector) {\n if (node.matches(maskTextSelector)) {\n return true;\n }\n }\n return needMaskingText(node.parentNode, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText);\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n }\n catch (error) {\n return;\n }\n if (readyState !== 'complete') {\n const timer = setTimeout(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener('load', () => {\n clearTimeout(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = 'about:blank';\n if (win.location.href !== blankUrl ||\n iframeEl.src === blankUrl ||\n iframeEl.src === '') {\n setTimeout(listener, 0);\n return;\n }\n iframeEl.addEventListener('load', listener);\n}\nfunction serializeNode(n, options) {\n var _a;\n const { doc, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, } = options;\n let rootId;\n if (doc.__sn) {\n const docId = doc.__sn.id;\n rootId = docId === 1 ? undefined : docId;\n }\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== 'CSS1Compat') {\n return {\n type: NodeType$1.Document,\n childNodes: [],\n compatMode: n.compatMode,\n rootId,\n };\n }\n else {\n return {\n type: NodeType$1.Document,\n childNodes: [],\n rootId,\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType$1.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId,\n };\n case n.ELEMENT_NODE:\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n for (const { name, value } of Array.from(n.attributes)) {\n if (!skipAttribute(tagName, name)) {\n attributes[name] = transformAttribute(doc, n, tagName, name, value, maskAllText, unmaskTextSelector, maskTextFn);\n }\n }\n if (tagName === 'link' && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\n return s.href === n.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = getCssRulesString(stylesheet);\n }\n if (cssText) {\n delete attributes.rel;\n delete attributes.href;\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === 'style' &&\n n.sheet &&\n !(n.innerText ||\n n.textContent ||\n '').trim().length) {\n const cssText = getCssRulesString(n.sheet);\n if (cssText) {\n attributes._cssText = absoluteToStylesheet(cssText, getHref());\n }\n }\n if (tagName === 'input' ||\n tagName === 'textarea' ||\n tagName === 'select' ||\n tagName === 'option') {\n const el = n;\n const value = getInputValue(tagName, el, attributes);\n const checked = n.checked;\n if (attributes.type !== 'submit' &&\n attributes.type !== 'button' &&\n value) {\n attributes.value = maskInputValue({\n input: el,\n type: attributes.type,\n tagName,\n value,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === 'option') {\n if (n.selected && !maskInputOptions['select']) {\n attributes.selected = true;\n }\n else {\n delete attributes.selected;\n }\n }\n if (tagName === 'canvas' && recordCanvas) {\n if (n.__context === '2d') {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n }\n else if (!('__context' in n)) {\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n const blankCanvas = document.createElement('canvas');\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === 'img' && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement('canvas');\n canvasCtx = canvasService.getContext('2d');\n }\n const image = n;\n const oldValue = image.crossOrigin;\n image.crossOrigin = 'anonymous';\n const recordInlineImage = () => {\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n catch (err) {\n console.warn(`Cannot inline img src=${image.currentSrc}! Error: ${err}`);\n }\n oldValue\n ? (attributes.crossOrigin = oldValue)\n : delete attributes.crossOrigin;\n };\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else\n image.onload = recordInlineImage;\n }\n if (tagName === 'audio' || tagName === 'video') {\n attributes.rr_mediaState = n.paused\n ? 'paused'\n : 'played';\n attributes.rr_mediaCurrentTime = n.currentTime;\n }\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n };\n }\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\n if (!n.contentDocument) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n return {\n type: NodeType$1.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || undefined,\n needBlock,\n rootId,\n };\n case n.TEXT_NODE:\n const parentTagName = n.parentNode && n.parentNode.tagName;\n let textContent = n.textContent;\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n }\n else if ((_a = n.parentNode.sheet) === null || _a === void 0 ? void 0 : _a.cssRules) {\n textContent = stringifyStyleSheet(n.parentNode.sheet);\n }\n }\n catch (err) {\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\n }\n textContent = absoluteToStylesheet(textContent, getHref());\n }\n if (isScript) {\n textContent = 'SCRIPT_PLACEHOLDER';\n }\n if (parentTagName === 'TEXTAREA' && textContent) {\n textContent = '';\n }\n else if (parentTagName === 'OPTION' && textContent) {\n const option = n.parentNode;\n textContent = maskInputValue({\n input: option,\n type: null,\n tagName: parentTagName,\n value: textContent,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n maskInputFn,\n });\n }\n else if (!isStyle &&\n !isScript &&\n needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextSelector, maskAllText) &&\n textContent) {\n textContent = maskTextFn\n ? maskTextFn(textContent)\n : defaultMaskFn(textContent);\n }\n return {\n type: NodeType$1.Text,\n textContent: textContent || '',\n isStyle,\n rootId,\n };\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType$1.CDATA,\n textContent: '',\n rootId,\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType$1.Comment,\n textContent: n.textContent || '',\n rootId,\n };\n default:\n return false;\n }\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === undefined || maybeAttr === null) {\n return '';\n }\n else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType$1.Comment) {\n return true;\n }\n else if (sn.type === NodeType$1.Element) {\n if (slimDOMOptions.script &&\n (sn.tagName === 'script' ||\n (sn.tagName === 'link' &&\n (sn.attributes.rel === 'preload' ||\n sn.attributes.rel === 'modulepreload') &&\n sn.attributes.as === 'script') ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'prefetch' &&\n typeof sn.attributes.href === 'string' &&\n sn.attributes.href.endsWith('.js')))) {\n return true;\n }\n else if (slimDOMOptions.headFavicon &&\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n (sn.tagName === 'meta' &&\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\n lowerIfExists(sn.attributes.name) === 'application-name' ||\n lowerIfExists(sn.attributes.rel) === 'icon' ||\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\n return true;\n }\n else if (sn.tagName === 'meta') {\n if (slimDOMOptions.headMetaDescKeywords &&\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n }\n else if (slimDOMOptions.headMetaSocial &&\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\n return true;\n }\n else if (slimDOMOptions.headMetaRobots &&\n (lowerIfExists(sn.attributes.name) === 'robots' ||\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\n return true;\n }\n else if (slimDOMOptions.headMetaHttpEquiv &&\n sn.attributes['http-equiv'] !== undefined) {\n return true;\n }\n else if (slimDOMOptions.headMetaAuthorship &&\n (lowerIfExists(sn.attributes.name) === 'author' ||\n lowerIfExists(sn.attributes.name) === 'generator' ||\n lowerIfExists(sn.attributes.name) === 'framework' ||\n lowerIfExists(sn.attributes.name) === 'publisher' ||\n lowerIfExists(sn.attributes.name) === 'progid' ||\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n }\n else if (slimDOMOptions.headMetaVerification &&\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n lowerIfExists(sn.attributes.name) === 'verification' ||\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const { doc, map, blockClass, blockSelector, unblockSelector, maskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputSelector, unmaskInputSelector, maskAllText, maskInputOptions = {}, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, keepIframeSrcFn = () => false, } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n });\n if (!_serializedNode) {\n console.warn(n, 'not serialized');\n return null;\n }\n let id;\n if ('__sn' in n) {\n id = n.__sn.id;\n }\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n (!preserveWhiteSpace &&\n _serializedNode.type === NodeType$1.Text &&\n !_serializedNode.isStyle &&\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\n id = IGNORED_NODE;\n }\n else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n n.__sn = serializedNode;\n if (id === IGNORED_NODE) {\n return null;\n }\n map[id] = n;\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType$1.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n if (n.shadowRoot)\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType$1.Document ||\n serializedNode.type === NodeType$1.Element) &&\n recordChild) {\n if (slimDOMOptions.headWhitespace &&\n _serializedNode.type === NodeType$1.Element &&\n _serializedNode.tagName === 'head') {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n };\n for (const childN of Array.from(n.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n if (isElement(n) && n.shadowRoot) {\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedChildNode.isShadow = true;\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode && isShadowRoot(n.parentNode)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType$1.Element &&\n serializedNode.tagName === 'iframe') {\n onceIframeLoaded(n, () => {\n const iframeDoc = n.contentDocument;\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n map,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n });\n if (serializedIframeNode) {\n onIframeLoad(n, serializedIframeNode);\n }\n }\n }, iframeLoadTimeout);\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n const { blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskInputSelector = null, unmaskInputSelector = null, maskAllText = false, maskAllInputs = false, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, keepIframeSrcFn = () => false, } = options || {};\n const idNodeMap = {};\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n }\n : maskAllInputs === false\n ? {}\n : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\n ?\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === 'all',\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true,\n }\n : slimDOM === false\n ? {}\n : slimDOM;\n return [\n serializeNodeWithId(n, {\n doc: n,\n map: idNodeMap,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputSelector,\n unmaskInputSelector,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n keepIframeSrcFn,\n }),\n idNodeMap,\n ];\n}\nfunction skipAttribute(tagName, attributeName, value) {\n return ((tagName === 'video' || tagName === 'audio') && attributeName === 'autoplay');\n}\nfunction getInputValue(tagName, el, attributes) {\n if (tagName === 'input' &&\n (attributes.type === 'radio' || attributes.type === 'checkbox')) {\n return el.getAttribute('value') || '';\n }\n return el.value;\n}\n\nvar EventType;\n(function (EventType) {\n EventType[EventType[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType[EventType[\"Load\"] = 1] = \"Load\";\n EventType[EventType[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType[EventType[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType[EventType[\"Meta\"] = 4] = \"Meta\";\n EventType[EventType[\"Custom\"] = 5] = \"Custom\";\n EventType[EventType[\"Plugin\"] = 6] = \"Plugin\";\n})(EventType || (EventType = {}));\nvar IncrementalSource;\n(function (IncrementalSource) {\n IncrementalSource[IncrementalSource[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource[IncrementalSource[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource[IncrementalSource[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource[IncrementalSource[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource[IncrementalSource[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource[IncrementalSource[\"Input\"] = 5] = \"Input\";\n IncrementalSource[IncrementalSource[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource[IncrementalSource[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource[IncrementalSource[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource[IncrementalSource[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource[IncrementalSource[\"Font\"] = 10] = \"Font\";\n IncrementalSource[IncrementalSource[\"Log\"] = 11] = \"Log\";\n IncrementalSource[IncrementalSource[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource[IncrementalSource[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n})(IncrementalSource || (IncrementalSource = {}));\nvar MouseInteractions;\n(function (MouseInteractions) {\n MouseInteractions[MouseInteractions[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions[MouseInteractions[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions[MouseInteractions[\"Click\"] = 2] = \"Click\";\n MouseInteractions[MouseInteractions[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions[MouseInteractions[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions[MouseInteractions[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions[MouseInteractions[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions[MouseInteractions[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions[MouseInteractions[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions[MouseInteractions[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions[MouseInteractions[\"TouchCancel\"] = 10] = \"TouchCancel\";\n})(MouseInteractions || (MouseInteractions = {}));\nvar CanvasContext;\n(function (CanvasContext) {\n CanvasContext[CanvasContext[\"2D\"] = 0] = \"2D\";\n CanvasContext[CanvasContext[\"WebGL\"] = 1] = \"WebGL\";\n CanvasContext[CanvasContext[\"WebGL2\"] = 2] = \"WebGL2\";\n})(CanvasContext || (CanvasContext = {}));\nvar MediaInteractions;\n(function (MediaInteractions) {\n MediaInteractions[MediaInteractions[\"Play\"] = 0] = \"Play\";\n MediaInteractions[MediaInteractions[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions[MediaInteractions[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions[MediaInteractions[\"VolumeChange\"] = 3] = \"VolumeChange\";\n})(MediaInteractions || (MediaInteractions = {}));\nvar ReplayerEvents;\n(function (ReplayerEvents) {\n ReplayerEvents[\"Start\"] = \"start\";\n ReplayerEvents[\"Pause\"] = \"pause\";\n ReplayerEvents[\"Resume\"] = \"resume\";\n ReplayerEvents[\"Resize\"] = \"resize\";\n ReplayerEvents[\"Finish\"] = \"finish\";\n ReplayerEvents[\"FullsnapshotRebuilded\"] = \"fullsnapshot-rebuilded\";\n ReplayerEvents[\"LoadStylesheetStart\"] = \"load-stylesheet-start\";\n ReplayerEvents[\"LoadStylesheetEnd\"] = \"load-stylesheet-end\";\n ReplayerEvents[\"SkipStart\"] = \"skip-start\";\n ReplayerEvents[\"SkipEnd\"] = \"skip-end\";\n ReplayerEvents[\"MouseInteraction\"] = \"mouse-interaction\";\n ReplayerEvents[\"EventCast\"] = \"event-cast\";\n ReplayerEvents[\"CustomEvent\"] = \"custom-event\";\n ReplayerEvents[\"Flush\"] = \"flush\";\n ReplayerEvents[\"StateChange\"] = \"state-change\";\n ReplayerEvents[\"PlayBack\"] = \"play-back\";\n})(ReplayerEvents || (ReplayerEvents = {}));\n\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nfunction createMirror() {\n return {\n map: {},\n getId(n) {\n if (!n || !n.__sn) {\n return -1;\n }\n return n.__sn.id;\n },\n getNode(id) {\n return this.map[id] || null;\n },\n removeNodeFromMap(n) {\n const id = n.__sn && n.__sn.id;\n delete this.map[id];\n if (n.childNodes) {\n n.childNodes.forEach((child) => this.removeNodeFromMap(child));\n }\n },\n has(id) {\n return this.map.hasOwnProperty(id);\n },\n reset() {\n this.map = {};\n },\n };\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\n '\\r\\n' +\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\n '\\r\\n' +\n 'or you can use record.mirror to access the mirror instance during recording.';\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n};\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === 'map') {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n },\n });\n}\nfunction throttle(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function (arg) {\n let now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n let remaining = wait - (now - previous);\n let context = this;\n let args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n }\n else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(target, key, isRevoked\n ? d\n : {\n set(value) {\n setTimeout(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n },\n });\n return () => hookSetter(target, key, original || {}, true);\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => { };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === 'function') {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original,\n },\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n }\n catch (_a) {\n return () => { };\n }\n}\nfunction getWindowHeight() {\n return (window.innerHeight ||\n (document.documentElement && document.documentElement.clientHeight) ||\n (document.body && document.body.clientHeight));\n}\nfunction getWindowWidth() {\n return (window.innerWidth ||\n (document.documentElement && document.documentElement.clientWidth) ||\n (document.body && document.body.clientWidth));\n}\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector) {\n if (!node) {\n return false;\n }\n if (node.nodeType === node.ELEMENT_NODE) {\n let needBlock = false;\n const needUnblock = unblockSelector && node.matches(unblockSelector);\n if (typeof blockClass === 'string') {\n if (node.closest !== undefined) {\n needBlock =\n !needUnblock &&\n node.closest('.' + blockClass) !== null;\n }\n else {\n needBlock =\n !needUnblock && node.classList.contains(blockClass);\n }\n }\n else {\n !needUnblock &&\n node.classList.forEach((className) => {\n if (blockClass.test(className)) {\n needBlock = true;\n }\n });\n }\n if (!needBlock && blockSelector) {\n needBlock = node.matches(blockSelector);\n }\n return ((!needUnblock && needBlock) ||\n isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector));\n }\n if (node.nodeType === node.TEXT_NODE) {\n return isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector);\n }\n return isBlocked(node.parentNode, blockClass, blockSelector, unblockSelector);\n}\nfunction isIgnored(n) {\n if ('__sn' in n) {\n return n.__sn.id === IGNORED_NODE;\n }\n return false;\n}\nfunction isAncestorRemoved(target, mirror) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror.getId(target);\n if (!mirror.has(id)) {\n return true;\n }\n if (target.parentNode &&\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!target.parentNode) {\n return true;\n }\n return isAncestorRemoved(target.parentNode, mirror);\n}\nfunction isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype\n .forEach;\n }\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype\n .forEach;\n }\n if (!Node.prototype.contains) {\n Node.prototype.contains = function contains(node) {\n if (!(0 in arguments)) {\n throw new TypeError('1 argument is required');\n }\n do {\n if (this === node) {\n return true;\n }\n } while ((node = node && node.parentNode));\n return false;\n };\n }\n}\nfunction isIframeINode(node) {\n if ('__sn' in node) {\n return (node.__sn.type === NodeType$1.Element && node.__sn.tagName === 'iframe');\n }\n return false;\n}\nfunction hasShadowRoot(n) {\n return Boolean(n === null || n === void 0 ? void 0 : n.shadowRoot);\n}\n\nfunction isNodeInLinkedList(n) {\n return '__ln' in n;\n}\nclass DoubleLinkedList {\n constructor() {\n this.length = 0;\n this.head = null;\n }\n get(position) {\n if (position >= this.length) {\n throw new Error('Position outside of list range');\n }\n let current = this.head;\n for (let index = 0; index < position; index++) {\n current = (current === null || current === void 0 ? void 0 : current.next) || null;\n }\n return current;\n }\n addNode(n) {\n const node = {\n value: n,\n previous: null,\n next: null,\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n const current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n }\n else if (n.nextSibling &&\n isNodeInLinkedList(n.nextSibling) &&\n n.nextSibling.__ln.previous) {\n const current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n }\n else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n this.length++;\n }\n removeNode(n) {\n const current = n.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n }\n }\n else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nfunction isINode(n) {\n return '__sn' in n;\n}\nclass MutationBuffer {\n constructor() {\n this.frozen = false;\n this.locked = false;\n this.texts = [];\n this.attributes = [];\n this.removes = [];\n this.mapRemoves = [];\n this.movedMap = {};\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.processMutations = (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n };\n this.emit = () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addList = new DoubleLinkedList();\n const getNextId = (n) => {\n let ns = n;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n) => {\n var _a, _b, _c, _d, _e;\n const shadowHost = n.getRootNode\n ? (_a = n.getRootNode()) === null || _a === void 0 ? void 0 : _a.host\n : null;\n let rootShadowHost = shadowHost;\n while ((_c = (_b = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _b === void 0 ? void 0 : _b.call(rootShadowHost)) === null || _c === void 0 ? void 0 : _c.host)\n rootShadowHost =\n ((_e = (_d = rootShadowHost === null || rootShadowHost === void 0 ? void 0 : rootShadowHost.getRootNode) === null || _d === void 0 ? void 0 : _d.call(rootShadowHost)) === null || _e === void 0 ? void 0 : _e.host) ||\n null;\n const notInDoc = !this.doc.contains(n) &&\n (!rootShadowHost || !this.doc.contains(rootShadowHost));\n if (!n.parentNode || notInDoc) {\n return;\n }\n const parentId = isShadowRoot(n.parentNode)\n ? this.mirror.getId(shadowHost)\n : this.mirror.getId(n.parentNode);\n const nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n let sn = serializeNodeWithId(n, {\n doc: this.doc,\n map: this.mirror.map,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n unblockSelector: this.unblockSelector,\n maskTextClass: this.maskTextClass,\n maskTextSelector: this.maskTextSelector,\n unmaskTextSelector: this.unmaskTextSelector,\n maskInputSelector: this.maskInputSelector,\n unmaskInputSelector: this.unmaskInputSelector,\n skipChild: true,\n inlineStylesheet: this.inlineStylesheet,\n maskAllText: this.maskAllText,\n maskInputOptions: this.maskInputOptions,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isIframeINode(currentN)) {\n this.iframeManager.addIframe(currentN);\n }\n if (hasShadowRoot(n)) {\n this.shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n this.iframeManager.attachIframe(iframe, childSn);\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn,\n });\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n of this.movedSet) {\n if (isParentRemoved(this.removes, n, this.mirror) &&\n !this.movedSet.has(n.parentNode)) {\n continue;\n }\n pushAdd(n);\n }\n for (const n of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n) &&\n !isParentRemoved(this.removes, n, this.mirror)) {\n pushAdd(n);\n }\n else if (isAncestorInSet(this.movedSet, n)) {\n pushAdd(n);\n }\n else {\n this.droppedSet.add(n);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(candidate.value.parentNode);\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n for (let index = addList.length - 1; index >= 0; index--) {\n const _node = addList.get(index);\n if (_node) {\n const parentId = this.mirror.getId(_node.value.parentNode);\n const nextId = getNextId(_node.value);\n if (parentId !== -1 && nextId !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts\n .map((text) => ({\n id: this.mirror.getId(text.node),\n value: text.value,\n }))\n .filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes\n .map((attribute) => ({\n id: this.mirror.getId(attribute.node),\n attributes: attribute.attributes,\n }))\n .filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds,\n };\n if (!payload.texts.length &&\n !payload.attributes.length &&\n !payload.removes.length &&\n !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.removes = [];\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n };\n this.processMutation = (m) => {\n if (isIgnored(m.target)) {\n return;\n }\n switch (m.type) {\n case 'characterData': {\n const value = m.target.textContent;\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) && value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextSelector, this.maskAllText) && value\n ? this.maskTextFn\n ? this.maskTextFn(value)\n : value.replace(/[\\S]/g, '*')\n : value,\n node: m.target,\n });\n }\n break;\n }\n case 'attributes': {\n const target = m.target;\n let value = target.getAttribute(m.attributeName);\n if (m.attributeName === 'value') {\n value = maskInputValue({\n input: target,\n maskInputSelector: this.maskInputSelector,\n unmaskInputSelector: this.unmaskInputSelector,\n maskInputOptions: this.maskInputOptions,\n tagName: target.tagName,\n type: target.getAttribute('type'),\n value,\n maskInputFn: this.maskInputFn,\n });\n }\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) || value === m.oldValue) {\n return;\n }\n let item = this.attributes.find((a) => a.node === m.target);\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n };\n this.attributes.push(item);\n }\n if (m.attributeName === 'type' &&\n m.target.tagName === 'INPUT' &&\n (m.oldValue || '').toLowerCase() === 'password') {\n m.target.setAttribute('rr_is_password', 'true');\n }\n if (m.attributeName === 'style') {\n const old = this.doc.createElement('span');\n if (m.oldValue) {\n old.setAttribute('style', m.oldValue);\n }\n if (item.attributes.style === undefined ||\n item.attributes.style === null) {\n item.attributes.style = {};\n }\n try {\n const styleObj = item.attributes.style;\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) ||\n newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === '') {\n styleObj[pname] = newValue;\n }\n else {\n styleObj[pname] = [newValue, newPriority];\n }\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === '') {\n styleObj[pname] = false;\n }\n }\n }\n catch (error) {\n console.warn('[rrweb] Error when parsing update to style attribute:', error);\n }\n }\n else {\n const element = m.target;\n item.attributes[m.attributeName] = transformAttribute(this.doc, element, element.tagName, m.attributeName, value, this.maskAllText, this.unmaskTextSelector, this.maskTextFn);\n }\n break;\n }\n case 'childList': {\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n m.removedNodes.forEach((n) => {\n const nodeId = this.mirror.getId(n);\n const parentId = isShadowRoot(m.target)\n ? this.mirror.getId(m.target.host)\n : this.mirror.getId(m.target);\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector) || isIgnored(n)) {\n return;\n }\n if (this.addedSet.has(n)) {\n deepDelete(this.addedSet, n);\n this.droppedSet.add(n);\n }\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n) &&\n this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n);\n }\n else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) ? true : undefined,\n });\n }\n this.mapRemoves.push(n);\n });\n break;\n }\n }\n };\n this.genAdds = (n, target) => {\n if (target && isBlocked(target, this.blockClass, this.blockSelector, this.unblockSelector)) {\n return;\n }\n if (isINode(n)) {\n if (isIgnored(n)) {\n return;\n }\n this.movedSet.add(n);\n let targetId = null;\n if (target && isINode(target)) {\n targetId = target.__sn.id;\n }\n if (targetId) {\n this.movedMap[moveKey(n.__sn.id, targetId)] = true;\n }\n }\n else {\n this.addedSet.add(n);\n this.droppedSet.delete(n);\n }\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector))\n n.childNodes.forEach((childN) => this.genAdds(childN));\n };\n }\n init(options) {\n [\n 'mutationCb',\n 'blockClass',\n 'blockSelector',\n 'unblockSelector',\n 'maskTextClass',\n 'maskTextSelector',\n 'unmaskTextSelector',\n 'maskInputSelector',\n 'unmaskInputSelector',\n 'inlineStylesheet',\n 'maskAllText',\n 'maskInputOptions',\n 'maskTextFn',\n 'maskInputFn',\n 'recordCanvas',\n 'inlineImages',\n 'slimDOMOptions',\n 'doc',\n 'mirror',\n 'iframeManager',\n 'shadowDomManager',\n 'canvasManager',\n ].forEach((key) => {\n this[key] = options[key];\n });\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.canvasManager.reset();\n }\n}\nfunction deepDelete(addsSet, n) {\n addsSet.delete(n);\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction isParentRemoved(removes, n, mirror) {\n const { parentNode } = n;\n if (!parentNode) {\n return false;\n }\n const parentId = mirror.getId(parentNode);\n if (removes.some((r) => r.id === parentId)) {\n return true;\n }\n return isParentRemoved(removes, parentNode, mirror);\n}\nfunction isAncestorInSet(set, n) {\n const { parentNode } = n;\n if (!parentNode) {\n return false;\n }\n if (set.has(parentNode)) {\n return true;\n }\n return isAncestorInSet(set, parentNode);\n}\n\nconst callbackWrapper = (cb) => {\n const rrwebWrapped = (...rest) => {\n try {\n return cb(...rest);\n }\n catch (error) {\n try {\n error.__rrweb__ = true;\n }\n catch (_a) {\n }\n throw error;\n }\n };\n return rrwebWrapped;\n};\n\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if ('composedPath' in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n }\n else if ('path' in event && event.path.length) {\n return event.path[0];\n }\n }\n catch (_a) { }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n var _a, _b;\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n let mutationObserverCtor = window.MutationObserver ||\n window.__rrMutationObserver;\n const angularZoneSymbol = (_b = (_a = window === null || window === void 0 ? void 0 : window.Zone) === null || _a === void 0 ? void 0 : _a.__symbol__) === null || _b === void 0 ? void 0 : _b.call(_a, 'MutationObserver');\n if (angularZoneSymbol &&\n window[angularZoneSymbol]) {\n mutationObserverCtor = window[angularZoneSymbol];\n }\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\n if (options.onMutation && options.onMutation(mutations) === false) {\n return;\n }\n mutationBuffer.processMutations(mutations);\n }));\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n });\n return observer;\n}\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\n if (sampling.mousemove === false) {\n return () => { };\n }\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\n ? sampling.mousemoveCallback\n : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle((source) => {\n const totalOffset = Date.now() - timeBaseline;\n callbackWrapper(mousemoveCb)(positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }), source);\n positions = [];\n timeBaseline = null;\n }, callbackThreshold);\n const updatePosition = throttle((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = isTouchEvent(evt)\n ? evt.changedTouches[0]\n : evt;\n if (!timeBaseline) {\n timeBaseline = Date.now();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror.getId(target),\n timeOffset: Date.now() - timeBaseline,\n });\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\n ? IncrementalSource.Drag\n : evt instanceof MouseEvent\n ? IncrementalSource.MouseMove\n : IncrementalSource.TouchMove);\n }, threshold, {\n trailing: false,\n });\n const handlers = [\n on('mousemove', callbackWrapper(updatePosition), doc),\n on('touchmove', callbackWrapper(updatePosition), doc),\n on('drag', callbackWrapper(updatePosition), doc),\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n if (sampling.mouseInteraction === false) {\n return () => { };\n }\n const disableMap = sampling.mouseInteraction === true ||\n sampling.mouseInteraction === undefined\n ? {}\n : sampling.mouseInteraction;\n const handlers = [];\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const e = isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n const id = mirror.getId(target);\n const { clientX, clientY } = e;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[eventKey],\n id,\n x: clientX,\n y: clientY,\n });\n };\n };\n Object.keys(MouseInteractions)\n .filter((key) => Number.isNaN(Number(key)) &&\n !key.endsWith('_Departed') &&\n disableMap[key] !== false)\n .forEach((eventKey) => {\n const eventName = eventKey.toLowerCase();\n const handler = callbackWrapper(getHandler(eventKey));\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n const updatePosition = throttle((evt) => {\n const target = getEventTarget(evt);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const id = mirror.getId(target);\n if (target === doc) {\n const scrollEl = (doc.scrollingElement || doc.documentElement);\n callbackWrapper(scrollCb)({\n id,\n x: scrollEl.scrollLeft,\n y: scrollEl.scrollTop,\n });\n }\n else {\n callbackWrapper(scrollCb)({\n id,\n x: target.scrollLeft,\n y: target.scrollTop,\n });\n }\n }, sampling.scroll || 100);\n return on('scroll', callbackWrapper(updatePosition), doc);\n}\nfunction initViewportResizeObserver({ viewportResizeCb, }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = throttle(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n callbackWrapper(viewportResizeCb)({\n width: Number(width),\n height: Number(height),\n });\n lastH = height;\n lastW = width;\n }\n }, 200);\n return on('resize', callbackWrapper(updateDimension), window);\n}\nfunction wrapEventWithUserTriggeredFlag(v, enable) {\n const value = Object.assign({}, v);\n if (!enable)\n delete value.userTriggered;\n return value;\n}\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\nconst lastInputValueMap = new WeakMap();\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputSelector, unmaskInputSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, }) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const tagName = target && target.tagName;\n const userTriggered = event.isTrusted;\n if (tagName === 'OPTION')\n target = target.parentElement;\n if (!target ||\n !tagName ||\n INPUT_TAGS.indexOf(tagName) < 0 ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n let type = target.type;\n if (target.classList.contains(ignoreClass) ||\n (ignoreSelector && target.matches(ignoreSelector))) {\n return;\n }\n let text = target.value;\n let isChecked = false;\n if (target.hasAttribute('rr_is_password')) {\n type = 'password';\n }\n if (type === 'radio' || type === 'checkbox') {\n isChecked = target.checked;\n }\n else if (hasInputMaskOptions({\n maskInputOptions,\n maskInputSelector,\n tagName,\n type,\n })) {\n text = maskInputValue({\n input: target,\n maskInputOptions,\n maskInputSelector,\n unmaskInputSelector,\n tagName,\n type,\n value: text,\n maskInputFn,\n });\n }\n cbWithDedup(target, callbackWrapper(wrapEventWithUserTriggeredFlag)({ text, isChecked, userTriggered }, userTriggeredOnInput));\n const name = target.name;\n if (type === 'radio' && name && isChecked) {\n doc\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\n .forEach((el) => {\n if (el !== target) {\n cbWithDedup(el, callbackWrapper(wrapEventWithUserTriggeredFlag)({\n text: el.value,\n isChecked: !isChecked,\n userTriggered: false,\n }, userTriggeredOnInput));\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue ||\n lastInputValue.text !== v.text ||\n lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n const id = mirror.getId(target);\n inputCb(Object.assign(Object.assign({}, v), { id }));\n }\n }\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\n const propertyDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');\n const hookProperties = [\n [HTMLInputElement.prototype, 'value'],\n [HTMLInputElement.prototype, 'checked'],\n [HTMLSelectElement.prototype, 'value'],\n [HTMLTextAreaElement.prototype, 'value'],\n [HTMLSelectElement.prototype, 'selectedIndex'],\n [HTMLOptionElement.prototype, 'selected'],\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\n set() {\n callbackWrapper(eventHandler)({ target: this });\n },\n })));\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if ((hasNestedCSSRule('CSSGroupingRule') &&\n childRule.parentRule instanceof CSSGroupingRule) ||\n (hasNestedCSSRule('CSSMediaRule') &&\n childRule.parentRule instanceof CSSMediaRule) ||\n (hasNestedCSSRule('CSSSupportsRule') &&\n childRule.parentRule instanceof CSSSupportsRule) ||\n (hasNestedCSSRule('CSSConditionRule') &&\n childRule.parentRule instanceof CSSConditionRule)) {\n const rules = Array.from(childRule.parentRule.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n else {\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => { };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const id = mirror.getId(thisArg.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n adds: [{ rule, index }],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const id = mirror.getId(thisArg.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n removes: [{ index }],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n }\n else {\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n insertRule: type.prototype.insertRule,\n deleteRule: type.prototype.deleteRule,\n };\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const id = mirror.getId(thisArg.parentStyleSheet.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index || 0,\n ],\n },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const id = mirror.getId(thisArg.parentStyleSheet.ownerNode);\n if (id !== -1) {\n styleSheetRuleCb({\n id,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index] },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror }, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n var _a, _b;\n const [property, value, priority] = argumentsList;\n const id = mirror.getId((_b = (_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet) === null || _b === void 0 ? void 0 : _b.ownerNode);\n if (id !== -1) {\n styleDeclarationCb({\n id,\n set: {\n property,\n value,\n priority,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n var _a, _b;\n const [property] = argumentsList;\n const id = mirror.getId((_b = (_a = thisArg.parentRule) === null || _a === void 0 ? void 0 : _a.parentStyleSheet) === null || _b === void 0 ? void 0 : _b.ownerNode);\n if (id !== -1) {\n styleDeclarationCb({\n id,\n remove: {\n property,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, }) {\n const handler = (type) => throttle(callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector)) {\n return;\n }\n const { currentTime, volume, muted } = target;\n mediaInteractionCb({\n type,\n id: mirror.getId(target),\n currentTime,\n volume,\n muted,\n });\n }), sampling.media || 500);\n const handlers = [\n on('play', handler(0)),\n on('pause', handler(1)),\n on('seeked', handler(2)),\n on('volumechange', handler(3)),\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => { };\n }\n const handlers = [];\n const fontMap = new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace(family, source, descriptors) {\n const fontFace = new originalFontFace(family, source, descriptors);\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== 'string',\n descriptors,\n fontSource: typeof source === 'string'\n ? source\n :\n JSON.stringify(Array.from(new Uint8Array(source))),\n });\n return fontFace;\n };\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\n return function (fontFace) {\n setTimeout(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }, 0);\n return original.apply(this, [fontFace]);\n };\n });\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction mergeHooks(o, hooks) {\n const { mutationCb, mousemoveCb, mouseInteractionCb, scrollCb, viewportResizeCb, inputCb, mediaInteractionCb, styleSheetRuleCb, styleDeclarationCb, canvasMutationCb, fontCb, } = o;\n o.mutationCb = (...p) => {\n if (hooks.mutation) {\n hooks.mutation(...p);\n }\n mutationCb(...p);\n };\n o.mousemoveCb = (...p) => {\n if (hooks.mousemove) {\n hooks.mousemove(...p);\n }\n mousemoveCb(...p);\n };\n o.mouseInteractionCb = (...p) => {\n if (hooks.mouseInteraction) {\n hooks.mouseInteraction(...p);\n }\n mouseInteractionCb(...p);\n };\n o.scrollCb = (...p) => {\n if (hooks.scroll) {\n hooks.scroll(...p);\n }\n scrollCb(...p);\n };\n o.viewportResizeCb = (...p) => {\n if (hooks.viewportResize) {\n hooks.viewportResize(...p);\n }\n viewportResizeCb(...p);\n };\n o.inputCb = (...p) => {\n if (hooks.input) {\n hooks.input(...p);\n }\n inputCb(...p);\n };\n o.mediaInteractionCb = (...p) => {\n if (hooks.mediaInteaction) {\n hooks.mediaInteaction(...p);\n }\n mediaInteractionCb(...p);\n };\n o.styleSheetRuleCb = (...p) => {\n if (hooks.styleSheetRule) {\n hooks.styleSheetRule(...p);\n }\n styleSheetRuleCb(...p);\n };\n o.styleDeclarationCb = (...p) => {\n if (hooks.styleDeclaration) {\n hooks.styleDeclaration(...p);\n }\n styleDeclarationCb(...p);\n };\n o.canvasMutationCb = (...p) => {\n if (hooks.canvasMutation) {\n hooks.canvasMutation(...p);\n }\n canvasMutationCb(...p);\n };\n o.fontCb = (...p) => {\n if (hooks.font) {\n hooks.font(...p);\n }\n fontCb(...p);\n };\n}\nfunction initObservers(o, hooks = {}) {\n const currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return () => { };\n }\n mergeHooks(o, hooks);\n const mutationObserver = initMutationObserver(o, o.doc);\n const mousemoveHandler = initMoveObserver(o);\n const mouseInteractionHandler = initMouseInteractionObserver(o);\n const scrollHandler = initScrollObserver(o);\n const viewportResizeHandler = initViewportResizeObserver(o);\n const inputHandler = initInputObserver(o);\n const mediaInteractionHandler = initMediaInteractionObserver(o);\n const styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n const styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow,\n });\n const fontObserver = o.collectFonts ? initFontObserver(o) : () => { };\n const pluginHandlers = [];\n for (const plugin of o.plugins) {\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\n }\n return callbackWrapper(() => {\n mutationBuffers.forEach((b) => b.reset());\n mutationObserver.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n try {\n styleSheetObserver();\n styleDeclarationObserver();\n }\n catch (e) {\n }\n fontObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== 'undefined';\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(typeof window[prop] !== 'undefined' &&\n window[prop].prototype &&\n 'insertRule' in window[prop].prototype &&\n 'deleteRule' in window[prop].prototype);\n}\n\nclass IframeManager {\n constructor(options) {\n this.iframes = new WeakMap();\n this.mutationCb = options.mutationCb;\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n attachIframe(iframeEl, childSn) {\n var _a;\n this.mutationCb({\n adds: [\n {\n parentId: iframeEl.__sn.id,\n nextId: null,\n node: childSn,\n },\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true,\n });\n (_a = this.loadListener) === null || _a === void 0 ? void 0 : _a.call(this, iframeEl);\n }\n}\n\nclass ShadowDomManager {\n constructor(options) {\n this.restorePatches = [];\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n const manager = this;\n this.restorePatches.push(patch(HTMLElement.prototype, 'attachShadow', function (original) {\n return function () {\n const shadowRoot = original.apply(this, arguments);\n if (this.shadowRoot)\n manager.addShadowRoot(this.shadowRoot, this.ownerDocument);\n return shadowRoot;\n };\n }));\n }\n addShadowRoot(shadowRoot, doc) {\n initMutationObserver(Object.assign(Object.assign({}, this.bypassOptions), { doc, mutationCb: this.mutationCb, mirror: this.mirror, shadowDomManager: this }), shadowRoot);\n initScrollObserver(Object.assign(Object.assign({}, this.bypassOptions), { scrollCb: this.scrollCb, doc: shadowRoot, mirror: this.mirror }));\n }\n observeAttachShadow(iframeElement) {\n if (iframeElement.contentWindow) {\n const manager = this;\n this.restorePatches.push(patch(iframeElement.contentWindow.HTMLElement.prototype, 'attachShadow', function (original) {\n return function () {\n const shadowRoot = original.apply(this, arguments);\n if (this.shadowRoot)\n manager.addShadowRoot(this.shadowRoot, iframeElement.contentDocument);\n return shadowRoot;\n };\n }));\n }\n }\n reset() {\n this.restorePatches.forEach((restorePatch) => restorePatch());\n }\n}\n\n/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n\nfunction __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nfunction initCanvas2DMutationObserver(cb, win, blockClass, unblockSelector, blockSelector, mirror) {\n const handlers = [];\n const props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);\n for (const prop of props2D) {\n try {\n if (typeof win.CanvasRenderingContext2D.prototype[prop] !== 'function') {\n continue;\n }\n const restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function (original) {\n return function (...args) {\n if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector)) {\n setTimeout(() => {\n const recordArgs = [...args];\n if (prop === 'drawImage') {\n if (recordArgs[0] &&\n recordArgs[0] instanceof HTMLCanvasElement) {\n const canvas = recordArgs[0];\n const ctx = canvas.getContext('2d');\n let imgd = ctx === null || ctx === void 0 ? void 0 : ctx.getImageData(0, 0, canvas.width, canvas.height);\n let pix = imgd === null || imgd === void 0 ? void 0 : imgd.data;\n recordArgs[0] = JSON.stringify(pix);\n }\n }\n cb(this.canvas, {\n type: CanvasContext['2D'],\n property: prop,\n args: recordArgs,\n });\n }, 0);\n }\n return original.apply(this, args);\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n const hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type: CanvasContext['2D'],\n property: prop,\n args: [v],\n setter: true,\n });\n },\n });\n handlers.push(hookHandler);\n }\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\nfunction initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector) {\n const handlers = [];\n try {\n const restoreHandler = patch(win.HTMLCanvasElement.prototype, 'getContext', function (original) {\n return function (contextType, ...args) {\n if (!isBlocked(this, blockClass, blockSelector, unblockSelector)) {\n if (!('__context' in this))\n this.__context = contextType;\n }\n return original.apply(this, [contextType, ...args]);\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n console.error('failed to patch HTMLCanvasElement.prototype.getContext');\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\n/*\n * base64-arraybuffer 1.0.2 \n * Copyright (c) 2022 Niklas von Hertzen \n * Released under MIT License\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n// Use a lookup table to find the index.\nvar lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\nvar encode = function (arraybuffer) {\n var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n }\n else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n return base64;\n};\n\nconst webGLVarMap = new Map();\nfunction variableListFor(ctx, ctor) {\n let contextMap = webGLVarMap.get(ctx);\n if (!contextMap) {\n contextMap = new Map();\n webGLVarMap.set(ctx, contextMap);\n }\n if (!contextMap.has(ctor)) {\n contextMap.set(ctor, []);\n }\n return contextMap.get(ctor);\n}\nconst saveWebGLVar = (value, win, ctx) => {\n if (!value ||\n !(isInstanceOfWebGLObject(value, win) || typeof value === 'object'))\n return;\n const name = value.constructor.name;\n const list = variableListFor(ctx, name);\n let index = list.indexOf(value);\n if (index === -1) {\n index = list.length;\n list.push(value);\n }\n return index;\n};\nfunction serializeArg(value, win, ctx) {\n if (value instanceof Array) {\n return value.map((arg) => serializeArg(arg, win, ctx));\n }\n else if (value === null) {\n return value;\n }\n else if (value instanceof Float32Array ||\n value instanceof Float64Array ||\n value instanceof Int32Array ||\n value instanceof Uint32Array ||\n value instanceof Uint8Array ||\n value instanceof Uint16Array ||\n value instanceof Int16Array ||\n value instanceof Int8Array ||\n value instanceof Uint8ClampedArray) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [Object.values(value)],\n };\n }\n else if (value instanceof ArrayBuffer) {\n const name = value.constructor.name;\n const base64 = encode(value);\n return {\n rr_type: name,\n base64,\n };\n }\n else if (value instanceof DataView) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [\n serializeArg(value.buffer, win, ctx),\n value.byteOffset,\n value.byteLength,\n ],\n };\n }\n else if (value instanceof HTMLImageElement) {\n const name = value.constructor.name;\n const { src } = value;\n return {\n rr_type: name,\n src,\n };\n }\n else if (value instanceof ImageData) {\n const name = value.constructor.name;\n return {\n rr_type: name,\n args: [serializeArg(value.data, win, ctx), value.width, value.height],\n };\n }\n else if (isInstanceOfWebGLObject(value, win) || typeof value === 'object') {\n const name = value.constructor.name;\n const index = saveWebGLVar(value, win, ctx);\n return {\n rr_type: name,\n index: index,\n };\n }\n return value;\n}\nconst serializeArgs = (args, win, ctx) => {\n return [...args].map((arg) => serializeArg(arg, win, ctx));\n};\nconst isInstanceOfWebGLObject = (value, win) => {\n const webGLConstructorNames = [\n 'WebGLActiveInfo',\n 'WebGLBuffer',\n 'WebGLFramebuffer',\n 'WebGLProgram',\n 'WebGLRenderbuffer',\n 'WebGLShader',\n 'WebGLShaderPrecisionFormat',\n 'WebGLTexture',\n 'WebGLUniformLocation',\n 'WebGLVertexArrayObject',\n 'WebGLVertexArrayObjectOES',\n ];\n const supportedWebGLConstructorNames = webGLConstructorNames.filter((name) => typeof win[name] === 'function');\n return Boolean(supportedWebGLConstructorNames.find((name) => value instanceof win[name]));\n};\n\nfunction patchGLPrototype(prototype, type, cb, blockClass, unblockSelector, blockSelector, mirror, win) {\n const handlers = [];\n const props = Object.getOwnPropertyNames(prototype);\n for (const prop of props) {\n try {\n if (typeof prototype[prop] !== 'function') {\n continue;\n }\n const restoreHandler = patch(prototype, prop, function (original) {\n return function (...args) {\n const result = original.apply(this, args);\n saveWebGLVar(result, win, prototype);\n if (!isBlocked(this.canvas, blockClass, blockSelector, unblockSelector)) {\n const id = mirror.getId(this.canvas);\n const recordArgs = serializeArgs([...args], win, prototype);\n const mutation = {\n type,\n property: prop,\n args: recordArgs,\n };\n cb(this.canvas, mutation);\n }\n return result;\n };\n });\n handlers.push(restoreHandler);\n }\n catch (_a) {\n const hookHandler = hookSetter(prototype, prop, {\n set(v) {\n cb(this.canvas, {\n type,\n property: prop,\n args: [v],\n setter: true,\n });\n },\n });\n handlers.push(hookHandler);\n }\n }\n return handlers;\n}\nfunction initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector, unblockSelector, mirror) {\n const handlers = [];\n handlers.push(...patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, unblockSelector, mirror, win));\n if (typeof win.WebGL2RenderingContext !== 'undefined') {\n handlers.push(...patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, unblockSelector, mirror, win));\n }\n return () => {\n handlers.forEach((h) => h());\n };\n}\n\nclass CanvasManager {\n reset() {\n this.pendingCanvasMutations.clear();\n this.resetObservers && this.resetObservers();\n }\n freeze() {\n this.frozen = true;\n }\n unfreeze() {\n this.frozen = false;\n }\n lock() {\n this.locked = true;\n }\n unlock() {\n this.locked = false;\n }\n constructor(options) {\n this.pendingCanvasMutations = new Map();\n this.rafStamps = { latestId: 0, invokeId: null };\n this.frozen = false;\n this.locked = false;\n this.processMutation = function (target, mutation) {\n const newFrame = this.rafStamps.invokeId &&\n this.rafStamps.latestId !== this.rafStamps.invokeId;\n if (newFrame || !this.rafStamps.invokeId)\n this.rafStamps.invokeId = this.rafStamps.latestId;\n if (!this.pendingCanvasMutations.has(target)) {\n this.pendingCanvasMutations.set(target, []);\n }\n this.pendingCanvasMutations.get(target).push(mutation);\n };\n this.mutationCb = options.mutationCb;\n this.mirror = options.mirror;\n if (options.recordCanvas === true)\n this.initCanvasMutationObserver(options.win, options.blockClass, options.blockSelector, options.unblockSelector);\n }\n initCanvasMutationObserver(win, blockClass, unblockSelector, blockSelector) {\n this.startRAFTimestamping();\n this.startPendingCanvasMutationFlusher();\n const canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, unblockSelector);\n const canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\n const canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector, unblockSelector, this.mirror);\n this.resetObservers = () => {\n canvasContextReset();\n canvas2DReset();\n canvasWebGL1and2Reset();\n };\n }\n startPendingCanvasMutationFlusher() {\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n startRAFTimestamping() {\n const setLatestRAFTimestamp = (timestamp) => {\n this.rafStamps.latestId = timestamp;\n requestAnimationFrame(setLatestRAFTimestamp);\n };\n requestAnimationFrame(setLatestRAFTimestamp);\n }\n flushPendingCanvasMutations() {\n this.pendingCanvasMutations.forEach((values, canvas) => {\n const id = this.mirror.getId(canvas);\n this.flushPendingCanvasMutationFor(canvas, id);\n });\n requestAnimationFrame(() => this.flushPendingCanvasMutations());\n }\n flushPendingCanvasMutationFor(canvas, id) {\n if (this.frozen || this.locked) {\n return;\n }\n const valuesWithType = this.pendingCanvasMutations.get(canvas);\n if (!valuesWithType || id === -1)\n return;\n const values = valuesWithType.map((value) => {\n const rest = __rest(value, [\"type\"]);\n return rest;\n });\n const { type } = valuesWithType[0];\n this.mutationCb({ id, type, commands: values });\n this.pendingCanvasMutations.delete(canvas);\n }\n}\n\nfunction wrapEvent(e) {\n return Object.assign(Object.assign({}, e), { timestamp: Date.now() });\n}\nlet wrappedEmit;\nlet takeFullSnapshot;\nconst mirror = createMirror();\nfunction record(options = {}) {\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskTextClass = 'rr-mask', maskTextSelector = null, maskInputSelector = null, unmaskTextSelector = null, unmaskInputSelector = null, inlineStylesheet = true, maskAllText = false, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskInputFn, maskTextFn, hooks, packFn, sampling = {}, mousemoveWait, recordCanvas = false, userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, onMutation, } = options;\n if (!emit) {\n throw new Error('emit function is required');\n }\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\n sampling.mousemove = mousemoveWait;\n }\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n radio: true,\n checkbox: true,\n }\n : _maskInputOptions !== undefined\n ? _maskInputOptions\n : {};\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\n ? {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n headMetaAuthorship: _slimDOMOptions === 'all',\n headMetaDescKeywords: _slimDOMOptions === 'all',\n }\n : _slimDOMOptions\n ? _slimDOMOptions\n : {};\n polyfill();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const eventProcessor = (e) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n if (packFn) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = (e, isCheckout) => {\n var _a;\n if (((_a = mutationBuffers[0]) === null || _a === void 0 ? void 0 : _a.isFrozen()) &&\n e.type !== EventType.FullSnapshot &&\n !(e.type === EventType.IncrementalSnapshot &&\n e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n emit(eventProcessor(e), isCheckout);\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n }\n else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation &&\n e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms &&\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\n const wrappedMutationEmit = (m) => {\n wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Mutation }, m),\n }));\n };\n const wrappedScrollEmit = (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Scroll }, p),\n }));\n const wrappedCanvasMutationEmit = (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.CanvasMutation }, p),\n }));\n const iframeManager = new IframeManager({\n mutationCb: wrappedMutationEmit,\n });\n const canvasManager = new CanvasManager({\n recordCanvas,\n mutationCb: wrappedCanvasMutationEmit,\n win: window,\n blockClass,\n blockSelector,\n unblockSelector,\n mirror,\n });\n const shadowDomManager = new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n onMutation,\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n inlineStylesheet,\n maskAllText,\n maskInputOptions,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n canvasManager,\n },\n mirror,\n });\n takeFullSnapshot = (isCheckout = false) => {\n var _a, _b, _c, _d;\n wrappedEmit(wrapEvent({\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight(),\n },\n }), isCheckout);\n mutationBuffers.forEach((buf) => buf.lock());\n const [node, idNodeMap] = snapshot(document, {\n blockClass,\n blockSelector,\n unblockSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n inlineStylesheet,\n maskAllText,\n maskAllInputs: maskInputOptions,\n maskTextFn,\n slimDOM: slimDOMOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n) => {\n if (isIframeINode(n)) {\n iframeManager.addIframe(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n shadowDomManager.observeAttachShadow(iframe);\n },\n keepIframeSrcFn,\n });\n if (!node) {\n return console.warn('Failed to snapshot the document');\n }\n mirror.map = idNodeMap;\n wrappedEmit(wrapEvent({\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: {\n left: window.pageXOffset !== undefined\n ? window.pageXOffset\n : (document === null || document === void 0 ? void 0 : document.documentElement.scrollLeft) ||\n ((_b = (_a = document === null || document === void 0 ? void 0 : document.body) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.scrollLeft) ||\n (document === null || document === void 0 ? void 0 : document.body.scrollLeft) ||\n 0,\n top: window.pageYOffset !== undefined\n ? window.pageYOffset\n : (document === null || document === void 0 ? void 0 : document.documentElement.scrollTop) ||\n ((_d = (_c = document === null || document === void 0 ? void 0 : document.body) === null || _c === void 0 ? void 0 : _c.parentElement) === null || _d === void 0 ? void 0 : _d.scrollTop) ||\n (document === null || document === void 0 ? void 0 : document.body.scrollTop) ||\n 0,\n },\n },\n }));\n mutationBuffers.forEach((buf) => buf.unlock());\n };\n try {\n const handlers = [];\n handlers.push(on('DOMContentLoaded', () => {\n wrappedEmit(wrapEvent({\n type: EventType.DomContentLoaded,\n data: {},\n }));\n }));\n const observe = (doc) => {\n var _a;\n return callbackWrapper(initObservers)({\n onMutation,\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions,\n },\n })),\n mouseInteractionCb: (d) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.MouseInteraction }, d),\n })),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.ViewportResize }, d),\n })),\n inputCb: (v) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Input }, v),\n })),\n mediaInteractionCb: (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.MediaInteraction }, p),\n })),\n styleSheetRuleCb: (r) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.StyleSheetRule }, r),\n })),\n styleDeclarationCb: (r) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.StyleDeclaration }, r),\n })),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit(wrapEvent({\n type: EventType.IncrementalSnapshot,\n data: Object.assign({ source: IncrementalSource.Font }, p),\n })),\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputSelector,\n unmaskInputSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskAllText,\n maskInputFn,\n maskTextFn,\n blockSelector,\n unblockSelector,\n slimDOMOptions,\n mirror,\n iframeManager,\n shadowDomManager,\n canvasManager,\n plugins: ((_a = plugins === null || plugins === void 0 ? void 0 : plugins.filter((p) => p.observer)) === null || _a === void 0 ? void 0 : _a.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit(wrapEvent({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload,\n },\n })),\n }))) || [],\n }, hooks);\n };\n iframeManager.addLoadListener((iframeEl) => {\n try {\n handlers.push(observe(iframeEl.contentDocument));\n }\n catch (error) {\n console.warn(error);\n }\n });\n const init = () => {\n takeFullSnapshot();\n handlers.push(observe(document));\n };\n if (document.readyState === 'interactive' ||\n document.readyState === 'complete') {\n init();\n }\n else {\n handlers.push(on('load', () => {\n wrappedEmit(wrapEvent({\n type: EventType.Load,\n data: {},\n }));\n init();\n }, window));\n }\n return () => {\n handlers.forEach((h) => h());\n };\n }\n catch (error) {\n console.warn(error);\n }\n}\nrecord.addCustomEvent = (tag, payload) => {\n if (!wrappedEmit) {\n throw new Error('please add custom event after start recording');\n }\n wrappedEmit(wrapEvent({\n type: EventType.Custom,\n data: {\n tag,\n payload,\n },\n }));\n};\nrecord.freezePage = () => {\n mutationBuffers.forEach((buf) => buf.freeze());\n};\nrecord.takeFullSnapshot = (isCheckout) => {\n if (!takeFullSnapshot) {\n throw new Error('please take full snapshot after start recording');\n }\n takeFullSnapshot(isCheckout);\n};\nrecord.mirror = mirror;\n\nconst NAVIGATION_ENTRY_KEYS = [\n 'name',\n 'type',\n 'startTime',\n 'transferSize',\n 'duration',\n];\n\nfunction isNavigationEntryEqual(a) {\n return function (b) {\n return NAVIGATION_ENTRY_KEYS.every(key => a[key] === b[key]);\n };\n}\n\n/**\n * There are some difficulties diagnosing why there are duplicate navigation\n * entries. We've witnessed several intermittent results:\n * - duplicate entries have duration = 0\n * - duplicate entries are the same object reference\n * - none of the above\n *\n * Compare the values of several keys to determine if the entries are duplicates or not.\n */\n// TODO (high-prio): Figure out wth is returned here\n// eslint-disable-next-line @typescript-eslint/explicit-function-return-type\nfunction dedupePerformanceEntries(\n currentList,\n newList,\n) {\n // Partition `currentList` into 3 different lists based on entryType\n const [existingNavigationEntries, existingLcpEntries, existingEntries] = currentList.reduce(\n (acc, entry) => {\n if (entry.entryType === 'navigation') {\n acc[0].push(entry );\n } else if (entry.entryType === 'largest-contentful-paint') {\n acc[1].push(entry );\n } else {\n acc[2].push(entry);\n }\n return acc;\n },\n [[], [], []],\n );\n\n const newEntries = [];\n const newNavigationEntries = [];\n let newLcpEntry = existingLcpEntries.length\n ? existingLcpEntries[existingLcpEntries.length - 1] // Take the last element as list is sorted\n : undefined;\n\n newList.forEach(entry => {\n if (entry.entryType === 'largest-contentful-paint') {\n // We want the latest LCP event only\n if (!newLcpEntry || newLcpEntry.startTime < entry.startTime) {\n newLcpEntry = entry;\n }\n return;\n }\n\n if (entry.entryType === 'navigation') {\n const navigationEntry = entry ;\n\n // Check if the navigation entry is contained in currentList or newList\n if (\n // Ignore any navigation entries with duration 0, as they are likely duplicates\n entry.duration > 0 &&\n // Ensure new entry does not already exist in existing entries\n !existingNavigationEntries.find(isNavigationEntryEqual(navigationEntry)) &&\n // Ensure new entry does not already exist in new list of navigation entries\n !newNavigationEntries.find(isNavigationEntryEqual(navigationEntry))\n ) {\n newNavigationEntries.push(navigationEntry);\n }\n\n // Otherwise this navigation entry is considered a duplicate and is thrown away\n return;\n }\n\n newEntries.push(entry);\n });\n\n // Re-combine and sort by startTime\n return [\n ...(newLcpEntry ? [newLcpEntry] : []),\n ...existingNavigationEntries,\n ...existingEntries,\n ...newEntries,\n ...newNavigationEntries,\n ].sort((a, b) => a.startTime - b.startTime);\n}\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n */\nfunction setupPerformanceObserver(replay) {\n const performanceObserverHandler = (list) => {\n // For whatever reason the observer was returning duplicate navigation\n // entries (the other entry types were not duplicated).\n const newPerformanceEntries = dedupePerformanceEntries(\n replay.performanceEvents,\n list.getEntries() ,\n );\n replay.performanceEvents = newPerformanceEntries;\n };\n\n const performanceObserver = new PerformanceObserver(performanceObserverHandler);\n\n [\n 'element',\n 'event',\n 'first-input',\n 'largest-contentful-paint',\n 'layout-shift',\n 'longtask',\n 'navigation',\n 'paint',\n 'resource',\n ].forEach(type => {\n try {\n performanceObserver.observe({\n type,\n buffered: true,\n });\n } catch (e) {\n // This can throw if an entry type is not supported in the browser.\n // Ignore these errors.\n }\n });\n\n return performanceObserver;\n}\n\nconst r = `/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\nfunction t(t){let e=t.length;for(;--e>=0;)t[e]=0}const e=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),a=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),i=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=new Array(576);t(s);const r=new Array(60);t(r);const o=new Array(512);t(o);const l=new Array(256);t(l);const h=new Array(29);t(h);const d=new Array(30);function _(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let f,c,u;function w(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}t(d);const m=t=>t<256?o[t]:o[256+(t>>>7)],b=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},g=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<{g(t,a[2*e],a[2*e+1])},k=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},v=(t,e,a)=>{const i=new Array(16);let n,s,r=0;for(n=1;n<=15;n++)r=r+a[n-1]<<1,i[n]=r;for(s=0;s<=e;s++){let e=t[2*s+1];0!==e&&(t[2*s]=k(i[e]++,e))}},y=t=>{let e;for(e=0;e<286;e++)t.dyn_ltree[2*e]=0;for(e=0;e<30;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},x=t=>{t.bi_valid>8?b(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},z=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n{let s,r,o,_,f=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+f++],s+=(255&t.pending_buf[t.sym_buf+f++])<<8,r=t.pending_buf[t.sym_buf+f++],0===s?p(t,r,i):(o=l[r],p(t,o+256+1,i),_=e[o],0!==_&&(r-=h[o],g(t,r,_)),s--,o=m(s),p(t,o,n),_=a[o],0!==_&&(s-=d[o],g(t,s,_)))}while(f{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,s=e.stat_desc.elems;let r,o,l,h=-1;for(t.heap_len=0,t.heap_max=573,r=0;r>1;r>=1;r--)A(t,a,r);l=s;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],A(t,a,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,a[2*l]=a[2*r]+a[2*o],t.depth[l]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,a[2*r+1]=a[2*o+1]=l,t.heap[1]=l++,A(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length;let h,d,_,f,c,u,w=0;for(f=0;f<=15;f++)t.bl_count[f]=0;for(a[2*t.heap[t.heap_max]+1]=0,h=t.heap_max+1;h<573;h++)d=t.heap[h],f=a[2*a[2*d+1]+1]+1,f>l&&(f=l,w++),a[2*d+1]=f,d>i||(t.bl_count[f]++,c=0,d>=o&&(c=r[d-o]),u=a[2*d],t.opt_len+=u*(f+c),s&&(t.static_len+=u*(n[2*d+1]+c)));if(0!==w){do{for(f=l-1;0===t.bl_count[f];)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[l]--,w-=2}while(w>0);for(f=l;0!==f;f--)for(d=t.bl_count[f];0!==d;)_=t.heap[--h],_>i||(a[2*_+1]!==f&&(t.opt_len+=(f-a[2*_+1])*a[2*_],a[2*_+1]=f),d--)}})(t,e),v(a,h,t.bl_count)},Z=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o{g(t,0+(i?1:0),3),x(t),b(t,a),b(t,~a),a&&t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a};var T=(t,e,a,i)=>{let o,l,h=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,a=4093624447;for(e=0;e<=31;e++,a>>>=1)if(1&a&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<256;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),R(t,t.l_desc),R(t,t.d_desc),h=(t=>{let e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),R(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*n[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),o=t.opt_len+3+7>>>3,l=t.static_len+3+7>>>3,l<=o&&(o=l)):o=l=a+5,a+4<=o&&-1!==e?D(t,e,a,i):4===t.strategy||l===o?(g(t,2+(i?1:0),3),E(t,s,r)):(g(t,4+(i?1:0),3),((t,e,a,i)=>{let s;for(g(t,e-257,5),g(t,a-1,5),g(t,i-4,4),s=0;s{S||((()=>{let t,n,w,m,b;const g=new Array(16);for(w=0,m=0;m<28;m++)for(h[m]=w,t=0;t<1<>=7;m<30;m++)for(d[m]=b<<7,t=0;t<1<(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=a,0===e?t.dyn_ltree[2*a]++:(t.matches++,e--,t.dyn_ltree[2*(l[a]+256+1)]++,t.dyn_dtree[2*m(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{g(t,2,3),p(t,256,s),(t=>{16===t.bi_valid?(b(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var F=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const L=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var N=(t,e,a,i)=>{const n=L,s=i+a;t^=-1;for(let a=i;a>>8^n[255&(t^e[a])];return-1^t},I={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"},B={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:C,_tr_stored_block:H,_tr_flush_block:M,_tr_tally:j,_tr_align:K}=O,{Z_NO_FLUSH:P,Z_PARTIAL_FLUSH:Y,Z_FULL_FLUSH:G,Z_FINISH:X,Z_BLOCK:W,Z_OK:q,Z_STREAM_END:J,Z_STREAM_ERROR:Q,Z_DATA_ERROR:V,Z_BUF_ERROR:$,Z_DEFAULT_COMPRESSION:tt,Z_FILTERED:et,Z_HUFFMAN_ONLY:at,Z_RLE:it,Z_FIXED:nt,Z_DEFAULT_STRATEGY:st,Z_UNKNOWN:rt,Z_DEFLATED:ot}=B,lt=(t,e)=>(t.msg=I[e],e),ht=t=>2*t-(t>4?9:0),dt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_t=t=>{let e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0}while(--e)};let ft=(t,e,a)=>(e<{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},ut=(t,e)=>{M(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ct(t.strm)},wt=(t,e)=>{t.pending_buf[t.pending++]=e},mt=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},bt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=F(t.adler,e,n,a):2===t.state.wrap&&(t.adler=N(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},gt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-262?t.strstart-(t.w_size-262):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+258;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&sr){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},pt=t=>{const e=t.w_size;let a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-262)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_t(t),i+=e),0===t.strm.avail_in)break;if(a=bt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=ft(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=ft(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<262&&0!==t.strm.avail_in)},kt=(t,e)=>{let a,i,n,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_outi+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,ct(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(bt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a)}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_watern&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(bt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===X)&&e!==P&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===X&&0===t.strm.avail_in&&a===i?1:0,H(t,t.block_start,a,r),t.block_start+=a,ct(t.strm)),r?3:1)},vt=(t,e)=>{let a,i;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-262&&(t.match_length=gt(t,a)),t.match_length>=3)if(i=j(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ft(t,t.ins_h,t.window[t.strstart+1]);else i=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2},yt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<262){if(pt(t),t.lookahead<262&&e===P)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=j(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=ft(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(ut(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=j(t,0,t.window[t.strstart-1]),i&&ut(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=j(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2};function xt(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const zt=[new xt(0,0,0,0,kt),new xt(4,4,8,4,vt),new xt(4,5,16,8,vt),new xt(4,6,32,32,vt),new xt(4,4,16,16,yt),new xt(8,16,32,32,yt),new xt(8,16,128,128,yt),new xt(8,32,128,256,yt),new xt(32,128,258,1024,yt),new xt(32,258,258,4096,yt)];function At(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ot,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Et=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||42!==e.status&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&113!==e.status&&666!==e.status?1:0},Rt=t=>{if(Et(t))return lt(t,Q);t.total_in=t.total_out=0,t.data_type=rt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?42:113,t.adler=2===e.wrap?0:1,e.last_flush=-2,C(e),q},Zt=t=>{const e=Rt(t);var a;return e===q&&((a=t.state).window_size=2*a.w_size,dt(a.head),a.max_lazy_match=zt[a.level].max_lazy,a.good_match=zt[a.level].good_length,a.nice_match=zt[a.level].nice_length,a.max_chain_length=zt[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},Ut=(t,e,a,i,n,s)=>{if(!t)return Q;let r=1;if(e===tt&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ot||i<8||i>15||e<0||e>9||s<0||s>nt||8===i&&1!==r)return lt(t,Q);8===i&&(i=9);const o=new At;return t.state=o,o.strm=t,o.status=42,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<Ut(t,e,ot,15,8,st),deflateInit2:Ut,deflateReset:Zt,deflateResetKeep:Rt,deflateSetHeader:(t,e)=>Et(t)||2!==t.state.wrap?Q:(t.state.gzhead=e,q),deflate:(t,e)=>{if(Et(t)||e>W||e<0)return t?lt(t,Q):Q;const a=t.state;if(!t.output||0!==t.avail_in&&!t.input||666===a.status&&e!==X)return lt(t,0===t.avail_out?$:Q);const i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(ct(t),0===t.avail_out)return a.last_flush=-1,q}else if(0===t.avail_in&&ht(e)<=ht(i)&&e!==X)return lt(t,$);if(666===a.status&&0!==t.avail_in)return lt(t,$);if(42===a.status&&0===a.wrap&&(a.status=113),42===a.status){let e=ot+(a.w_bits-8<<4)<<8,i=-1;if(i=a.strategy>=at||a.level<2?0:a.level<6?1:6===a.level?2:3,e|=i<<6,0!==a.strstart&&(e|=32),e+=31-e%31,mt(a,e),0!==a.strstart&&(mt(a,t.adler>>>16),mt(a,65535&t.adler)),t.adler=1,a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(57===a.status)if(t.adler=0,wt(a,31),wt(a,139),wt(a,8),a.gzhead)wt(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),wt(a,255&a.gzhead.time),wt(a,a.gzhead.time>>8&255),wt(a,a.gzhead.time>>16&255),wt(a,a.gzhead.time>>24&255),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(wt(a,255&a.gzhead.extra.length),wt(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=N(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,0),wt(a,9===a.level?2:a.strategy>=at||a.level<2?4:0),wt(a,3),a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q;if(69===a.status){if(a.gzhead.extra){let e=a.pending,i=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+i>a.pending_buf_size;){let n=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+n),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex+=n,ct(t),0!==a.pending)return a.last_flush=-1,q;e=0,i-=n}let n=new Uint8Array(a.gzhead.extra);a.pending_buf.set(n.subarray(a.gzindex,a.gzindex+i),a.pending),a.pending+=i,a.gzhead.hcrc&&a.pending>e&&(t.adler=N(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex=0}a.status=73}if(73===a.status){if(a.gzhead.name){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),a.gzindex=0}a.status=91}if(91===a.status){if(a.gzhead.comment){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i)),ct(t),0!==a.pending)return a.last_flush=-1,q;i=0}e=a.gzindexi&&(t.adler=N(t.adler,a.pending_buf,a.pending-i,i))}a.status=103}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(ct(t),0!==a.pending))return a.last_flush=-1,q;wt(a,255&t.adler),wt(a,t.adler>>8&255),t.adler=0}if(a.status=113,ct(t),0!==a.pending)return a.last_flush=-1,q}if(0!==t.avail_in||0!==a.lookahead||e!==P&&666!==a.status){let i=0===a.level?kt(a,e):a.strategy===at?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(pt(t),0===t.lookahead)){if(e===P)return 1;break}if(t.match_length=0,a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):a.strategy===it?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=258){if(pt(t),t.lookahead<=258&&e===P)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+258;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=j(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=j(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(ut(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===X?(ut(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ut(t,!1),0===t.strm.avail_out)?1:2})(a,e):zt[a.level].func(a,e);if(3!==i&&4!==i||(a.status=666),1===i||3===i)return 0===t.avail_out&&(a.last_flush=-1),q;if(2===i&&(e===Y?K(a):e!==W&&(H(a,0,0,!1),e===G&&(dt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),ct(t),0===t.avail_out))return a.last_flush=-1,q}return e!==X?q:a.wrap<=0?J:(2===a.wrap?(wt(a,255&t.adler),wt(a,t.adler>>8&255),wt(a,t.adler>>16&255),wt(a,t.adler>>24&255),wt(a,255&t.total_in),wt(a,t.total_in>>8&255),wt(a,t.total_in>>16&255),wt(a,t.total_in>>24&255)):(mt(a,t.adler>>>16),mt(a,65535&t.adler)),ct(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?q:J)},deflateEnd:t=>{if(Et(t))return Q;const e=t.state.status;return t.state=null,113===e?lt(t,V):q},deflateSetDictionary:(t,e)=>{let a=e.length;if(Et(t))return Q;const i=t.state,n=i.wrap;if(2===n||1===n&&42!==i.status||i.lookahead)return Q;if(1===n&&(t.adler=F(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(dt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,pt(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=ft(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,pt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,q},deflateInfo:\"pako deflate (from Nodeca project)\"};const Dt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Tt=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if(\"object\"!=typeof a)throw new TypeError(a+\"must be non-object\");for(const e in a)Dt(a,e)&&(t[e]=a[e])}}return t},Ot=t=>{let e=0;for(let a=0,i=t.length;a=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Lt[254]=Lt[254]=1;var Nt=t=>{if(\"function\"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},It=(t,e)=>{const a=e||t.length;if(\"function\"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Ft)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a=\"\";for(let i=0;i{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Lt[t[a]]>e?a:e};var Ct=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0};const Ht=Object.prototype.toString,{Z_NO_FLUSH:Mt,Z_SYNC_FLUSH:jt,Z_FULL_FLUSH:Kt,Z_FINISH:Pt,Z_OK:Yt,Z_STREAM_END:Gt,Z_DEFAULT_COMPRESSION:Xt,Z_DEFAULT_STRATEGY:Wt,Z_DEFLATED:qt}=B;function Jt(t){this.options=Tt({level:Xt,method:qt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Wt},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=St.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==Yt)throw new Error(I[a]);if(e.header&&St.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t=\"string\"==typeof e.dictionary?Nt(e.dictionary):\"[object ArrayBuffer]\"===Ht.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=St.deflateSetDictionary(this.strm,t),a!==Yt)throw new Error(I[a]);this._dict_set=!0}}function Qt(t,e){const a=new Jt(e);if(a.push(t,!0),a.err)throw a.msg||I[a.err];return a.result}Jt.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?Pt:Mt,\"string\"==typeof t?a.input=Nt(t):\"[object ArrayBuffer]\"===Ht.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===jt||s===Kt)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=St.deflate(a,s),n===Gt)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=St.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Yt;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},Jt.prototype.onData=function(t){this.chunks.push(t)},Jt.prototype.onEnd=function(t){t===Yt&&(this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Vt={Deflate:Jt,deflate:Qt,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Qt(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Qt(t,e)},constants:B};var $t=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<>>=p,c-=p),c<15&&(f+=z[a++]<>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<o){t.msg=\"invalid distance too far back\",E.mode=16209;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg=\"invalid distance too far back\",E.mode=16209;break t}if(y=0,x=_,0===d){if(y+=l-p,p2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a>3,a-=k,c-=k<<3,f&=(1<{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,U,S,D=null;for(w=0;w<=15;w++)E[w]=0;for(m=0;m=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<15;w++)R[w+1]=R[w]+E[w];for(m=0;m852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<>v)+d]=Z<<24|U<<16|S|0}while(0!==d);for(h=1<>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:se,Z_BLOCK:re,Z_TREES:oe,Z_OK:le,Z_STREAM_END:he,Z_NEED_DICT:de,Z_STREAM_ERROR:_e,Z_DATA_ERROR:fe,Z_MEM_ERROR:ce,Z_BUF_ERROR:ue,Z_DEFLATED:we}=B,me=16209,be=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function ge(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const pe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<16180||e.mode>16211?1:0},ke=t=>{if(pe(t))return _e;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg=\"\",e.wrap&&(t.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,le},ve=t=>{if(pe(t))return _e;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,ke(t)},ye=(t,e)=>{let a;if(pe(t))return _e;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?_e:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,ve(t))},xe=(t,e)=>{if(!t)return _e;const a=new ge;t.state=a,a.strm=t,a.window=null,a.mode=16180;const i=ye(t,e);return i!==le&&(t.state=null),i};let ze,Ae,Ee=!0;const Re=t=>{if(Ee){ze=new Int32Array(512),Ae=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(ne(1,t.lens,0,288,ze,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;ne(2,t.lens,0,32,Ae,0,t.work,{bits:5}),Ee=!1}t.lencode=ze,t.lenbits=9,t.distcode=Ae,t.distbits=5},Ze=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whavexe(t,15),inflateInit2:xe,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pe(t)||!t.output||!t.input&&0!==t.avail_in)return _e;a=t.state,16191===a.mode&&(a.mode=16192),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=le;t:for(;;)switch(a.mode){case 16180:if(0===a.wrap){a.mode=16192;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg=\"incorrect header check\",a.mode=me;break}if((15&h)!==we){t.msg=\"unknown compression method\",a.mode=me;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg=\"invalid window size\",a.mode=me;break}a.dmax=1<>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=N(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=N(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=N(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=16191;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>=7&d,d-=7&d,a.mode=16206;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Re(a),a.mode=16199,e===oe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg=\"invalid block type\",a.mode=me}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<>>16^65535)){t.msg=\"invalid stored block lengths\",a.mode=me;break}if(a.length=65535&h,h=0,d=0,a.mode=16194,e===oe)break t;case 16194:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=16191;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg=\"too many length or distance symbols\",a.mode=me;break}a.have=0,a.mode=16197;case 16197:for(;a.have>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=ne(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid code lengths set\",a.mode=me;break}a.have=0,a.mode=16198;case 16198:for(;a.have>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d>>=m,d-=m,0===a.have){t.msg=\"invalid bit length repeat\",a.mode=me;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg=\"invalid bit length repeat\",a.mode=me;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===me)break;if(0===a.lens[256]){t.msg=\"invalid code -- missing end-of-block\",a.mode=me;break}if(a.lenbits=9,E={bits:a.lenbits},x=ne(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg=\"invalid literal/lengths set\",a.mode=me;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=ne(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg=\"invalid distances set\",a.mode=me;break}if(a.mode=16199,e===oe)break t;case 16199:a.mode=16200;case 16200:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,$t(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,16191===a.mode&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=16191;break}if(64&b){t.msg=\"invalid literal/length code\",a.mode=me;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg=\"invalid distance code\",a.mode=me;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg=\"invalid distance too far back\",a.mode=me;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg=\"invalid distance too far back\",a.mode=me;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=16200);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=16200;break;case 16206:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<{if(pe(t))return _e;let e=t.state;return e.window&&(e.window=null),t.state=null,le},inflateGetHeader:(t,e)=>{if(pe(t))return _e;const a=t.state;return 0==(2&a.wrap)?_e:(a.head=e,e.done=!1,le)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return pe(t)?_e:(i=t.state,0!==i.wrap&&16190!==i.mode?_e:16190===i.mode&&(n=1,n=F(n,e,a,0),n!==i.check)?fe:(s=Ze(t,e,a,a),s?(i.mode=16210,ce):(i.havedict=1,le)))},inflateInfo:\"pako inflate (from Nodeca project)\"};var Se=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1};const De=Object.prototype.toString,{Z_NO_FLUSH:Te,Z_FINISH:Oe,Z_OK:Fe,Z_STREAM_END:Le,Z_NEED_DICT:Ne,Z_STREAM_ERROR:Ie,Z_DATA_ERROR:Be,Z_MEM_ERROR:Ce}=B;function He(t){this.options=Tt({chunkSize:65536,windowBits:15,to:\"\"},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new Ct,this.strm.avail_out=0;let a=Ue.inflateInit2(this.strm,e.windowBits);if(a!==Fe)throw new Error(I[a]);if(this.header=new Se,Ue.inflateGetHeader(this.strm,this.header),e.dictionary&&(\"string\"==typeof e.dictionary?e.dictionary=Nt(e.dictionary):\"[object ArrayBuffer]\"===De.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=Ue.inflateSetDictionary(this.strm,e.dictionary),a!==Fe)))throw new Error(I[a])}He.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Oe:Te,\"[object ArrayBuffer]\"===De.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=Ue.inflate(a,r),s===Ne&&n&&(s=Ue.inflateSetDictionary(a,n),s===Fe?s=Ue.inflate(a,r):s===Be&&(s=Ne));a.avail_in>0&&s===Le&&a.state.wrap>0&&0!==t[a.next_in];)Ue.inflateReset(a),s=Ue.inflate(a,r);switch(s){case Ie:case Be:case Ne:case Ce:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===Le))if(\"string\"===this.options.to){let t=Bt(a.output,a.next_out),e=a.next_out-t,n=It(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==Fe||0!==o){if(s===Le)return s=Ue.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},He.prototype.onData=function(t){this.chunks.push(t)},He.prototype.onEnd=function(t){t===Fe&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=Ot(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};const{Deflate:Me,deflate:je,deflateRaw:Ke,gzip:Pe}=Vt;var Ye=Me,Ge=je,Xe=B;const We=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const e=this._hasEvents?\",\":\"\";this.deflate.push(e+t,Xe.Z_SYNC_FLUSH),this._hasEvents=!0}finish(){if(this.deflate.push(\"]\",Xe.Z_FINISH),this.deflate.err)throw this.deflate.err;const t=this.deflate.result;return this._init(),t}_init(){this._hasEvents=!1,this.deflate=new Ye,this.deflate.push(\"[\",Xe.Z_NO_FLUSH)}},qe={clear:()=>{We.clear()},addEvent:t=>We.addEvent(t),finish:()=>We.finish(),compress:t=>function(t){return Ge(t)}(t)};addEventListener(\"message\",(function(t){const e=t.data.method,a=t.data.id,i=t.data.arg;if(e in qe&&\"function\"==typeof qe[e])try{const t=qe[e](i);postMessage({id:a,method:e,success:!0,response:t})}catch(t){postMessage({id:a,method:e,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n\nfunction e(){const e=new Blob([r]);return URL.createObjectURL(e)}\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nclass EventBufferArray {\n /** All the events that are buffered to be sent. */\n\n constructor() {\n this.events = [];\n }\n\n /** @inheritdoc */\n get hasEvents() {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n destroy() {\n this.events = [];\n }\n\n /** @inheritdoc */\n async addEvent(event, isCheckout) {\n if (isCheckout) {\n this.events = [event];\n return;\n }\n\n this.events.push(event);\n return;\n }\n\n /** @inheritdoc */\n finish() {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.events = [];\n resolve(JSON.stringify(eventsRet));\n });\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass WorkerHandler {\n\n constructor(worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n ensureReady() {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }) => {\n if ((data ).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n destroy() {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n postMessage(method, arg) {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }) => {\n const response = data ;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response );\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n _getAndIncrementId() {\n return this._id++;\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass EventBufferCompressionWorker {\n /** @inheritdoc */\n\n constructor(worker) {\n this._worker = new WorkerHandler(worker);\n this.hasEvents = false;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occured.\n */\n ensureReady() {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n destroy() {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfuly received and processed by worker.\n */\n async addEvent(event, isCheckout) {\n this.hasEvents = true;\n\n if (isCheckout) {\n // This event is a checkout, make sure worker buffer is cleared before\n // proceeding.\n await this._clear();\n }\n\n return this._sendEventToWorker(event);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n finish() {\n return this._finishRequest();\n }\n\n /**\n * Send the event to the worker.\n */\n _sendEventToWorker(event) {\n return this._worker.postMessage('addEvent', JSON.stringify(event));\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n async _finishRequest() {\n const response = await this._worker.postMessage('finish');\n\n this.hasEvents = false;\n\n return response;\n }\n\n /** Clear any pending events from the worker. */\n _clear() {\n return this._worker.postMessage('clear');\n }\n}\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nclass EventBufferProxy {\n\n constructor(worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritDoc */\n get hasEvents() {\n return this._used.hasEvents;\n }\n\n /** @inheritDoc */\n destroy() {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n addEvent(event, isCheckout) {\n return this._used.addEvent(event, isCheckout);\n }\n\n /** @inheritDoc */\n async finish() {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n ensureWorkerIsLoaded() {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n async _ensureWorkerIsLoaded() {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n async _switchToCompressionWorker() {\n const { events } = this._fallback;\n\n const addEventPromises = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('[Replay] Failed to add events when switching buffers.', error);\n }\n }\n}\n\n/**\n * Create an event buffer for replays.\n */\nfunction createEventBuffer({ useCompression }) {\n // eslint-disable-next-line no-restricted-globals\n if (useCompression && window.Worker) {\n try {\n const workerUrl = e();\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Using compression worker');\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Using simple buffer');\n return new EventBufferArray();\n}\n\n/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nfunction isExpired(\n initialTime,\n expiry,\n targetTime = +new Date(),\n) {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n\n/**\n * Checks to see if session is expired\n */\nfunction isSessionExpired(session, timeouts, targetTime = +new Date()) {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, timeouts.maxSessionLife, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `idleTimeout` ms)\n isExpired(session.lastActivity, timeouts.sessionIdle, targetTime)\n );\n}\n\n/**\n * Save a session to session storage.\n */\nfunction saveSession(session) {\n const hasSessionStorage = 'sessionStorage' in WINDOW;\n if (!hasSessionStorage) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch (e) {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nfunction isSampled(sampleRate) {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n\n/**\n * Get a session with defaults & applied sampling.\n */\nfunction makeSession(session) {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n };\n}\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nfunction getSessionSampleType(sessionSampleRate, errorSampleRate) {\n return isSampled(sessionSampleRate) ? 'session' : isSampled(errorSampleRate) ? 'error' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nfunction createSession({ sessionSampleRate, errorSampleRate, stickySession = false }) {\n const sampled = getSessionSampleType(sessionSampleRate, errorSampleRate);\n const session = makeSession({\n sampled,\n });\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Replay] Creating new session: ${session.id}`);\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n\n/**\n * Fetches a session from storage\n */\nfunction fetchSession() {\n const hasSessionStorage = 'sessionStorage' in WINDOW;\n\n if (!hasSessionStorage) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) ;\n\n return makeSession(sessionObj);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Get or create a session\n */\nfunction getSession({\n timeouts,\n currentSession,\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n}) {\n // If session exists and is passed, use it instead of always hitting session storage\n const session = currentSession || (stickySession && fetchSession());\n\n if (session) {\n // If there is a session, check if it is valid (e.g. \"last activity\" time\n // should be within the \"session idle time\", and \"session started\" time is\n // within \"max session time\").\n const isExpired = isSessionExpired(session, timeouts);\n\n if (!isExpired) {\n return { type: 'saved', session };\n } else if (session.sampled === 'error') {\n // Error samples should not be re-created when expired, but instead we stop when the replay is done\n const discardedSession = makeSession({ sampled: false });\n return { type: 'new', session: discardedSession };\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Session has expired');\n }\n // Otherwise continue to create a new session\n }\n\n const newSession = createSession({\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n });\n\n return { type: 'new', session: newSession };\n}\n\n/**\n * Add an event to the event buffer.\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nasync function addEvent(\n replay,\n event,\n isCheckout,\n) {\n if (!replay.eventBuffer) {\n // This implies that `_isEnabled` is false\n return null;\n }\n\n if (replay.isPaused()) {\n // Do not add to event buffer when recording is paused\n return null;\n }\n\n // TODO: sadness -- we will want to normalize timestamps to be in ms -\n // requires coordination with frontend\n const isMs = event.timestamp > 9999999999;\n const timestampInMs = isMs ? event.timestamp : event.timestamp * 1000;\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdle < Date.now()) {\n return null;\n }\n\n // Only record earliest event if a new session was created, otherwise it\n // shouldn't be relevant\n const earliestEvent = replay.getContext().earliestEvent;\n if (replay.session && replay.session.segmentId === 0 && (!earliestEvent || timestampInMs < earliestEvent)) {\n replay.getContext().earliestEvent = timestampInMs;\n }\n\n try {\n return await replay.eventBuffer.addEvent(event, isCheckout);\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(error);\n replay.stop('addEvent');\n\n const client = getCurrentHub().getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n\n/** If the event is an error event */\nfunction isErrorEvent(event) {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nfunction isReplayEvent(event) {\n return event.type === 'replay_event';\n}\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nfunction handleAfterSendEvent(replay) {\n // Custom transports may still be returning `Promise`, which means we cannot expect the status code to be available there\n // TODO (v8): remove this check as it will no longer be necessary\n const enforceStatusCode = isBaseTransportSend();\n\n return (event, sendResponse) => {\n if (!isErrorEvent(event) && !isTransactionEvent(event)) {\n return;\n }\n\n const statusCode = sendResponse && sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (enforceStatusCode && (!statusCode || statusCode < 200 || statusCode >= 300)) {\n return;\n }\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n if (isTransactionEvent(event) && event.contexts && event.contexts.trace && event.contexts.trace.trace_id) {\n replay.getContext().traceIds.add(event.contexts.trace.trace_id );\n return;\n }\n\n // Everything below is just for error events\n if (!isErrorEvent(event)) {\n return;\n }\n\n // Add error to list of errorIds of replay\n if (event.event_id) {\n replay.getContext().errorIds.add(event.event_id);\n }\n\n // Trigger error recording\n // Need to be very careful that this does not cause an infinite loop\n if (\n replay.recordingMode === 'error' &&\n event.exception &&\n event.message !== UNABLE_TO_SEND_REPLAY // ignore this error because otherwise we could loop indefinitely with trying to capture replay and failing\n ) {\n setTimeout(async () => {\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await replay.flushImmediate();\n\n if (replay.stopRecording()) {\n // Reset all \"capture on error\" configuration before\n // starting a new recording\n replay.recordingMode = 'session';\n replay.startRecording();\n }\n });\n }\n };\n}\n\nfunction isBaseTransportSend() {\n const client = getCurrentHub().getClient();\n if (!client) {\n return false;\n }\n\n const transport = client.getTransport();\n if (!transport) {\n return false;\n }\n\n return (\n (transport.send ).__sentry__baseTransport__ || false\n );\n}\n\nvar NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType || (NodeType = {}));\n\n/**\n * Create a breadcrumb for a replay.\n */\nfunction createBreadcrumb(\n breadcrumb,\n) {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n\n/**\n * Add a breadcrumb event to replay.\n */\nfunction addBreadcrumbEvent(replay, breadcrumb) {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category )) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n void addEvent(replay, {\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n payload: normalize(breadcrumb),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n\n// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nfunction getAttributesToRecord(attributes) {\n const obj = {};\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n\nconst handleDomListener =\n (replay) =>\n (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to react to DOM events.\n */\nfunction handleDom(handlerData) {\n let target;\n let targetNode;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n targetNode = getTargetNode(handlerData);\n target = htmlTreeAsString(targetNode);\n } catch (e) {\n target = '';\n }\n\n // `__sn` property is the serialized node created by rrweb\n const serializedNode =\n targetNode && '__sn' in targetNode && targetNode.__sn.type === NodeType.Element ? targetNode.__sn : null;\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n message: target,\n data: serializedNode\n ? {\n nodeId: serializedNode.id,\n node: {\n id: serializedNode.id,\n tagName: serializedNode.tagName,\n textContent: targetNode\n ? Array.from(targetNode.childNodes)\n .map(\n (node) => '__sn' in node && node.__sn.type === NodeType.Text && node.__sn.textContent,\n )\n .filter(Boolean) // filter out empty values\n .map(text => (text ).trim())\n .join('')\n : '',\n attributes: getAttributesToRecord(serializedNode.attributes),\n },\n }\n : {},\n });\n}\n\nfunction getTargetNode(handlerData) {\n if (isEventWithTarget(handlerData.event)) {\n return handlerData.event.target;\n }\n\n return handlerData.event;\n}\n\nfunction isEventWithTarget(event) {\n return !!(event ).target;\n}\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nfunction isRrwebError(event, hint) {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-ignore this may be set by rrweb when it finds errors\n if (hint.originalException && hint.originalException.__rrweb__) {\n return true;\n }\n\n // Check if any exception originates from rrweb\n return event.exception.values.some(exception => {\n if (!exception.stacktrace || !exception.stacktrace.frames || !exception.stacktrace.frames.length) {\n return false;\n }\n\n return exception.stacktrace.frames.some(frame => frame.filename && frame.filename.includes('/rrweb/src/'));\n });\n}\n\n/**\n * Returns a listener to be added to `addGlobalEventProcessor(listener)`.\n */\nfunction handleGlobalEventListener(\n replay,\n includeAfterSendEventHandling = false,\n) {\n const afterSendHandler = includeAfterSendEventHandling ? handleAfterSendEvent(replay) : undefined;\n\n return (event, hint) => {\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors & transactions, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event)) {\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Ignoring error from rrweb internals', event);\n return null;\n }\n\n // Only tag transactions with replayId if not waiting for an error\n if (isErrorEvent(event) || (isTransactionEvent(event) && replay.recordingMode === 'session')) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals && isErrorEvent(event)) {\n const exc = getEventExceptionValues(event);\n addInternalBreadcrumb({\n message: `Tagging event (${event.event_id}) - ${event.message} - ${exc.type}: ${exc.value}`,\n });\n }\n\n // In cases where a custom client is used that does not support the new hooks (yet),\n // we manually call this hook method here\n if (afterSendHandler) {\n // Pretend the error had a 200 response so we always capture it\n afterSendHandler(event, { statusCode: 200 });\n }\n\n return event;\n };\n}\n\nfunction addInternalBreadcrumb(arg) {\n const { category, level, message, ...rest } = arg;\n\n addBreadcrumb({\n category: category || 'console',\n level: level || 'debug',\n message: `[debug]: ${message}`,\n ...rest,\n });\n}\n\nfunction getEventExceptionValues(event) {\n return {\n type: 'Unknown',\n value: 'n/a',\n ...(event.exception && event.exception.values && event.exception.values[0]),\n };\n}\n\n/**\n * Create a \"span\" for each performance entry. The parent transaction is `this.replayEvent`.\n */\nfunction createPerformanceSpans(\n replay,\n entries,\n) {\n return entries.map(({ type, start, end, name, data }) =>\n addEvent(replay, {\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n }),\n );\n}\n\nfunction handleHistory(handlerData) {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('history', listener)`.\n */\nfunction handleHistorySpanListener(replay) {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nfunction shouldFilterRequest(replay, url) {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return _isSentryRequest(url);\n}\n\n/**\n * Checks wether a given URL belongs to the configured Sentry DSN.\n */\nfunction _isSentryRequest(url) {\n const client = getCurrentHub().getClient();\n const dsn = client && client.getDsn();\n return dsn ? url.includes(dsn.host) : false;\n}\n\n/** Add a performance entry breadcrumb */\nfunction addNetworkBreadcrumb(\n replay,\n result,\n) {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n\n/** only exported for tests */\nfunction handleFetch(handlerData) {\n const { startTimestamp, endTimestamp, fetchData, response } = handlerData;\n\n if (!endTimestamp) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url } = fetchData;\n\n return {\n type: 'resource.fetch',\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode: response && (response ).status,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('fetch', listener)`.\n */\nfunction handleFetchSpanListener(replay) {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleFetch(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n\n/** only exported for tests */\nfunction handleXhr(handlerData) {\n const { startTimestamp, endTimestamp, xhr } = handlerData;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return null;\n }\n\n // This is only used as a fallback, so we know the body sizes are never set here\n const { method, url, status_code: statusCode } = sentryXhrData;\n\n if (url === undefined) {\n return null;\n }\n\n return {\n type: 'resource.xhr',\n name: url,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n data: {\n method,\n statusCode,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addInstrumentationHandler('xhr', listener)`.\n */\nfunction handleXhrSpanListener(replay) {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleXhr(handlerData);\n\n addNetworkBreadcrumb(replay, result);\n };\n}\n\n/** Get the size of a body. */\nfunction getBodySize(\n body,\n textEncoder,\n) {\n if (!body) {\n return undefined;\n }\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = _serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch (e) {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nfunction parseContentLengthHeader(header) {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Get the string representation of a body. */\nfunction getBodyString(body) {\n if (typeof body === 'string') {\n return body;\n }\n\n if (body instanceof URLSearchParams) {\n return body.toString();\n }\n\n if (body instanceof FormData) {\n return _serializeFormData(body);\n }\n\n return undefined;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nfunction makeNetworkReplayBreadcrumb(\n type,\n data,\n) {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Get either a JSON network body, or a text representation. */\nfunction getNetworkBody(bodyText) {\n if (!bodyText) {\n return;\n }\n\n try {\n return JSON.parse(bodyText);\n } catch (e2) {\n // return text\n }\n\n return bodyText;\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nfunction buildNetworkRequestOrResponse(\n headers,\n bodySize,\n body,\n) {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info = {\n headers,\n size: bodySize,\n };\n\n if (bodySize < NETWORK_BODY_MAX_SIZE) {\n info.body = body;\n } else {\n info._meta = {\n errors: ['MAX_BODY_SIZE_EXCEEDED'],\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nfunction getAllowedHeaders(headers, allowedHeaders) {\n return Object.keys(headers).reduce((filteredHeaders, key) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = headers[key];\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction _serializeFormData(formData) {\n // This is a bit simplified, but gives us a decent estimate\n // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'\n // @ts-ignore passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nasync function captureFetchBreadcrumbToReplay(\n breadcrumb,\n hint,\n options\n\n,\n) {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nfunction enrichFetchBreadcrumb(\n breadcrumb,\n hint,\n options,\n) {\n const { input, response } = hint;\n\n const body = _getFetchRequestArgBody(input);\n const reqSize = getBodySize(body, options.textEncoder);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb,\n hint,\n options\n\n,\n) {\n const { startTimestamp, endTimestamp } = hint;\n\n const {\n url,\n method,\n status_code: statusCode,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const request = _getRequestInfo(options, hint.input, requestBodySize);\n const response = await _getResponseInfo(options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode: statusCode || 0,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { captureBodies, requestHeaders },\n input,\n requestBodySize,\n) {\n const headers = getRequestHeaders(input, requestHeaders);\n\n if (!captureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = _getFetchRequestArgBody(input);\n const body = getNetworkBody(getBodyString(requestBody));\n return buildNetworkRequestOrResponse(headers, requestBodySize, body);\n}\n\nasync function _getResponseInfo(\n {\n captureBodies,\n textEncoder,\n responseHeaders,\n }\n\n,\n response,\n responseBodySize,\n) {\n const headers = getAllHeaders(response.headers, responseHeaders);\n\n if (!captureBodies && responseBodySize !== undefined) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n // Only clone the response if we need to\n try {\n // We have to clone this, as the body can only be read once\n const res = response.clone();\n const { body, bodyText } = await _parseFetchBody(res);\n\n const size =\n bodyText && bodyText.length && responseBodySize === undefined\n ? getBodySize(bodyText, textEncoder)\n : responseBodySize;\n\n if (captureBodies) {\n return buildNetworkRequestOrResponse(headers, size, body);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch (e) {\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchBody(\n response,\n) {\n let bodyText;\n\n try {\n bodyText = await response.text();\n } catch (e2) {\n return {};\n }\n\n try {\n const body = JSON.parse(bodyText);\n return { body, bodyText };\n } catch (e3) {\n // just send bodyText\n }\n\n return { bodyText, body: bodyText };\n}\n\nfunction _getFetchRequestArgBody(fetchArgs = []) {\n // We only support getting the body from the fetch options\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] ).body;\n}\n\nfunction getAllHeaders(headers, allowedHeaders) {\n const allHeaders = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) ;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs, allowedHeaders) {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] , allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] , allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input,\n allowedHeaders,\n) {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where approriate).\n */\nasync function captureXhrBreadcrumbToReplay(\n breadcrumb,\n hint,\n options,\n) {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Failed to capture fetch breadcrumb', error);\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nfunction enrichXhrBreadcrumb(\n breadcrumb,\n hint,\n options,\n) {\n const { xhr, input } = hint;\n\n const reqSize = getBodySize(input, options.textEncoder);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : getBodySize(xhr.response, options.textEncoder);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb,\n hint,\n options,\n) {\n const { startTimestamp, endTimestamp, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const requestHeaders = xhrInfo ? getAllowedHeaders(xhrInfo.request_headers, options.requestHeaders) : {};\n const responseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.responseHeaders);\n\n if (!url) {\n return null;\n }\n\n const request = buildNetworkRequestOrResponse(\n requestHeaders,\n requestBodySize,\n options.captureBodies ? getNetworkBody(getBodyString(input)) : undefined,\n );\n const response = buildNetworkRequestOrResponse(\n responseHeaders,\n responseBodySize,\n options.captureBodies ? getNetworkBody(hint.xhr.responseText) : undefined,\n );\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode: statusCode || 0,\n request,\n response,\n };\n}\n\nfunction getResponseHeaders(xhr) {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc, line) => {\n const [key, value] = line.split(': ');\n acc[key.toLowerCase()] = value;\n return acc;\n }, {});\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nfunction handleNetworkBreadcrumbs(replay) {\n const client = getCurrentHub().getClient();\n\n try {\n const textEncoder = new TextEncoder();\n\n const options = {\n replay,\n textEncoder,\n ...replay.getExperimentalOptions().network,\n };\n\n if (client && client.on) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n } else {\n // Fallback behavior\n addInstrumentationHandler('fetch', handleFetchSpanListener(replay));\n addInstrumentationHandler('xhr', handleXhrSpanListener(replay));\n }\n } catch (e2) {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nfunction beforeAddNetworkBreadcrumb(\n options,\n breadcrumb,\n hint,\n) {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint, options);\n\n void captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint, options);\n\n void captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint) {\n return hint && hint.xhr;\n}\n\nfunction _isFetchHint(hint) {\n return hint && hint.response;\n}\n\nlet _LAST_BREADCRUMB = null;\n\nconst handleScopeListener =\n (replay) =>\n (scope) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleScope(scope);\n\n if (!result) {\n return;\n }\n\n addBreadcrumbEvent(replay, result);\n };\n\n/**\n * An event handler to handle scope changes.\n */\nfunction handleScope(scope) {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n newBreadcrumb.category &&\n (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.'))\n ) {\n return null;\n }\n\n return createBreadcrumb(newBreadcrumb);\n}\n\n/**\n * Add global listeners that cannot be removed.\n */\nfunction addGlobalListeners(replay) {\n // Listeners from core SDK //\n const scope = getCurrentHub().getScope();\n const client = getCurrentHub().getClient();\n\n if (scope) {\n scope.addScopeListener(handleScopeListener(replay));\n }\n addInstrumentationHandler('dom', handleDomListener(replay));\n addInstrumentationHandler('history', handleHistorySpanListener(replay));\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n addGlobalEventProcessor(handleGlobalEventListener(replay, !hasHooks(client)));\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (hasHooks(client)) {\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc) => {\n const replayId = replay.getSessionId();\n if (replayId) {\n dsc.replay_id = replayId;\n }\n });\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasHooks(client) {\n return !!(client && client.on);\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nasync function addMemoryEntry(replay) {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-ignore memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry) {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n\n// Map entryType -> function to normalize data for event\n// @ts-ignore TODO: entry type does not fit the create* functions entry type\nconst ENTRY_TYPES\n\n = {\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n // @ts-ignore TODO: entry type does not fit the create* functions entry type\n ['largest-contentful-paint']: createLargestContentfulPaint,\n};\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nfunction createPerformanceEntries(\n entries,\n) {\n return entries.map(createPerformanceEntry).filter(Boolean) ;\n}\n\nfunction createPerformanceEntry(entry) {\n if (ENTRY_TYPES[entry.entryType] === undefined) {\n return null;\n }\n\n return ENTRY_TYPES[entry.entryType](entry);\n}\n\nfunction getAbsoluteTime(time) {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry) {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry) {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry,\n) {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\nfunction createLargestContentfulPaint(\n entry,\n) {\n const { entryType, startTime, size } = entry;\n\n let startTimeOrNavigationActivation = 0;\n\n if (WINDOW.performance) {\n const navEntry = WINDOW.performance.getEntriesByType('navigation')[0]\n\n;\n\n // See https://github.com/GoogleChrome/web-vitals/blob/9f11c4c6578fb4c5ee6fa4e32b9d1d756475f135/src/lib/getActivationStart.ts#L21\n startTimeOrNavigationActivation = (navEntry && navEntry.activationStart) || 0;\n }\n\n // value is in ms\n const value = Math.max(startTime - startTimeOrNavigationActivation, 0);\n // LCP doesn't have a \"duration\", it just happens at a single point in time.\n // But the UI expects both, so use end (in seconds) for both timestamps.\n const end = getAbsoluteTime(startTimeOrNavigationActivation) + value / 1000;\n\n return {\n type: entryType,\n name: entryType,\n start: end,\n end,\n data: {\n value, // LCP \"duration\" in ms\n size,\n // Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n nodeId: record.mirror.getId(entry.element ),\n },\n };\n}\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nfunction debounce(func, wait, options) {\n let callbackReturnValue;\n\n let timerId;\n let maxTimerId;\n\n const maxWait = options && options.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc() {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers() {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush() {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced() {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nfunction getHandleRecordingEmit(replay) {\n let hadFirstEvent = false;\n\n return (event, _isCheckout) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('[Replay] Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'error' && isCheckout) {\n replay.setInitialState();\n }\n\n // We need to clear existing events on a checkout, otherwise they are\n // incremental event updates and should be appended\n void addEvent(replay, event, isCheckout);\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (replay.session && replay.session.previousSessionId) {\n return true;\n }\n\n // See note above re: session start needs to reflect the most recent\n // checkout.\n if (replay.recordingMode === 'error' && replay.session) {\n const { earliestEvent } = replay.getContext();\n if (earliestEvent) {\n replay.session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(replay.session);\n }\n }\n }\n\n // Flush immediately so that we do not miss the first segment, otherwise\n // it can prevent loading on the UI. This will cause an increase in short\n // replays (e.g. opening and closing a tab quickly), but these can be\n // filtered on the UI.\n if (replay.recordingMode === 'session') {\n // We want to ensure the worker is ready, as otherwise we'd always send the first event uncompressed\n void replay.flushImmediate();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nfunction createReplayEnvelope(\n replayEvent,\n recordingData,\n dsn,\n tunnel,\n) {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n\n/**\n * Prepare the recording data ready to be sent.\n */\nfunction prepareRecordingData({\n recordingData,\n headers,\n}\n\n) {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nasync function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}\n\n) {\n const integrations =\n typeof client._integrations === 'object' && client._integrations !== null && !Array.isArray(client._integrations)\n ? Object.keys(client._integrations)\n : undefined;\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n { event_id, integrations },\n scope,\n )) ;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata && client.getSdkMetadata();\n const { name, version } = (metadata && metadata.sdk) || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n\n/**\n * Send replay attachment using `fetch()`\n */\nasync function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n options,\n}) {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const hub = getCurrentHub();\n const client = hub.getClient();\n const scope = hub.getScope();\n const transport = client && client.getTransport();\n const dsn = client && client.getDsn();\n\n if (!client || !scope || !transport || !dsn || !session.sampled) {\n return;\n }\n\n const baseEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay', baseEvent);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('An event processor returned `null`, will not send event.');\n return;\n }\n\n replayEvent.contexts = {\n ...replayEvent.contexts,\n replay: {\n ...(replayEvent.contexts && replayEvent.contexts.replay),\n session_sample_rate: options.sessionSampleRate,\n error_sample_rate: options.errorSampleRate,\n },\n };\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n \"replay\": {\n \"session_sample_rate\": 1,\n \"error_sample_rate\": 0,\n },\n },\n }\n */\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-ignore This needs lib es2022 and newer\n error.cause = err;\n } catch (e) {\n // nothing to do\n }\n throw error;\n }\n\n // TODO (v8): we can remove this guard once transport.send's type signature doesn't include void anymore\n if (!response) {\n return response;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nclass TransportStatusCodeError extends Error {\n constructor(statusCode) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nasync function sendReplay(\n replayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n) {\n const { recordingData, options } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && options._experiments && options._experiments.captureExceptions) {\n captureException(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-ignore This needs lib es2022 and newer\n error.cause = err;\n } catch (e) {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return await new Promise((resolve, reject) => {\n setTimeout(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n\n/* eslint-disable max-lines */ // TODO: We might want to split this file up\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nclass ReplayContainer {\n __init() {this.eventBuffer = null;}\n\n /**\n * List of PerformanceEntry from PerformanceObserver\n */\n __init2() {this.performanceEvents = [];}\n\n /**\n * Recording can happen in one of two modes:\n * * session: Record the whole session, sending it continuously\n * * error: Always keep the last 60s of recording, and when an error occurs, send it immediately\n */\n __init3() {this.recordingMode = 'session';}\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n __init4() {this.timeouts = {\n sessionIdle: SESSION_IDLE_DURATION,\n maxSessionLife: MAX_SESSION_LIFE,\n }; }\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n __init5() {this._performanceObserver = null;}\n\n __init6() {this._flushLock = null;}\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n __init7() {this._lastActivity = Date.now();}\n\n /**\n * Is the integration currently active?\n */\n __init8() {this._isEnabled = false;}\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n __init9() {this._isPaused = false;}\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n __init10() {this._hasInitializedCoreListeners = false;}\n\n /**\n * Function to stop recording\n */\n __init11() {this._stopRecording = null;}\n\n __init12() {this._context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n earliestEvent: null,\n initialTimestamp: Date.now(),\n initialUrl: '',\n };}\n\n constructor({\n options,\n recordingOptions,\n }\n\n) {ReplayContainer.prototype.__init.call(this);ReplayContainer.prototype.__init2.call(this);ReplayContainer.prototype.__init3.call(this);ReplayContainer.prototype.__init4.call(this);ReplayContainer.prototype.__init5.call(this);ReplayContainer.prototype.__init6.call(this);ReplayContainer.prototype.__init7.call(this);ReplayContainer.prototype.__init8.call(this);ReplayContainer.prototype.__init9.call(this);ReplayContainer.prototype.__init10.call(this);ReplayContainer.prototype.__init11.call(this);ReplayContainer.prototype.__init12.call(this);ReplayContainer.prototype.__init13.call(this);ReplayContainer.prototype.__init14.call(this);ReplayContainer.prototype.__init15.call(this);ReplayContainer.prototype.__init16.call(this);ReplayContainer.prototype.__init17.call(this);\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._experimentalOptions = _getExperimentalOptions(options);\n }\n\n /** Get the event context. */\n getContext() {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n isEnabled() {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n isPaused() {\n return this._isPaused;\n }\n\n /** Get the replay integration options. */\n getOptions() {\n return this._options;\n }\n\n /**\n * Get the experimental options.\n * THIS IS INTERNAL AND SUBJECT TO CHANGE!\n * @hidden\n */\n getExperimentalOptions() {\n return this._experimentalOptions;\n }\n\n /**\n * Initializes the plugin.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n start() {\n this.setInitialState();\n\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // If there is no session, then something bad has happened - can't continue\n if (!this.session) {\n this._handleException(new Error('No session found'));\n return;\n }\n\n if (!this.session.sampled) {\n // If session was not sampled, then we do not initialize the integration at all.\n return;\n }\n\n // If session is sampled for errors, then we need to set the recordingMode\n // to 'error', which will configure recording with different options.\n if (this.session.sampled === 'error') {\n this.recordingMode = 'error';\n }\n\n // setup() is generally called on page load or manually - in both cases we\n // should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n });\n\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n\n this.startRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n startRecording() {\n try {\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'error' && { checkoutEveryNms: ERROR_CHECKOUT_TIME }),\n emit: getHandleRecordingEmit(this),\n onMutation: this._onMutationHandler,\n });\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n * Returns true if it was stopped, else false.\n */\n stopRecording() {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n return true;\n }\n\n return false;\n } catch (err) {\n this._handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n stop(reason) {\n if (!this._isEnabled) {\n return;\n }\n\n try {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n const msg = `[Replay] Stopping Replay${reason ? ` triggered by ${reason}` : ''}`;\n\n // When `traceInternals` is enabled, we want to log this to the console\n // Else, use the regular debug output\n // eslint-disable-next-line\n const log = this.getOptions()._experiments.traceInternals ? console.warn : logger.log;\n log(msg);\n }\n\n this._isEnabled = false;\n this._removeListeners();\n this.stopRecording();\n this.eventBuffer && this.eventBuffer.destroy();\n this.eventBuffer = null;\n this._debouncedFlush.cancel();\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n pause() {\n this._isPaused = true;\n this.stopRecording();\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n resume() {\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n addUpdate(cb) {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'error'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'error') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n triggerUserActivity() {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n *\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of mulitple flushes happening closely together.\n */\n flushImmediate() {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() ;\n }\n\n /** Get the current sesion (=replay) ID */\n getSessionId() {\n return this.session && this.session.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n checkAndHandleExpiredSession() {\n const oldSessionId = this.getSessionId();\n\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdle) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._loadAndCheckSession()) {\n return;\n }\n\n // Session was expired if session ids do not match\n const expired = oldSessionId !== this.getSessionId();\n\n if (!expired) {\n return true;\n }\n\n // Session is expired, trigger a full snapshot (which will create a new session)\n this._triggerFullSnapshot();\n\n return false;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n setInitialState() {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEvents = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /** A wrapper to conditionally capture exceptions. */\n _handleException(error) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay]', error);\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && this._options._experiments && this._options._experiments.captureExceptions) {\n captureException(error);\n }\n }\n\n /**\n * Loads (or refreshes) the current session.\n * Returns false if session is not recorded.\n */\n _loadAndCheckSession() {\n const { type, session } = getSession({\n timeouts: this.timeouts,\n stickySession: Boolean(this._options.stickySession),\n currentSession: this.session,\n sessionSampleRate: this._options.sessionSampleRate,\n errorSampleRate: this._options.errorSampleRate,\n });\n\n // If session was newly created (i.e. was not loaded from storage), then\n // enable flag to create the root replay\n if (type === 'new') {\n this.setInitialState();\n }\n\n const currentSessionId = this.getSessionId();\n if (session.id !== currentSessionId) {\n session.previousSessionId = currentSessionId;\n }\n\n this.session = session;\n\n if (!this.session.sampled) {\n this.stop('session unsampled');\n return false;\n }\n\n return true;\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n _addListeners() {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this._handleException(err);\n }\n\n // PerformanceObserver //\n if (!('PerformanceObserver' in WINDOW)) {\n return;\n }\n\n this._performanceObserver = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n _removeListeners() {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n\n if (this._performanceObserver) {\n this._performanceObserver.disconnect();\n this._performanceObserver = null;\n }\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n __init13() {this._handleVisibilityChange = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };}\n\n /**\n * Handle when page is blurred\n */\n __init14() {this._handleWindowBlur = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };}\n\n /**\n * Handle when page is focused\n */\n __init15() {this._handleWindowFocus = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };}\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n _doChangeToBackgroundTasks(breadcrumb) {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, this.timeouts);\n\n if (breadcrumb && !expired) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n this._conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n _doChangeToForegroundTasks(breadcrumb) {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Trigger rrweb to take a full snapshot which will cause this plugin to\n * create a new Replay event.\n */\n _triggerFullSnapshot(checkout = true) {\n try {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Replay] Taking full rrweb snapshot');\n record.takeFullSnapshot(checkout);\n } catch (err) {\n this._handleException(err);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n _updateUserActivity(_lastActivity = Date.now()) {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n _updateSessionActivity(_lastActivity = Date.now()) {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n _createCustomBreadcrumb(breadcrumb) {\n this.addUpdate(() => {\n void addEvent(this, {\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEvents`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n _addPerformanceEntries() {\n // Copy and reset entries before processing\n const entries = [...this.performanceEvents];\n this.performanceEvents = [];\n\n return Promise.all(createPerformanceSpans(this, createPerformanceEntries(entries)));\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n _conditionalFlush() {\n if (this.recordingMode === 'error') {\n return;\n }\n\n void this.flushImmediate();\n }\n\n /**\n * Clear _context\n */\n _clearContext() {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n this._context.earliestEvent = null;\n }\n\n /**\n * Return and clear _context\n */\n _popEventContext() {\n if (this._context.earliestEvent && this._context.earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = this._context.earliestEvent;\n }\n\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds).filter(Boolean),\n traceIds: Array.from(this._context.traceIds).filter(Boolean),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n async _runFlush() {\n if (!this.session || !this.eventBuffer) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer || !this.eventBuffer.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n try {\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n // NOTE: Copy values from instance members, as it's possible they could\n // change before the flush finishes.\n const replayId = this.session.id;\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n options: this.getOptions(),\n timestamp: Date.now(),\n });\n } catch (err) {\n this._handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n this.stop('sendReplay');\n\n const client = getCurrentHub().getClient();\n\n if (client) {\n client.recordDroppedEvent('send_error', 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n __init16() {this._flush = async () => {\n if (!this._isEnabled) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('[Replay] No session found to flush.');\n return;\n }\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // this._flushLock acts as a lock so that future calls to `_flush()`\n // will be blocked until this promise resolves\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n await this._flushLock;\n this._flushLock = null;\n return;\n }\n\n // Wait for previous flush to finish, then call the debounced `_flush()`.\n // It's possible there are other flush requests queued and waiting for it\n // to resolve. We want to reduce all outstanding requests (as well as any\n // new flush requests that occur within a second of the locked flush\n // completing) into a single flush.\n\n try {\n await this._flushLock;\n } catch (err) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(err);\n } finally {\n this._debouncedFlush();\n }\n };}\n\n /** Save the session, if it is sticky */\n _maybeSaveSession() {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n __init17() {this._onMutationHandler = (mutations) => {\n const count = mutations.length;\n\n const mutationLimit = this._options._experiments.mutationLimit || 0;\n const mutationBreadcrumbLimit = this._options._experiments.mutationBreadcrumbLimit || 1000;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n if (overMutationLimit) {\n // We want to skip doing an incremental snapshot if there are too many mutations\n // Instead, we do a full snapshot\n this._triggerFullSnapshot(false);\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n };}\n}\n\nfunction _getExperimentalOptions(options) {\n const requestHeaders = options._experiments.captureRequestHeaders || [];\n const responseHeaders = options._experiments.captureResponseHeaders || [];\n const captureBodies = options._experiments.captureNetworkBodies || false;\n\n // Add defaults\n const defaultHeaders = ['content-length', 'content-type', 'accept'];\n\n return {\n network: {\n captureBodies,\n requestHeaders: [...defaultHeaders, ...requestHeaders.map(header => header.toLowerCase())],\n responseHeaders: [...defaultHeaders, ...responseHeaders.map(header => header.toLowerCase())],\n },\n };\n}\n\nfunction getOption(\n selectors,\n defaultSelectors,\n deprecatedClassOption,\n deprecatedSelectorOption,\n) {\n const deprecatedSelectors = typeof deprecatedSelectorOption === 'string' ? deprecatedSelectorOption.split(',') : [];\n\n const allSelectors = [\n ...selectors,\n // @deprecated\n ...deprecatedSelectors,\n\n // sentry defaults\n ...defaultSelectors,\n ];\n\n // @deprecated\n if (typeof deprecatedClassOption !== 'undefined') {\n // NOTE: No support for RegExp\n if (typeof deprecatedClassOption === 'string') {\n allSelectors.push(`.${deprecatedClassOption}`);\n }\n\n // eslint-disable-next-line no-console\n console.warn(\n '[Replay] You are using a deprecated configuration item for privacy. Read the documentation on how to use the new privacy configuration.',\n );\n }\n\n return allSelectors.join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nfunction getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n}) {\n const defaultBlockedElements = ['base[href=\"/\"]'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]'], maskTextClass, maskTextSelector);\n const unmaskSelector = getOption(unmask, ['.sentry-unmask', '[data-sentry-unmask]']);\n\n const options = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n maskInputSelector: maskSelector,\n unmaskInputSelector: unmaskSelector,\n\n blockSelector: getOption(\n block,\n ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements],\n blockClass,\n blockSelector,\n ),\n unblockSelector: getOption(unblock, ['.sentry-unblock', '[data-sentry-unblock]']),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]'], ignoreClass),\n };\n\n if (blockClass instanceof RegExp) {\n options.blockClass = blockClass;\n }\n\n if (maskTextClass instanceof RegExp) {\n options.maskTextClass = maskTextClass;\n }\n\n return options;\n}\n\n/**\n * Returns true if we are in the browser.\n */\nfunction isBrowser() {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer() {\n return typeof process !== 'undefined' && (process ).type === 'renderer';\n}\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nlet _initialized = false;\n\n/**\n * The main replay integration class, to be passed to `init({ integrations: [] })`.\n */\nclass Replay {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Replay';}\n\n /**\n * @inheritDoc\n */\n __init() {this.name = Replay.id;}\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n\n constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n stickySession = true,\n useCompression = true,\n _experiments = {},\n sessionSampleRate,\n errorSampleRate,\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mask = [],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n // eslint-disable-next-line deprecation/deprecation\n blockClass,\n // eslint-disable-next-line deprecation/deprecation\n blockSelector,\n // eslint-disable-next-line deprecation/deprecation\n maskInputOptions,\n // eslint-disable-next-line deprecation/deprecation\n maskTextClass,\n // eslint-disable-next-line deprecation/deprecation\n maskTextSelector,\n // eslint-disable-next-line deprecation/deprecation\n ignoreClass,\n } = {}) {Replay.prototype.__init.call(this);\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { ...(maskInputOptions || {}), password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n\n ...getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n blockClass,\n blockSelector,\n maskTextClass,\n maskTextSelector,\n ignoreClass,\n }),\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n stickySession,\n sessionSampleRate,\n errorSampleRate,\n useCompression,\n blockAllMedia,\n _experiments,\n };\n\n if (typeof sessionSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`sessionSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysSessionSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysSessionSampleRate: ${sessionSampleRate} })`,\n );\n\n this._initialOptions.sessionSampleRate = sessionSampleRate;\n }\n\n if (typeof errorSampleRate === 'number') {\n // eslint-disable-next-line\n console.warn(\n `[Replay] You are passing \\`errorSampleRate\\` to the Replay integration.\nThis option is deprecated and will be removed soon.\nInstead, configure \\`replaysOnErrorSampleRate\\` directly in the SDK init options, e.g.:\nSentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,\n );\n\n this._initialOptions.errorSampleRate = errorSampleRate;\n }\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n get _isInitialized() {\n return _initialized;\n }\n\n /** Update _isInitialized */\n set _isInitialized(value) {\n _initialized = value;\n }\n\n /**\n * We previously used to create a transaction in `setupOnce` and it would\n * potentially create a transaction before some native SDK integrations have run\n * and applied their own global event processor. An example is:\n * https://github.com/getsentry/sentry-javascript/blob/b47ceafbdac7f8b99093ce6023726ad4687edc48/packages/browser/src/integrations/useragent.ts\n *\n * So we call `replay.setup` in next event loop as a workaround to wait for other\n * global event processors to finish. This is no longer needed, but keeping it\n * here to avoid any future issues.\n */\n setupOnce() {\n if (!isBrowser()) {\n return;\n }\n\n this._setup();\n\n // XXX: See method comments above\n setTimeout(() => this.start());\n }\n\n /**\n * Initializes the plugin.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n start() {\n if (!this._replay) {\n return;\n }\n\n this._replay.start();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n stop() {\n if (!this._replay) {\n return;\n }\n\n this._replay.stop();\n }\n\n /**\n * Immediately send all pending events.\n */\n flush() {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.flushImmediate();\n }\n\n /**\n * Get the current session ID.\n */\n getReplayId() {\n if (!this._replay || !this._replay.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n\n /** Setup the integration. */\n _setup() {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n} Replay.__initStatic();\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions) {\n const client = getCurrentHub().getClient();\n const opt = client && (client.getOptions() );\n\n const finalOptions = { sessionSampleRate: 0, errorSampleRate: 0, ...dropUndefinedKeys(initialOptions) };\n\n if (!opt) {\n // eslint-disable-next-line no-console\n console.warn('SDK client is not available.');\n return finalOptions;\n }\n\n if (\n initialOptions.sessionSampleRate == null && // TODO remove once deprecated rates are removed\n initialOptions.errorSampleRate == null && // TODO remove once deprecated rates are removed\n opt.replaysSessionSampleRate == null &&\n opt.replaysOnErrorSampleRate == null\n ) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n }\n\n if (typeof opt.replaysSessionSampleRate === 'number') {\n finalOptions.sessionSampleRate = opt.replaysSessionSampleRate;\n }\n\n if (typeof opt.replaysOnErrorSampleRate === 'number') {\n finalOptions.errorSampleRate = opt.replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nexport { Replay };\n//# sourceMappingURL=index.js.map\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nexport { WINDOW };\n//# sourceMappingURL=types.js.map\n","import { getActiveTransaction } from '@sentry/core';\nimport { logger } from '@sentry/utils';\nimport { WINDOW } from './types.js';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nfunction registerBackgroundTabDetection() {\n if (WINDOW && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() ;\n if (WINDOW.document.hidden && activeTransaction) {\n const statusType = 'cancelled';\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(statusType);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n\nexport { registerBackgroundTabDetection };\n//# sourceMappingURL=backgroundtab.js.map\n","const bindReporter = (\n callback,\n metric,\n reportAllChanges,\n) => {\n let prevValue;\n let delta;\n return (forceReport) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n callback(metric);\n }\n }\n }\n };\n};\n\nexport { bindReporter };\n//# sourceMappingURL=bindReporter.js.map\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nconst generateUniqueID = () => {\n return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n\nexport { generateUniqueID };\n//# sourceMappingURL=generateUniqueID.js.map\n","import { WINDOW } from '../../types.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst getNavigationEntryFromPerformanceTiming = () => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n navigationEntry[key] = Math.max((timing[key ] ) - timing.navigationStart, 0);\n }\n }\n return navigationEntry ;\n};\n\nconst getNavigationEntry = () => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n\nexport { getNavigationEntry };\n//# sourceMappingURL=getNavigationEntry.js.map\n","import { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst getActivationStart = () => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n\nexport { getActivationStart };\n//# sourceMappingURL=getActivationStart.js.map\n","import { WINDOW } from '../../types.js';\nimport { generateUniqueID } from './generateUniqueID.js';\nimport { getActivationStart } from './getActivationStart.js';\nimport { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst initMetric = (name, value) => {\n const navEntry = getNavigationEntry();\n let navigationType = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else {\n navigationType = navEntry.type.replace(/_/g, '-') ;\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n\nexport { initMetric };\n//# sourceMappingURL=initMetric.js.map\n","/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nconst observe = (\n type,\n callback,\n opts,\n) => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n callback(list.getEntries() );\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) ,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n\nexport { observe };\n//# sourceMappingURL=observe.js.map\n","import { WINDOW } from '../../types.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst onHidden = (cb, once) => {\n const onHiddenOrPageHide = (event) => {\n if (event.type === 'pagehide' || WINDOW.document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n\nexport { onHidden };\n//# sourceMappingURL=onHidden.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Calculates the [CLS](https://web.dev/cls/) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/cls/#layout-shift-score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nconst onCLS = (onReport) => {\n const metric = initMetric('CLS', 0);\n let report;\n\n let sessionValue = 0;\n let sessionEntries = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\n const handleEntries = (entries) => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = () => {\n handleEntries(po.takeRecords() );\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n\nexport { onCLS };\n//# sourceMappingURL=getCLS.js.map\n","import { WINDOW } from '../../types.js';\nimport { onHidden } from './onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = () => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst trackChanges = () => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nconst getVisibilityWatcher = (\n\n) => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n\nexport { getVisibilityWatcher };\n//# sourceMappingURL=getVisibilityWatcher.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Calculates the [FID](https://web.dev/fid/) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nconst onFID = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report;\n\n const handleEntry = (entry) => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries) => {\n (entries ).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() );\n po.disconnect();\n }, true);\n }\n};\n\nexport { onFID };\n//# sourceMappingURL=getFID.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst reportedMetricIDs = {};\n\n/**\n * Calculates the [LCP](https://web.dev/lcp/) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n */\nconst onLCP = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report;\n\n const handleEntries = (entries) => {\n const lastEntry = entries[entries.length - 1] ;\n if (lastEntry) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = () => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() );\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n\nexport { onLCP };\n//# sourceMappingURL=getLCP.js.map\n","/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nfunction _startChild(transaction, { startTimestamp, ...ctx }) {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n\nexport { _startChild, isMeasurementValue };\n//# sourceMappingURL=utils.js.map\n","import { getActiveTransaction } from '@sentry/core';\nimport { browserPerformanceTimeOrigin, logger, htmlTreeAsString } from '@sentry/utils';\nimport { WINDOW } from '../types.js';\nimport { onCLS } from '../web-vitals/getCLS.js';\nimport { onFID } from '../web-vitals/getFID.js';\nimport { onLCP } from '../web-vitals/getLCP.js';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher.js';\nimport { observe } from '../web-vitals/lib/observe.js';\nimport { _startChild, isMeasurementValue } from './utils.js';\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time) {\n return time / 1000;\n}\n\nfunction getBrowserPerformanceAPI() {\n return WINDOW && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor = 0;\n\nlet _measurements = {};\nlet _lcpEntry;\nlet _clsEntry;\n\n/**\n * Start tracking web vitals\n *\n * @returns A function that forces web vitals collection\n */\nfunction startTrackingWebVitals() {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin) {\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n\n return () => {\n if (clsCallback) {\n clsCallback();\n }\n if (lcpCallback) {\n lcpCallback();\n }\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nfunction startTrackingLongTasks() {\n const entryHandler = (entries) => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() ;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n };\n\n observe('longtask', entryHandler);\n}\n\n/**\n * Start tracking interaction events.\n */\nfunction startTrackingInteractions() {\n const entryHandler = (entries) => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() ;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n }\n };\n\n observe('event', entryHandler, { durationThreshold: 0 });\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS() {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n return onCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry ;\n });\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP() {\n return onLCP(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry ;\n });\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID() {\n onFID(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin );\n const startTime = msToSec(entry.startTime);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\n/** Add performance related spans to a transaction */\nfunction addPerformanceEntries(transaction) {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n let responseStartTimestamp;\n let requestStartTimestamp;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n const resourceName = (entry.name ).replace(WINDOW.location.origin, '');\n _addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n break;\n }\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000,\n unit: 'millisecond',\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n _measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000,\n unit: 'millisecond',\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n const delta = normalizedValue - oldValue;\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n startTimestamp: fidMark.value,\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n transaction.setMeasurement(\n measurementName,\n _measurements[measurementName].value,\n _measurements[measurementName].unit,\n );\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nfunction _addMeasureSpans(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n startTime,\n duration,\n timeOrigin,\n) {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name ,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType ,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction, entry, timeOrigin) {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n event,\n timeOrigin,\n description,\n eventEnd,\n) {\n const end = eventEnd ? (entry[eventEnd] ) : (entry[`${event}End`] );\n const start = entry[`${event}Start`] ;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction, entry, timeOrigin) {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart ),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd ),\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart ),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd ),\n });\n}\n\n/** Create resource-related spans */\nfunction _addResourceSpans(\n transaction,\n entry,\n resourceName,\n startTime,\n duration,\n timeOrigin,\n) {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data = {};\n if ('transferSize' in entry) {\n data['Transfer Size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['Encoded Body Size'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['Decoded Body Size'] = entry.decodedBodySize;\n }\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction) {\n const navigator = WINDOW.navigator ;\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction) {\n if (_lcpEntry) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nexport { _addMeasureSpans, _addResourceSpans, addPerformanceEntries, startTrackingInteractions, startTrackingLongTasks, startTrackingWebVitals };\n//# sourceMappingURL=index.js.map\n","import { hasTracingEnabled, getCurrentHub } from '@sentry/core';\nimport { addInstrumentationHandler, dynamicSamplingContextToSentryBaggageHeader, isInstanceOf, BAGGAGE_HEADER_NAME, SENTRY_XHR_DATA_KEY, stringMatchesSomePattern } from '@sentry/utils';\n\n/* eslint-disable max-lines */\n\nconst DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\//];\n\n/** Options for Request Instrumentation */\n\nconst defaultRequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nfunction instrumentOutgoingRequests(_options) {\n // eslint-disable-next-line deprecation/deprecation\n const { traceFetch, traceXHR, tracePropagationTargets, tracingOrigins, shouldCreateSpanForRequest } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url) =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans = {};\n\n if (traceFetch) {\n addInstrumentationHandler('fetch', (handlerData) => {\n fetchCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler('xhr', (handlerData) => {\n xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n });\n }\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nfunction shouldAttachHeaders(url, tracePropagationTargets) {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track fetch request spans\n */\nfunction fetchCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const span = currentSpan.startChild({\n data: {\n ...handlerData.fetchData,\n type: 'fetch',\n },\n description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`,\n op: 'http.client',\n });\n\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n\n const request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options = handlerData.args[1];\n\n if (shouldAttachHeaders(handlerData.fetchData.url)) {\n options.headers = addTracingHeadersToFetchRequest(\n request,\n activeTransaction.getDynamicSamplingContext(),\n span,\n options,\n );\n }\n }\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers\n */\nfunction addTracingHeadersToFetchRequest(\n request, // unknown is actually type Request but we can't export DOM types from this package,\n dynamicSamplingContext,\n span,\n options\n\n,\n) {\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n const sentryTraceHeader = span.toTraceparent();\n\n const headers =\n typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request ).headers : options.headers;\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers );\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders ;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push([BAGGAGE_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders ;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers ),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\n/**\n * Create and track xhr request spans\n */\nfunction xhrCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (\n !hasTracingEnabled() ||\n (xhr && xhr.__sentry_own_request__) ||\n !(xhr && sentryXhrData && shouldCreateSpan(sentryXhrData.url))\n ) {\n return;\n }\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n span.setHttpStatus(sentryXhrData.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return;\n }\n\n const currentScope = getCurrentHub().getScope();\n const currentSpan = currentScope && currentScope.getSpan();\n const activeTransaction = currentSpan && currentSpan.transaction;\n\n if (currentSpan && activeTransaction) {\n const span = currentSpan.startChild({\n data: {\n ...sentryXhrData.data,\n type: 'xhr',\n method: sentryXhrData.method,\n url: sentryXhrData.url,\n },\n description: `${sentryXhrData.method} ${sentryXhrData.url}`,\n op: 'http.client',\n });\n\n xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url)) {\n try {\n xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n\n const dynamicSamplingContext = activeTransaction.getDynamicSamplingContext();\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n xhr.setRequestHeader(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}\n\nexport { DEFAULT_TRACE_PROPAGATION_TARGETS, addTracingHeadersToFetchRequest, defaultRequestInstrumentationOptions, fetchCallback, instrumentOutgoingRequests, shouldAttachHeaders, xhrCallback };\n//# sourceMappingURL=request.js.map\n","import { logger, browserPerformanceTimeOrigin, addInstrumentationHandler } from '@sentry/utils';\nimport { WINDOW } from './types.js';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nfunction instrumentRoutingWithDefaults(\n customStartTransaction,\n startTransactionOnPageLoad = true,\n startTransactionOnLocationChange = true,\n) {\n if (!WINDOW || !WINDOW.location) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl = WINDOW.location.href;\n\n let activeTransaction;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin\n startTimestamp: browserPerformanceTimeOrigin,\n op: 'pageload',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler('history', ({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n\nexport { instrumentRoutingWithDefaults };\n//# sourceMappingURL=router.js.map\n","import { TRACING_DEFAULTS, addTracingExtensions, extractTraceparentData, startIdleTransaction, getActiveTransaction } from '@sentry/core';\nimport { logger, baggageHeaderToDynamicSamplingContext, getDomElement } from '@sentry/utils';\nimport { registerBackgroundTabDetection } from './backgroundtab.js';\nimport { startTrackingWebVitals, startTrackingLongTasks, startTrackingInteractions, addPerformanceEntries } from './metrics/index.js';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request.js';\nimport { instrumentRoutingWithDefaults } from './router.js';\nimport { WINDOW } from './types.js';\n\nconst BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: true,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nclass BrowserTracing {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n\n /**\n * @inheritDoc\n */\n __init() {this.name = BROWSER_TRACING_INTEGRATION_ID;}\n\n constructor(_options) {BrowserTracing.prototype.__init.call(this);\n addTracingExtensions();\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n this._getCurrentHub = getCurrentHub;\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n _experiments,\n } = this.options;\n\n instrumentRouting(\n (context) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n });\n }\n\n /** Create routing idle transaction. */\n _createRouteTransaction(context) {\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n const sentryTraceMetaTagValue = isPageloadTransaction ? getMetaContent('sentry-trace') : null;\n const baggageMetaTagValue = isPageloadTransaction ? getMetaContent('baggage') : null;\n\n const traceParentData = sentryTraceMetaTagValue ? extractTraceparentData(sentryTraceMetaTagValue) : undefined;\n const dynamicSamplingContext = baggageMetaTagValue\n ? baggageHeaderToDynamicSamplingContext(baggageMetaTagValue)\n : undefined;\n\n const expandedContext = {\n ...context,\n ...traceParentData,\n metadata: {\n ...context.metadata,\n dynamicSamplingContext: traceParentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n trimEnd: true,\n };\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? { ...finalContext.metadata, source: 'custom' }\n : finalContext.metadata;\n\n this._latestRouteName = finalContext.name;\n this._latestRouteSource = finalContext.metadata && finalContext.metadata.source;\n\n if (finalContext.sampled === false) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction ;\n }\n\n /** Start listener for interaction transactions */\n _registerInteractionListener() {\n let inflightInteractionTransaction;\n const registerInteractionTransaction = () => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.finish();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRouteName) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context = {\n name: this._latestRouteName,\n op,\n trimEnd: true,\n metadata: {\n source: this._latestRouteSource || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n });\n }\n}\n\n/** Returns the value of a meta tag */\nfunction getMetaContent(metaName) {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : null;\n}\n\nexport { BROWSER_TRACING_INTEGRATION_ID, BrowserTracing, getMetaContent };\n//# sourceMappingURL=browsertracing.js.map\n","const DEFAULT_HOOKS = ['activate', 'mount', 'update'];\n\nexport { DEFAULT_HOOKS };\n//# sourceMappingURL=constants.js.map\n","// Vendored from https://github.com/vuejs/vue/blob/612fb89547711cacb030a3893a0065b785802860/src/core/util/debug.js\n// with types only changes.\n\n// The MIT License (MIT)\n\n// Copyright (c) 2013-present, Yuxi (Evan) You\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nconst classifyRE = /(?:^|[-_])(\\w)/g;\nconst classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');\n\nconst ROOT_COMPONENT_NAME = '';\nconst ANONYMOUS_COMPONENT_NAME = '';\n\nconst repeat = (str, n) => {\n // string.repeat() is not supported by IE11, we fall back to just using the string in that case\n // eslint-disable-next-line @sentry-internal/sdk/no-unsupported-es6-methods\n return str.repeat ? str.repeat(n) : str;\n};\n\nconst formatComponentName = (vm, includeFile) => {\n if (!vm) {\n return ANONYMOUS_COMPONENT_NAME;\n }\n\n if (vm.$root === vm) {\n return ROOT_COMPONENT_NAME;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5204 $options can be undefined\n if (!vm.$options) {\n return ANONYMOUS_COMPONENT_NAME;\n }\n\n const options = vm.$options;\n\n let name = options.name || options._componentTag;\n const file = options.__file;\n if (!name && file) {\n const match = file.match(/([^/\\\\]+)\\.vue$/);\n if (match) {\n name = match[1];\n }\n }\n\n return (\n (name ? `<${classify(name)}>` : ANONYMOUS_COMPONENT_NAME) + (file && includeFile !== false ? ` at ${file}` : '')\n );\n};\n\nconst generateComponentTrace = (vm) => {\n if (vm && (vm._isVue || vm.__isVue) && vm.$parent) {\n const tree = [];\n let currentRecursiveSequence = 0;\n while (vm) {\n if (tree.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const last = tree[tree.length - 1] ;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (last.constructor === vm.constructor) {\n currentRecursiveSequence++;\n vm = vm.$parent; // eslint-disable-line no-param-reassign\n continue;\n } else if (currentRecursiveSequence > 0) {\n tree[tree.length - 1] = [last, currentRecursiveSequence];\n currentRecursiveSequence = 0;\n }\n }\n tree.push(vm);\n vm = vm.$parent; // eslint-disable-line no-param-reassign\n }\n\n const formattedTree = tree\n .map(\n (vm, i) =>\n `${\n (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) +\n (Array.isArray(vm)\n ? `${formatComponentName(vm[0])}... (${vm[1]} recursive calls)`\n : formatComponentName(vm))\n }`,\n )\n .join('\\n');\n\n return `\\n\\nfound in\\n\\n${formattedTree}`;\n }\n\n return `\\n\\n(found in ${formatComponentName(vm)})`;\n};\n\nexport { formatComponentName, generateComponentTrace };\n//# sourceMappingURL=components.js.map\n","import { getCurrentHub } from '@sentry/browser';\nimport { formatComponentName, generateComponentTrace } from './vendor/components.js';\n\nconst attachErrorHandler = (app, options) => {\n const { errorHandler, warnHandler, silent } = app.config;\n\n app.config.errorHandler = (error, vm, lifecycleHook) => {\n const componentName = formatComponentName(vm, false);\n const trace = vm ? generateComponentTrace(vm) : '';\n const metadata = {\n componentName,\n lifecycleHook,\n trace,\n };\n\n if (options.attachProps && vm) {\n // Vue2 - $options.propsData\n // Vue3 - $props\n if (vm.$options && vm.$options.propsData) {\n metadata.propsData = vm.$options.propsData;\n } else if (vm.$props) {\n metadata.propsData = vm.$props;\n }\n }\n\n // Capture exception in the next event loop, to make sure that all breadcrumbs are recorded in time.\n setTimeout(() => {\n getCurrentHub().withScope(scope => {\n scope.setContext('vue', metadata);\n getCurrentHub().captureException(error);\n });\n });\n\n if (typeof errorHandler === 'function') {\n (errorHandler ).call(app, error, vm, lifecycleHook);\n }\n\n if (options.logErrors) {\n const hasConsole = typeof console !== 'undefined';\n const message = `Error in ${lifecycleHook}: \"${error && error.toString()}\"`;\n\n if (warnHandler) {\n (warnHandler ).call(null, message, vm, trace);\n } else if (hasConsole && !silent) {\n // eslint-disable-next-line no-console\n console.error(`[Vue warn]: ${message}${trace}`);\n }\n }\n };\n};\n\nexport { attachErrorHandler };\n//# sourceMappingURL=errorhandler.js.map\n","import { getCurrentHub } from '@sentry/browser';\nimport { logger, timestampInSeconds } from '@sentry/utils';\nimport { DEFAULT_HOOKS } from './constants.js';\nimport { formatComponentName } from './vendor/components.js';\n\nconst VUE_OP = 'ui.vue';\n\n// Mappings from operation to corresponding lifecycle hook.\nconst HOOKS = {\n activate: ['activated', 'deactivated'],\n create: ['beforeCreate', 'created'],\n destroy: ['beforeDestroy', 'destroyed'],\n mount: ['beforeMount', 'mounted'],\n update: ['beforeUpdate', 'updated'],\n};\n\n/** Grabs active transaction off scope, if any */\nfunction getActiveTransaction() {\n const scope = getCurrentHub().getScope();\n return scope && scope.getTransaction();\n}\n\n/** Finish top-level span and activity with a debounce configured using `timeout` option */\nfunction finishRootSpan(vm, timestamp, timeout) {\n if (vm.$_sentryRootSpanTimer) {\n clearTimeout(vm.$_sentryRootSpanTimer);\n }\n\n vm.$_sentryRootSpanTimer = setTimeout(() => {\n if (vm.$root && vm.$root.$_sentryRootSpan) {\n vm.$root.$_sentryRootSpan.finish(timestamp);\n vm.$root.$_sentryRootSpan = undefined;\n }\n }, timeout);\n}\n\nconst createTracingMixins = (options) => {\n const hooks = (options.hooks || [])\n .concat(DEFAULT_HOOKS)\n // Removing potential duplicates\n .filter((value, index, self) => self.indexOf(value) === index);\n\n const mixins = {};\n\n for (const operation of hooks) {\n // Retrieve corresponding hooks from Vue lifecycle.\n // eg. mount => ['beforeMount', 'mounted']\n const internalHooks = HOOKS[operation];\n if (!internalHooks) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Unknown hook: ${operation}`);\n continue;\n }\n\n for (const internalHook of internalHooks) {\n mixins[internalHook] = function () {\n const isRoot = this.$root === this;\n\n if (isRoot) {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n this.$_sentryRootSpan =\n this.$_sentryRootSpan ||\n activeTransaction.startChild({\n description: 'Application Render',\n op: `${VUE_OP}.render`,\n });\n }\n }\n\n // Skip components that we don't want to track to minimize the noise and give a more granular control to the user\n const name = formatComponentName(this, false);\n const shouldTrack = Array.isArray(options.trackComponents)\n ? options.trackComponents.indexOf(name) > -1\n : options.trackComponents;\n\n // We always want to track root component\n if (!isRoot && !shouldTrack) {\n return;\n }\n\n this.$_sentrySpans = this.$_sentrySpans || {};\n\n // Start a new span if current hook is a 'before' hook.\n // Otherwise, retrieve the current span and finish it.\n if (internalHook == internalHooks[0]) {\n const activeTransaction = (this.$root && this.$root.$_sentryRootSpan) || getActiveTransaction();\n if (activeTransaction) {\n // Cancel old span for this hook operation in case it didn't get cleaned up. We're not actually sure if it\n // will ever be the case that cleanup hooks re not called, but we had users report that spans didn't get\n // finished so we finish the span before starting a new one, just to be sure.\n const oldSpan = this.$_sentrySpans[operation];\n if (oldSpan && !oldSpan.endTimestamp) {\n oldSpan.finish();\n }\n\n this.$_sentrySpans[operation] = activeTransaction.startChild({\n description: `Vue <${name}>`,\n op: `${VUE_OP}.${operation}`,\n });\n }\n } else {\n // The span should already be added via the first handler call (in the 'before' hook)\n const span = this.$_sentrySpans[operation];\n // The before hook did not start the tracking span, so the span was not added.\n // This is probably because it happened before there is an active transaction\n if (!span) return;\n span.finish();\n\n finishRootSpan(this, timestampInSeconds(), options.timeout);\n }\n };\n }\n }\n\n return mixins;\n};\n\nexport { createTracingMixins, getActiveTransaction };\n//# sourceMappingURL=tracing.js.map\n","import { SDK_VERSION, init as init$1 } from '@sentry/browser';\nimport { hasTracingEnabled } from '@sentry/core';\nimport { GLOBAL_OBJ, arrayify } from '@sentry/utils';\nimport { DEFAULT_HOOKS } from './constants.js';\nimport { attachErrorHandler } from './errorhandler.js';\nimport { createTracingMixins } from './tracing.js';\n\nconst globalWithVue = GLOBAL_OBJ ;\n\nconst DEFAULT_CONFIG = {\n Vue: globalWithVue.Vue,\n attachProps: true,\n logErrors: true,\n hooks: DEFAULT_HOOKS,\n timeout: 2000,\n trackComponents: false,\n _metadata: {\n sdk: {\n name: 'sentry.javascript.vue',\n packages: [\n {\n name: 'npm:@sentry/vue',\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n },\n },\n};\n\n/**\n * Inits the Vue SDK\n */\nfunction init(\n config = {},\n) {\n const options = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n init$1(options);\n\n if (!options.Vue && !options.app) {\n // eslint-disable-next-line no-console\n console.warn(\n `[@sentry/vue]: Misconfigured SDK. Vue specific errors will not be captured.\nUpdate your \\`Sentry.init\\` call with an appropriate config option:\n\\`app\\` (Application Instance - Vue 3) or \\`Vue\\` (Vue Constructor - Vue 2).`,\n );\n return;\n }\n\n if (options.app) {\n const apps = arrayify(options.app);\n apps.forEach(app => vueInit(app, options));\n } else if (options.Vue) {\n vueInit(options.Vue, options);\n }\n}\n\nconst vueInit = (app, options) => {\n // Check app is not mounted yet - should be mounted _after_ init()!\n // This is _somewhat_ private, but in the case that this doesn't exist we simply ignore it\n // See: https://github.com/vuejs/core/blob/eb2a83283caa9de0a45881d860a3cbd9d0bdd279/packages/runtime-core/src/component.ts#L394\n const appWithInstance = app\n\n;\n\n const isMounted = appWithInstance._instance && appWithInstance._instance.isMounted;\n if (isMounted === true) {\n // eslint-disable-next-line no-console\n console.warn(\n '[@sentry/vue]: Misconfigured SDK. Vue app is already mounted. Make sure to call `app.mount()` after `Sentry.init()`.',\n );\n }\n\n attachErrorHandler(app, options);\n\n if (hasTracingEnabled(options)) {\n app.mixin(\n createTracingMixins({\n ...options,\n ...options.tracingOptions,\n }),\n );\n }\n};\n\nexport { init };\n//# sourceMappingURL=sdk.js.map\n","// These are here so that the bundler picks them up and processes them\nimport \"@/modules/core/styles/index.scss\";\nimport \"./styles/index.scss\";\n\n//@ts-ignore\nimport 'virtual:svg-icons-register';\n\nimport { createApp } from 'vue';\nimport configureAxios from \"./config/axios\";\nimport Pinia from \"./stores\";\nimport App from './website.vue';\n\nimport * as Sentry from \"@sentry/vue\";\n\nconst app = createApp(App);\n\nif (import.meta.env.MODE === 'production') {\n Sentry.init({\n app,\n dsn: \"https://0736167ad5a64520922b47660a836ed3@o4504790555623424.ingest.sentry.io/4505039762161664\",\n environment: import.meta.env.MODE,\n integrations: [\n new Sentry.BrowserTracing({\n tracePropagationTargets: [\"localhost\", \"https://test.e-greetingtnb.com/\", \"https://www.e-greetingtnb.com/\", /^\\//],\n }),\n new Sentry.Replay(),\n ],\n // Set tracesSampleRate to 1.0 to capture 100%\n // of transactions for performance monitoring.\n // We recommend adjusting this value in production\n tracesSampleRate: 0.5,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n });\n}\n\n// Pinia needs the app to use as a symbol to ensure it is a singleton \napp.use(Pinia);\n\n// As we configure our axios interceptor using values from Pinia, we invoke it after the line above\nconfigureAxios();\n\napp.mount('#app');"],"file":"assets/website.js"}