publicUtils.cjs 162 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193
  1. 'use strict';
  2. var path$3 = require('node:path');
  3. var node_url = require('node:url');
  4. var fs$1 = require('node:fs');
  5. var esbuild = require('esbuild');
  6. var node_module = require('node:module');
  7. var require$$0 = require('tty');
  8. var require$$1 = require('util');
  9. var require$$0$1 = require('path');
  10. var require$$0$2 = require('crypto');
  11. var fs$2 = require('fs');
  12. var readline = require('node:readline');
  13. var require$$2 = require('os');
  14. var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
  15. const { version: version$2 } = JSON.parse(fs$1.readFileSync(new URL('../../package.json', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))).toString());
  16. const VERSION = version$2;
  17. /**
  18. * Prefix for resolved fs paths, since windows paths may not be valid as URLs.
  19. */
  20. const FS_PREFIX = `/@fs/`;
  21. const VITE_PACKAGE_DIR = path$3.resolve(
  22. // import.meta.url is `dist/node/constants.js` after bundle
  23. node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))), '../../..');
  24. const CLIENT_ENTRY = path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/client.mjs');
  25. path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/env.mjs');
  26. path$3.dirname(CLIENT_ENTRY);
  27. const comma = ','.charCodeAt(0);
  28. const semicolon = ';'.charCodeAt(0);
  29. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  30. const intToChar = new Uint8Array(64); // 64 possible chars.
  31. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  32. for (let i = 0; i < chars.length; i++) {
  33. const c = chars.charCodeAt(i);
  34. intToChar[i] = c;
  35. charToInt[c] = i;
  36. }
  37. // Provide a fallback for older environments.
  38. const td = typeof TextDecoder !== 'undefined'
  39. ? /* #__PURE__ */ new TextDecoder()
  40. : typeof Buffer !== 'undefined'
  41. ? {
  42. decode(buf) {
  43. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  44. return out.toString();
  45. },
  46. }
  47. : {
  48. decode(buf) {
  49. let out = '';
  50. for (let i = 0; i < buf.length; i++) {
  51. out += String.fromCharCode(buf[i]);
  52. }
  53. return out;
  54. },
  55. };
  56. function encode(decoded) {
  57. const state = new Int32Array(5);
  58. const bufLength = 1024 * 16;
  59. const subLength = bufLength - 36;
  60. const buf = new Uint8Array(bufLength);
  61. const sub = buf.subarray(0, subLength);
  62. let pos = 0;
  63. let out = '';
  64. for (let i = 0; i < decoded.length; i++) {
  65. const line = decoded[i];
  66. if (i > 0) {
  67. if (pos === bufLength) {
  68. out += td.decode(buf);
  69. pos = 0;
  70. }
  71. buf[pos++] = semicolon;
  72. }
  73. if (line.length === 0)
  74. continue;
  75. state[0] = 0;
  76. for (let j = 0; j < line.length; j++) {
  77. const segment = line[j];
  78. // We can push up to 5 ints, each int can take at most 7 chars, and we
  79. // may push a comma.
  80. if (pos > subLength) {
  81. out += td.decode(sub);
  82. buf.copyWithin(0, subLength, pos);
  83. pos -= subLength;
  84. }
  85. if (j > 0)
  86. buf[pos++] = comma;
  87. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  88. if (segment.length === 1)
  89. continue;
  90. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  91. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  92. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  93. if (segment.length === 4)
  94. continue;
  95. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  96. }
  97. }
  98. return out + td.decode(buf.subarray(0, pos));
  99. }
  100. function encodeInteger(buf, pos, state, segment, j) {
  101. const next = segment[j];
  102. let num = next - state[j];
  103. state[j] = next;
  104. num = num < 0 ? (-num << 1) | 1 : num << 1;
  105. do {
  106. let clamped = num & 0b011111;
  107. num >>>= 5;
  108. if (num > 0)
  109. clamped |= 0b100000;
  110. buf[pos++] = intToChar[clamped];
  111. } while (num > 0);
  112. return pos;
  113. }
  114. function getDefaultExportFromCjs (x) {
  115. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  116. }
  117. var picocolors = {exports: {}};
  118. let tty = require$$0;
  119. let isColorSupported =
  120. !("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
  121. ("FORCE_COLOR" in process.env ||
  122. process.argv.includes("--color") ||
  123. process.platform === "win32" ||
  124. (tty.isatty(1) && process.env.TERM !== "dumb") ||
  125. "CI" in process.env);
  126. let formatter =
  127. (open, close, replace = open) =>
  128. input => {
  129. let string = "" + input;
  130. let index = string.indexOf(close, open.length);
  131. return ~index
  132. ? open + replaceClose(string, close, replace, index) + close
  133. : open + string + close
  134. };
  135. let replaceClose = (string, close, replace, index) => {
  136. let start = string.substring(0, index) + replace;
  137. let end = string.substring(index + close.length);
  138. let nextIndex = end.indexOf(close);
  139. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  140. };
  141. let createColors = (enabled = isColorSupported) => ({
  142. isColorSupported: enabled,
  143. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  144. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  145. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  146. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  147. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  148. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  149. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  150. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  151. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  152. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  153. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  154. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  155. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  156. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  157. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  158. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  159. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  160. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  161. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  162. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  163. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  164. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  165. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  166. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  167. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  168. });
  169. picocolors.exports = createColors();
  170. picocolors.exports.createColors = createColors;
  171. var picocolorsExports = picocolors.exports;
  172. var colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  173. var src = {exports: {}};
  174. var browser$1 = {exports: {}};
  175. /**
  176. * Helpers.
  177. */
  178. var ms;
  179. var hasRequiredMs;
  180. function requireMs () {
  181. if (hasRequiredMs) return ms;
  182. hasRequiredMs = 1;
  183. var s = 1000;
  184. var m = s * 60;
  185. var h = m * 60;
  186. var d = h * 24;
  187. var w = d * 7;
  188. var y = d * 365.25;
  189. /**
  190. * Parse or format the given `val`.
  191. *
  192. * Options:
  193. *
  194. * - `long` verbose formatting [false]
  195. *
  196. * @param {String|Number} val
  197. * @param {Object} [options]
  198. * @throws {Error} throw an error if val is not a non-empty string or a number
  199. * @return {String|Number}
  200. * @api public
  201. */
  202. ms = function(val, options) {
  203. options = options || {};
  204. var type = typeof val;
  205. if (type === 'string' && val.length > 0) {
  206. return parse(val);
  207. } else if (type === 'number' && isFinite(val)) {
  208. return options.long ? fmtLong(val) : fmtShort(val);
  209. }
  210. throw new Error(
  211. 'val is not a non-empty string or a valid number. val=' +
  212. JSON.stringify(val)
  213. );
  214. };
  215. /**
  216. * Parse the given `str` and return milliseconds.
  217. *
  218. * @param {String} str
  219. * @return {Number}
  220. * @api private
  221. */
  222. function parse(str) {
  223. str = String(str);
  224. if (str.length > 100) {
  225. return;
  226. }
  227. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  228. str
  229. );
  230. if (!match) {
  231. return;
  232. }
  233. var n = parseFloat(match[1]);
  234. var type = (match[2] || 'ms').toLowerCase();
  235. switch (type) {
  236. case 'years':
  237. case 'year':
  238. case 'yrs':
  239. case 'yr':
  240. case 'y':
  241. return n * y;
  242. case 'weeks':
  243. case 'week':
  244. case 'w':
  245. return n * w;
  246. case 'days':
  247. case 'day':
  248. case 'd':
  249. return n * d;
  250. case 'hours':
  251. case 'hour':
  252. case 'hrs':
  253. case 'hr':
  254. case 'h':
  255. return n * h;
  256. case 'minutes':
  257. case 'minute':
  258. case 'mins':
  259. case 'min':
  260. case 'm':
  261. return n * m;
  262. case 'seconds':
  263. case 'second':
  264. case 'secs':
  265. case 'sec':
  266. case 's':
  267. return n * s;
  268. case 'milliseconds':
  269. case 'millisecond':
  270. case 'msecs':
  271. case 'msec':
  272. case 'ms':
  273. return n;
  274. default:
  275. return undefined;
  276. }
  277. }
  278. /**
  279. * Short format for `ms`.
  280. *
  281. * @param {Number} ms
  282. * @return {String}
  283. * @api private
  284. */
  285. function fmtShort(ms) {
  286. var msAbs = Math.abs(ms);
  287. if (msAbs >= d) {
  288. return Math.round(ms / d) + 'd';
  289. }
  290. if (msAbs >= h) {
  291. return Math.round(ms / h) + 'h';
  292. }
  293. if (msAbs >= m) {
  294. return Math.round(ms / m) + 'm';
  295. }
  296. if (msAbs >= s) {
  297. return Math.round(ms / s) + 's';
  298. }
  299. return ms + 'ms';
  300. }
  301. /**
  302. * Long format for `ms`.
  303. *
  304. * @param {Number} ms
  305. * @return {String}
  306. * @api private
  307. */
  308. function fmtLong(ms) {
  309. var msAbs = Math.abs(ms);
  310. if (msAbs >= d) {
  311. return plural(ms, msAbs, d, 'day');
  312. }
  313. if (msAbs >= h) {
  314. return plural(ms, msAbs, h, 'hour');
  315. }
  316. if (msAbs >= m) {
  317. return plural(ms, msAbs, m, 'minute');
  318. }
  319. if (msAbs >= s) {
  320. return plural(ms, msAbs, s, 'second');
  321. }
  322. return ms + ' ms';
  323. }
  324. /**
  325. * Pluralization helper.
  326. */
  327. function plural(ms, msAbs, n, name) {
  328. var isPlural = msAbs >= n * 1.5;
  329. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  330. }
  331. return ms;
  332. }
  333. var common;
  334. var hasRequiredCommon;
  335. function requireCommon () {
  336. if (hasRequiredCommon) return common;
  337. hasRequiredCommon = 1;
  338. /**
  339. * This is the common logic for both the Node.js and web browser
  340. * implementations of `debug()`.
  341. */
  342. function setup(env) {
  343. createDebug.debug = createDebug;
  344. createDebug.default = createDebug;
  345. createDebug.coerce = coerce;
  346. createDebug.disable = disable;
  347. createDebug.enable = enable;
  348. createDebug.enabled = enabled;
  349. createDebug.humanize = requireMs();
  350. createDebug.destroy = destroy;
  351. Object.keys(env).forEach(key => {
  352. createDebug[key] = env[key];
  353. });
  354. /**
  355. * The currently active debug mode names, and names to skip.
  356. */
  357. createDebug.names = [];
  358. createDebug.skips = [];
  359. /**
  360. * Map of special "%n" handling functions, for the debug "format" argument.
  361. *
  362. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  363. */
  364. createDebug.formatters = {};
  365. /**
  366. * Selects a color for a debug namespace
  367. * @param {String} namespace The namespace string for the debug instance to be colored
  368. * @return {Number|String} An ANSI color code for the given namespace
  369. * @api private
  370. */
  371. function selectColor(namespace) {
  372. let hash = 0;
  373. for (let i = 0; i < namespace.length; i++) {
  374. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  375. hash |= 0; // Convert to 32bit integer
  376. }
  377. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  378. }
  379. createDebug.selectColor = selectColor;
  380. /**
  381. * Create a debugger with the given `namespace`.
  382. *
  383. * @param {String} namespace
  384. * @return {Function}
  385. * @api public
  386. */
  387. function createDebug(namespace) {
  388. let prevTime;
  389. let enableOverride = null;
  390. let namespacesCache;
  391. let enabledCache;
  392. function debug(...args) {
  393. // Disabled?
  394. if (!debug.enabled) {
  395. return;
  396. }
  397. const self = debug;
  398. // Set `diff` timestamp
  399. const curr = Number(new Date());
  400. const ms = curr - (prevTime || curr);
  401. self.diff = ms;
  402. self.prev = prevTime;
  403. self.curr = curr;
  404. prevTime = curr;
  405. args[0] = createDebug.coerce(args[0]);
  406. if (typeof args[0] !== 'string') {
  407. // Anything else let's inspect with %O
  408. args.unshift('%O');
  409. }
  410. // Apply any `formatters` transformations
  411. let index = 0;
  412. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  413. // If we encounter an escaped % then don't increase the array index
  414. if (match === '%%') {
  415. return '%';
  416. }
  417. index++;
  418. const formatter = createDebug.formatters[format];
  419. if (typeof formatter === 'function') {
  420. const val = args[index];
  421. match = formatter.call(self, val);
  422. // Now we need to remove `args[index]` since it's inlined in the `format`
  423. args.splice(index, 1);
  424. index--;
  425. }
  426. return match;
  427. });
  428. // Apply env-specific formatting (colors, etc.)
  429. createDebug.formatArgs.call(self, args);
  430. const logFn = self.log || createDebug.log;
  431. logFn.apply(self, args);
  432. }
  433. debug.namespace = namespace;
  434. debug.useColors = createDebug.useColors();
  435. debug.color = createDebug.selectColor(namespace);
  436. debug.extend = extend;
  437. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  438. Object.defineProperty(debug, 'enabled', {
  439. enumerable: true,
  440. configurable: false,
  441. get: () => {
  442. if (enableOverride !== null) {
  443. return enableOverride;
  444. }
  445. if (namespacesCache !== createDebug.namespaces) {
  446. namespacesCache = createDebug.namespaces;
  447. enabledCache = createDebug.enabled(namespace);
  448. }
  449. return enabledCache;
  450. },
  451. set: v => {
  452. enableOverride = v;
  453. }
  454. });
  455. // Env-specific initialization logic for debug instances
  456. if (typeof createDebug.init === 'function') {
  457. createDebug.init(debug);
  458. }
  459. return debug;
  460. }
  461. function extend(namespace, delimiter) {
  462. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  463. newDebug.log = this.log;
  464. return newDebug;
  465. }
  466. /**
  467. * Enables a debug mode by namespaces. This can include modes
  468. * separated by a colon and wildcards.
  469. *
  470. * @param {String} namespaces
  471. * @api public
  472. */
  473. function enable(namespaces) {
  474. createDebug.save(namespaces);
  475. createDebug.namespaces = namespaces;
  476. createDebug.names = [];
  477. createDebug.skips = [];
  478. let i;
  479. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  480. const len = split.length;
  481. for (i = 0; i < len; i++) {
  482. if (!split[i]) {
  483. // ignore empty strings
  484. continue;
  485. }
  486. namespaces = split[i].replace(/\*/g, '.*?');
  487. if (namespaces[0] === '-') {
  488. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  489. } else {
  490. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  491. }
  492. }
  493. }
  494. /**
  495. * Disable debug output.
  496. *
  497. * @return {String} namespaces
  498. * @api public
  499. */
  500. function disable() {
  501. const namespaces = [
  502. ...createDebug.names.map(toNamespace),
  503. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  504. ].join(',');
  505. createDebug.enable('');
  506. return namespaces;
  507. }
  508. /**
  509. * Returns true if the given mode name is enabled, false otherwise.
  510. *
  511. * @param {String} name
  512. * @return {Boolean}
  513. * @api public
  514. */
  515. function enabled(name) {
  516. if (name[name.length - 1] === '*') {
  517. return true;
  518. }
  519. let i;
  520. let len;
  521. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  522. if (createDebug.skips[i].test(name)) {
  523. return false;
  524. }
  525. }
  526. for (i = 0, len = createDebug.names.length; i < len; i++) {
  527. if (createDebug.names[i].test(name)) {
  528. return true;
  529. }
  530. }
  531. return false;
  532. }
  533. /**
  534. * Convert regexp to namespace
  535. *
  536. * @param {RegExp} regxep
  537. * @return {String} namespace
  538. * @api private
  539. */
  540. function toNamespace(regexp) {
  541. return regexp.toString()
  542. .substring(2, regexp.toString().length - 2)
  543. .replace(/\.\*\?$/, '*');
  544. }
  545. /**
  546. * Coerce `val`.
  547. *
  548. * @param {Mixed} val
  549. * @return {Mixed}
  550. * @api private
  551. */
  552. function coerce(val) {
  553. if (val instanceof Error) {
  554. return val.stack || val.message;
  555. }
  556. return val;
  557. }
  558. /**
  559. * XXX DO NOT USE. This is a temporary stub function.
  560. * XXX It WILL be removed in the next major release.
  561. */
  562. function destroy() {
  563. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  564. }
  565. createDebug.enable(createDebug.load());
  566. return createDebug;
  567. }
  568. common = setup;
  569. return common;
  570. }
  571. /* eslint-env browser */
  572. var hasRequiredBrowser;
  573. function requireBrowser () {
  574. if (hasRequiredBrowser) return browser$1.exports;
  575. hasRequiredBrowser = 1;
  576. (function (module, exports) {
  577. /**
  578. * This is the web browser implementation of `debug()`.
  579. */
  580. exports.formatArgs = formatArgs;
  581. exports.save = save;
  582. exports.load = load;
  583. exports.useColors = useColors;
  584. exports.storage = localstorage();
  585. exports.destroy = (() => {
  586. let warned = false;
  587. return () => {
  588. if (!warned) {
  589. warned = true;
  590. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  591. }
  592. };
  593. })();
  594. /**
  595. * Colors.
  596. */
  597. exports.colors = [
  598. '#0000CC',
  599. '#0000FF',
  600. '#0033CC',
  601. '#0033FF',
  602. '#0066CC',
  603. '#0066FF',
  604. '#0099CC',
  605. '#0099FF',
  606. '#00CC00',
  607. '#00CC33',
  608. '#00CC66',
  609. '#00CC99',
  610. '#00CCCC',
  611. '#00CCFF',
  612. '#3300CC',
  613. '#3300FF',
  614. '#3333CC',
  615. '#3333FF',
  616. '#3366CC',
  617. '#3366FF',
  618. '#3399CC',
  619. '#3399FF',
  620. '#33CC00',
  621. '#33CC33',
  622. '#33CC66',
  623. '#33CC99',
  624. '#33CCCC',
  625. '#33CCFF',
  626. '#6600CC',
  627. '#6600FF',
  628. '#6633CC',
  629. '#6633FF',
  630. '#66CC00',
  631. '#66CC33',
  632. '#9900CC',
  633. '#9900FF',
  634. '#9933CC',
  635. '#9933FF',
  636. '#99CC00',
  637. '#99CC33',
  638. '#CC0000',
  639. '#CC0033',
  640. '#CC0066',
  641. '#CC0099',
  642. '#CC00CC',
  643. '#CC00FF',
  644. '#CC3300',
  645. '#CC3333',
  646. '#CC3366',
  647. '#CC3399',
  648. '#CC33CC',
  649. '#CC33FF',
  650. '#CC6600',
  651. '#CC6633',
  652. '#CC9900',
  653. '#CC9933',
  654. '#CCCC00',
  655. '#CCCC33',
  656. '#FF0000',
  657. '#FF0033',
  658. '#FF0066',
  659. '#FF0099',
  660. '#FF00CC',
  661. '#FF00FF',
  662. '#FF3300',
  663. '#FF3333',
  664. '#FF3366',
  665. '#FF3399',
  666. '#FF33CC',
  667. '#FF33FF',
  668. '#FF6600',
  669. '#FF6633',
  670. '#FF9900',
  671. '#FF9933',
  672. '#FFCC00',
  673. '#FFCC33'
  674. ];
  675. /**
  676. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  677. * and the Firebug extension (any Firefox version) are known
  678. * to support "%c" CSS customizations.
  679. *
  680. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  681. */
  682. // eslint-disable-next-line complexity
  683. function useColors() {
  684. // NB: In an Electron preload script, document will be defined but not fully
  685. // initialized. Since we know we're in Chrome, we'll just detect this case
  686. // explicitly
  687. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  688. return true;
  689. }
  690. // Internet Explorer and Edge do not support colors.
  691. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  692. return false;
  693. }
  694. // Is webkit? http://stackoverflow.com/a/16459606/376773
  695. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  696. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  697. // Is firebug? http://stackoverflow.com/a/398120/376773
  698. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  699. // Is firefox >= v31?
  700. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  701. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  702. // Double check webkit in userAgent just in case we are in a worker
  703. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  704. }
  705. /**
  706. * Colorize log arguments if enabled.
  707. *
  708. * @api public
  709. */
  710. function formatArgs(args) {
  711. args[0] = (this.useColors ? '%c' : '') +
  712. this.namespace +
  713. (this.useColors ? ' %c' : ' ') +
  714. args[0] +
  715. (this.useColors ? '%c ' : ' ') +
  716. '+' + module.exports.humanize(this.diff);
  717. if (!this.useColors) {
  718. return;
  719. }
  720. const c = 'color: ' + this.color;
  721. args.splice(1, 0, c, 'color: inherit');
  722. // The final "%c" is somewhat tricky, because there could be other
  723. // arguments passed either before or after the %c, so we need to
  724. // figure out the correct index to insert the CSS into
  725. let index = 0;
  726. let lastC = 0;
  727. args[0].replace(/%[a-zA-Z%]/g, match => {
  728. if (match === '%%') {
  729. return;
  730. }
  731. index++;
  732. if (match === '%c') {
  733. // We only are interested in the *last* %c
  734. // (the user may have provided their own)
  735. lastC = index;
  736. }
  737. });
  738. args.splice(lastC, 0, c);
  739. }
  740. /**
  741. * Invokes `console.debug()` when available.
  742. * No-op when `console.debug` is not a "function".
  743. * If `console.debug` is not available, falls back
  744. * to `console.log`.
  745. *
  746. * @api public
  747. */
  748. exports.log = console.debug || console.log || (() => {});
  749. /**
  750. * Save `namespaces`.
  751. *
  752. * @param {String} namespaces
  753. * @api private
  754. */
  755. function save(namespaces) {
  756. try {
  757. if (namespaces) {
  758. exports.storage.setItem('debug', namespaces);
  759. } else {
  760. exports.storage.removeItem('debug');
  761. }
  762. } catch (error) {
  763. // Swallow
  764. // XXX (@Qix-) should we be logging these?
  765. }
  766. }
  767. /**
  768. * Load `namespaces`.
  769. *
  770. * @return {String} returns the previously persisted debug modes
  771. * @api private
  772. */
  773. function load() {
  774. let r;
  775. try {
  776. r = exports.storage.getItem('debug');
  777. } catch (error) {
  778. // Swallow
  779. // XXX (@Qix-) should we be logging these?
  780. }
  781. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  782. if (!r && typeof process !== 'undefined' && 'env' in process) {
  783. r = process.env.DEBUG;
  784. }
  785. return r;
  786. }
  787. /**
  788. * Localstorage attempts to return the localstorage.
  789. *
  790. * This is necessary because safari throws
  791. * when a user disables cookies/localstorage
  792. * and you attempt to access it.
  793. *
  794. * @return {LocalStorage}
  795. * @api private
  796. */
  797. function localstorage() {
  798. try {
  799. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  800. // The Browser also has localStorage in the global context.
  801. return localStorage;
  802. } catch (error) {
  803. // Swallow
  804. // XXX (@Qix-) should we be logging these?
  805. }
  806. }
  807. module.exports = requireCommon()(exports);
  808. const {formatters} = module.exports;
  809. /**
  810. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  811. */
  812. formatters.j = function (v) {
  813. try {
  814. return JSON.stringify(v);
  815. } catch (error) {
  816. return '[UnexpectedJSONParseError]: ' + error.message;
  817. }
  818. };
  819. } (browser$1, browser$1.exports));
  820. return browser$1.exports;
  821. }
  822. var node = {exports: {}};
  823. /**
  824. * Module dependencies.
  825. */
  826. var hasRequiredNode;
  827. function requireNode () {
  828. if (hasRequiredNode) return node.exports;
  829. hasRequiredNode = 1;
  830. (function (module, exports) {
  831. const tty = require$$0;
  832. const util = require$$1;
  833. /**
  834. * This is the Node.js implementation of `debug()`.
  835. */
  836. exports.init = init;
  837. exports.log = log;
  838. exports.formatArgs = formatArgs;
  839. exports.save = save;
  840. exports.load = load;
  841. exports.useColors = useColors;
  842. exports.destroy = util.deprecate(
  843. () => {},
  844. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  845. );
  846. /**
  847. * Colors.
  848. */
  849. exports.colors = [6, 2, 3, 4, 5, 1];
  850. try {
  851. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  852. // eslint-disable-next-line import/no-extraneous-dependencies
  853. const supportsColor = require('supports-color');
  854. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  855. exports.colors = [
  856. 20,
  857. 21,
  858. 26,
  859. 27,
  860. 32,
  861. 33,
  862. 38,
  863. 39,
  864. 40,
  865. 41,
  866. 42,
  867. 43,
  868. 44,
  869. 45,
  870. 56,
  871. 57,
  872. 62,
  873. 63,
  874. 68,
  875. 69,
  876. 74,
  877. 75,
  878. 76,
  879. 77,
  880. 78,
  881. 79,
  882. 80,
  883. 81,
  884. 92,
  885. 93,
  886. 98,
  887. 99,
  888. 112,
  889. 113,
  890. 128,
  891. 129,
  892. 134,
  893. 135,
  894. 148,
  895. 149,
  896. 160,
  897. 161,
  898. 162,
  899. 163,
  900. 164,
  901. 165,
  902. 166,
  903. 167,
  904. 168,
  905. 169,
  906. 170,
  907. 171,
  908. 172,
  909. 173,
  910. 178,
  911. 179,
  912. 184,
  913. 185,
  914. 196,
  915. 197,
  916. 198,
  917. 199,
  918. 200,
  919. 201,
  920. 202,
  921. 203,
  922. 204,
  923. 205,
  924. 206,
  925. 207,
  926. 208,
  927. 209,
  928. 214,
  929. 215,
  930. 220,
  931. 221
  932. ];
  933. }
  934. } catch (error) {
  935. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  936. }
  937. /**
  938. * Build up the default `inspectOpts` object from the environment variables.
  939. *
  940. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  941. */
  942. exports.inspectOpts = Object.keys(process.env).filter(key => {
  943. return /^debug_/i.test(key);
  944. }).reduce((obj, key) => {
  945. // Camel-case
  946. const prop = key
  947. .substring(6)
  948. .toLowerCase()
  949. .replace(/_([a-z])/g, (_, k) => {
  950. return k.toUpperCase();
  951. });
  952. // Coerce string value into JS value
  953. let val = process.env[key];
  954. if (/^(yes|on|true|enabled)$/i.test(val)) {
  955. val = true;
  956. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  957. val = false;
  958. } else if (val === 'null') {
  959. val = null;
  960. } else {
  961. val = Number(val);
  962. }
  963. obj[prop] = val;
  964. return obj;
  965. }, {});
  966. /**
  967. * Is stdout a TTY? Colored output is enabled when `true`.
  968. */
  969. function useColors() {
  970. return 'colors' in exports.inspectOpts ?
  971. Boolean(exports.inspectOpts.colors) :
  972. tty.isatty(process.stderr.fd);
  973. }
  974. /**
  975. * Adds ANSI color escape codes if enabled.
  976. *
  977. * @api public
  978. */
  979. function formatArgs(args) {
  980. const {namespace: name, useColors} = this;
  981. if (useColors) {
  982. const c = this.color;
  983. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  984. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  985. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  986. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  987. } else {
  988. args[0] = getDate() + name + ' ' + args[0];
  989. }
  990. }
  991. function getDate() {
  992. if (exports.inspectOpts.hideDate) {
  993. return '';
  994. }
  995. return new Date().toISOString() + ' ';
  996. }
  997. /**
  998. * Invokes `util.format()` with the specified arguments and writes to stderr.
  999. */
  1000. function log(...args) {
  1001. return process.stderr.write(util.format(...args) + '\n');
  1002. }
  1003. /**
  1004. * Save `namespaces`.
  1005. *
  1006. * @param {String} namespaces
  1007. * @api private
  1008. */
  1009. function save(namespaces) {
  1010. if (namespaces) {
  1011. process.env.DEBUG = namespaces;
  1012. } else {
  1013. // If you set a process.env field to null or undefined, it gets cast to the
  1014. // string 'null' or 'undefined'. Just delete instead.
  1015. delete process.env.DEBUG;
  1016. }
  1017. }
  1018. /**
  1019. * Load `namespaces`.
  1020. *
  1021. * @return {String} returns the previously persisted debug modes
  1022. * @api private
  1023. */
  1024. function load() {
  1025. return process.env.DEBUG;
  1026. }
  1027. /**
  1028. * Init logic for `debug` instances.
  1029. *
  1030. * Create a new `inspectOpts` object in case `useColors` is set
  1031. * differently for a particular `debug` instance.
  1032. */
  1033. function init(debug) {
  1034. debug.inspectOpts = {};
  1035. const keys = Object.keys(exports.inspectOpts);
  1036. for (let i = 0; i < keys.length; i++) {
  1037. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  1038. }
  1039. }
  1040. module.exports = requireCommon()(exports);
  1041. const {formatters} = module.exports;
  1042. /**
  1043. * Map %o to `util.inspect()`, all on a single line.
  1044. */
  1045. formatters.o = function (v) {
  1046. this.inspectOpts.colors = this.useColors;
  1047. return util.inspect(v, this.inspectOpts)
  1048. .split('\n')
  1049. .map(str => str.trim())
  1050. .join(' ');
  1051. };
  1052. /**
  1053. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  1054. */
  1055. formatters.O = function (v) {
  1056. this.inspectOpts.colors = this.useColors;
  1057. return util.inspect(v, this.inspectOpts);
  1058. };
  1059. } (node, node.exports));
  1060. return node.exports;
  1061. }
  1062. /**
  1063. * Detect Electron renderer / nwjs process, which is node, but we should
  1064. * treat as a browser.
  1065. */
  1066. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  1067. src.exports = requireBrowser();
  1068. } else {
  1069. src.exports = requireNode();
  1070. }
  1071. var srcExports = src.exports;
  1072. var debug$2 = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
  1073. var utils$3 = {};
  1074. const path$2 = require$$0$1;
  1075. const WIN_SLASH = '\\\\/';
  1076. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  1077. /**
  1078. * Posix glob regex
  1079. */
  1080. const DOT_LITERAL = '\\.';
  1081. const PLUS_LITERAL = '\\+';
  1082. const QMARK_LITERAL = '\\?';
  1083. const SLASH_LITERAL = '\\/';
  1084. const ONE_CHAR = '(?=.)';
  1085. const QMARK = '[^/]';
  1086. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  1087. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  1088. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  1089. const NO_DOT = `(?!${DOT_LITERAL})`;
  1090. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  1091. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  1092. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  1093. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  1094. const STAR = `${QMARK}*?`;
  1095. const POSIX_CHARS = {
  1096. DOT_LITERAL,
  1097. PLUS_LITERAL,
  1098. QMARK_LITERAL,
  1099. SLASH_LITERAL,
  1100. ONE_CHAR,
  1101. QMARK,
  1102. END_ANCHOR,
  1103. DOTS_SLASH,
  1104. NO_DOT,
  1105. NO_DOTS,
  1106. NO_DOT_SLASH,
  1107. NO_DOTS_SLASH,
  1108. QMARK_NO_DOT,
  1109. STAR,
  1110. START_ANCHOR
  1111. };
  1112. /**
  1113. * Windows glob regex
  1114. */
  1115. const WINDOWS_CHARS = {
  1116. ...POSIX_CHARS,
  1117. SLASH_LITERAL: `[${WIN_SLASH}]`,
  1118. QMARK: WIN_NO_SLASH,
  1119. STAR: `${WIN_NO_SLASH}*?`,
  1120. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  1121. NO_DOT: `(?!${DOT_LITERAL})`,
  1122. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1123. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  1124. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1125. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  1126. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  1127. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  1128. };
  1129. /**
  1130. * POSIX Bracket Regex
  1131. */
  1132. const POSIX_REGEX_SOURCE$1 = {
  1133. alnum: 'a-zA-Z0-9',
  1134. alpha: 'a-zA-Z',
  1135. ascii: '\\x00-\\x7F',
  1136. blank: ' \\t',
  1137. cntrl: '\\x00-\\x1F\\x7F',
  1138. digit: '0-9',
  1139. graph: '\\x21-\\x7E',
  1140. lower: 'a-z',
  1141. print: '\\x20-\\x7E ',
  1142. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1143. space: ' \\t\\r\\n\\v\\f',
  1144. upper: 'A-Z',
  1145. word: 'A-Za-z0-9_',
  1146. xdigit: 'A-Fa-f0-9'
  1147. };
  1148. var constants$2 = {
  1149. MAX_LENGTH: 1024 * 64,
  1150. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  1151. // regular expressions
  1152. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1153. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1154. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1155. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1156. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1157. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1158. // Replace globs with equivalent patterns to reduce parsing time.
  1159. REPLACEMENTS: {
  1160. '***': '*',
  1161. '**/**': '**',
  1162. '**/**/**': '**'
  1163. },
  1164. // Digits
  1165. CHAR_0: 48, /* 0 */
  1166. CHAR_9: 57, /* 9 */
  1167. // Alphabet chars.
  1168. CHAR_UPPERCASE_A: 65, /* A */
  1169. CHAR_LOWERCASE_A: 97, /* a */
  1170. CHAR_UPPERCASE_Z: 90, /* Z */
  1171. CHAR_LOWERCASE_Z: 122, /* z */
  1172. CHAR_LEFT_PARENTHESES: 40, /* ( */
  1173. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  1174. CHAR_ASTERISK: 42, /* * */
  1175. // Non-alphabetic chars.
  1176. CHAR_AMPERSAND: 38, /* & */
  1177. CHAR_AT: 64, /* @ */
  1178. CHAR_BACKWARD_SLASH: 92, /* \ */
  1179. CHAR_CARRIAGE_RETURN: 13, /* \r */
  1180. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  1181. CHAR_COLON: 58, /* : */
  1182. CHAR_COMMA: 44, /* , */
  1183. CHAR_DOT: 46, /* . */
  1184. CHAR_DOUBLE_QUOTE: 34, /* " */
  1185. CHAR_EQUAL: 61, /* = */
  1186. CHAR_EXCLAMATION_MARK: 33, /* ! */
  1187. CHAR_FORM_FEED: 12, /* \f */
  1188. CHAR_FORWARD_SLASH: 47, /* / */
  1189. CHAR_GRAVE_ACCENT: 96, /* ` */
  1190. CHAR_HASH: 35, /* # */
  1191. CHAR_HYPHEN_MINUS: 45, /* - */
  1192. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  1193. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  1194. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  1195. CHAR_LINE_FEED: 10, /* \n */
  1196. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  1197. CHAR_PERCENT: 37, /* % */
  1198. CHAR_PLUS: 43, /* + */
  1199. CHAR_QUESTION_MARK: 63, /* ? */
  1200. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  1201. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  1202. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  1203. CHAR_SEMICOLON: 59, /* ; */
  1204. CHAR_SINGLE_QUOTE: 39, /* ' */
  1205. CHAR_SPACE: 32, /* */
  1206. CHAR_TAB: 9, /* \t */
  1207. CHAR_UNDERSCORE: 95, /* _ */
  1208. CHAR_VERTICAL_LINE: 124, /* | */
  1209. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  1210. SEP: path$2.sep,
  1211. /**
  1212. * Create EXTGLOB_CHARS
  1213. */
  1214. extglobChars(chars) {
  1215. return {
  1216. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1217. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1218. '+': { type: 'plus', open: '(?:', close: ')+' },
  1219. '*': { type: 'star', open: '(?:', close: ')*' },
  1220. '@': { type: 'at', open: '(?:', close: ')' }
  1221. };
  1222. },
  1223. /**
  1224. * Create GLOB_CHARS
  1225. */
  1226. globChars(win32) {
  1227. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1228. }
  1229. };
  1230. (function (exports) {
  1231. const path = require$$0$1;
  1232. const win32 = process.platform === 'win32';
  1233. const {
  1234. REGEX_BACKSLASH,
  1235. REGEX_REMOVE_BACKSLASH,
  1236. REGEX_SPECIAL_CHARS,
  1237. REGEX_SPECIAL_CHARS_GLOBAL
  1238. } = constants$2;
  1239. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1240. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1241. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  1242. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1243. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  1244. exports.removeBackslashes = str => {
  1245. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1246. return match === '\\' ? '' : match;
  1247. });
  1248. };
  1249. exports.supportsLookbehinds = () => {
  1250. const segs = process.version.slice(1).split('.').map(Number);
  1251. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  1252. return true;
  1253. }
  1254. return false;
  1255. };
  1256. exports.isWindows = options => {
  1257. if (options && typeof options.windows === 'boolean') {
  1258. return options.windows;
  1259. }
  1260. return win32 === true || path.sep === '\\';
  1261. };
  1262. exports.escapeLast = (input, char, lastIdx) => {
  1263. const idx = input.lastIndexOf(char, lastIdx);
  1264. if (idx === -1) return input;
  1265. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  1266. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  1267. };
  1268. exports.removePrefix = (input, state = {}) => {
  1269. let output = input;
  1270. if (output.startsWith('./')) {
  1271. output = output.slice(2);
  1272. state.prefix = './';
  1273. }
  1274. return output;
  1275. };
  1276. exports.wrapOutput = (input, state = {}, options = {}) => {
  1277. const prepend = options.contains ? '' : '^';
  1278. const append = options.contains ? '' : '$';
  1279. let output = `${prepend}(?:${input})${append}`;
  1280. if (state.negated === true) {
  1281. output = `(?:^(?!${output}).*$)`;
  1282. }
  1283. return output;
  1284. };
  1285. } (utils$3));
  1286. const utils$2 = utils$3;
  1287. const {
  1288. CHAR_ASTERISK, /* * */
  1289. CHAR_AT, /* @ */
  1290. CHAR_BACKWARD_SLASH, /* \ */
  1291. CHAR_COMMA, /* , */
  1292. CHAR_DOT, /* . */
  1293. CHAR_EXCLAMATION_MARK, /* ! */
  1294. CHAR_FORWARD_SLASH, /* / */
  1295. CHAR_LEFT_CURLY_BRACE, /* { */
  1296. CHAR_LEFT_PARENTHESES, /* ( */
  1297. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1298. CHAR_PLUS, /* + */
  1299. CHAR_QUESTION_MARK, /* ? */
  1300. CHAR_RIGHT_CURLY_BRACE, /* } */
  1301. CHAR_RIGHT_PARENTHESES, /* ) */
  1302. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  1303. } = constants$2;
  1304. const isPathSeparator = code => {
  1305. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1306. };
  1307. const depth = token => {
  1308. if (token.isPrefix !== true) {
  1309. token.depth = token.isGlobstar ? Infinity : 1;
  1310. }
  1311. };
  1312. /**
  1313. * Quickly scans a glob pattern and returns an object with a handful of
  1314. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1315. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  1316. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  1317. *
  1318. * ```js
  1319. * const pm = require('picomatch');
  1320. * console.log(pm.scan('foo/bar/*.js'));
  1321. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1322. * ```
  1323. * @param {String} `str`
  1324. * @param {Object} `options`
  1325. * @return {Object} Returns an object with tokens and regex source string.
  1326. * @api public
  1327. */
  1328. const scan$1 = (input, options) => {
  1329. const opts = options || {};
  1330. const length = input.length - 1;
  1331. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  1332. const slashes = [];
  1333. const tokens = [];
  1334. const parts = [];
  1335. let str = input;
  1336. let index = -1;
  1337. let start = 0;
  1338. let lastIndex = 0;
  1339. let isBrace = false;
  1340. let isBracket = false;
  1341. let isGlob = false;
  1342. let isExtglob = false;
  1343. let isGlobstar = false;
  1344. let braceEscaped = false;
  1345. let backslashes = false;
  1346. let negated = false;
  1347. let negatedExtglob = false;
  1348. let finished = false;
  1349. let braces = 0;
  1350. let prev;
  1351. let code;
  1352. let token = { value: '', depth: 0, isGlob: false };
  1353. const eos = () => index >= length;
  1354. const peek = () => str.charCodeAt(index + 1);
  1355. const advance = () => {
  1356. prev = code;
  1357. return str.charCodeAt(++index);
  1358. };
  1359. while (index < length) {
  1360. code = advance();
  1361. let next;
  1362. if (code === CHAR_BACKWARD_SLASH) {
  1363. backslashes = token.backslashes = true;
  1364. code = advance();
  1365. if (code === CHAR_LEFT_CURLY_BRACE) {
  1366. braceEscaped = true;
  1367. }
  1368. continue;
  1369. }
  1370. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  1371. braces++;
  1372. while (eos() !== true && (code = advance())) {
  1373. if (code === CHAR_BACKWARD_SLASH) {
  1374. backslashes = token.backslashes = true;
  1375. advance();
  1376. continue;
  1377. }
  1378. if (code === CHAR_LEFT_CURLY_BRACE) {
  1379. braces++;
  1380. continue;
  1381. }
  1382. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  1383. isBrace = token.isBrace = true;
  1384. isGlob = token.isGlob = true;
  1385. finished = true;
  1386. if (scanToEnd === true) {
  1387. continue;
  1388. }
  1389. break;
  1390. }
  1391. if (braceEscaped !== true && code === CHAR_COMMA) {
  1392. isBrace = token.isBrace = true;
  1393. isGlob = token.isGlob = true;
  1394. finished = true;
  1395. if (scanToEnd === true) {
  1396. continue;
  1397. }
  1398. break;
  1399. }
  1400. if (code === CHAR_RIGHT_CURLY_BRACE) {
  1401. braces--;
  1402. if (braces === 0) {
  1403. braceEscaped = false;
  1404. isBrace = token.isBrace = true;
  1405. finished = true;
  1406. break;
  1407. }
  1408. }
  1409. }
  1410. if (scanToEnd === true) {
  1411. continue;
  1412. }
  1413. break;
  1414. }
  1415. if (code === CHAR_FORWARD_SLASH) {
  1416. slashes.push(index);
  1417. tokens.push(token);
  1418. token = { value: '', depth: 0, isGlob: false };
  1419. if (finished === true) continue;
  1420. if (prev === CHAR_DOT && index === (start + 1)) {
  1421. start += 2;
  1422. continue;
  1423. }
  1424. lastIndex = index + 1;
  1425. continue;
  1426. }
  1427. if (opts.noext !== true) {
  1428. const isExtglobChar = code === CHAR_PLUS
  1429. || code === CHAR_AT
  1430. || code === CHAR_ASTERISK
  1431. || code === CHAR_QUESTION_MARK
  1432. || code === CHAR_EXCLAMATION_MARK;
  1433. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  1434. isGlob = token.isGlob = true;
  1435. isExtglob = token.isExtglob = true;
  1436. finished = true;
  1437. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  1438. negatedExtglob = true;
  1439. }
  1440. if (scanToEnd === true) {
  1441. while (eos() !== true && (code = advance())) {
  1442. if (code === CHAR_BACKWARD_SLASH) {
  1443. backslashes = token.backslashes = true;
  1444. code = advance();
  1445. continue;
  1446. }
  1447. if (code === CHAR_RIGHT_PARENTHESES) {
  1448. isGlob = token.isGlob = true;
  1449. finished = true;
  1450. break;
  1451. }
  1452. }
  1453. continue;
  1454. }
  1455. break;
  1456. }
  1457. }
  1458. if (code === CHAR_ASTERISK) {
  1459. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  1460. isGlob = token.isGlob = true;
  1461. finished = true;
  1462. if (scanToEnd === true) {
  1463. continue;
  1464. }
  1465. break;
  1466. }
  1467. if (code === CHAR_QUESTION_MARK) {
  1468. isGlob = token.isGlob = true;
  1469. finished = true;
  1470. if (scanToEnd === true) {
  1471. continue;
  1472. }
  1473. break;
  1474. }
  1475. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  1476. while (eos() !== true && (next = advance())) {
  1477. if (next === CHAR_BACKWARD_SLASH) {
  1478. backslashes = token.backslashes = true;
  1479. advance();
  1480. continue;
  1481. }
  1482. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1483. isBracket = token.isBracket = true;
  1484. isGlob = token.isGlob = true;
  1485. finished = true;
  1486. break;
  1487. }
  1488. }
  1489. if (scanToEnd === true) {
  1490. continue;
  1491. }
  1492. break;
  1493. }
  1494. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  1495. negated = token.negated = true;
  1496. start++;
  1497. continue;
  1498. }
  1499. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  1500. isGlob = token.isGlob = true;
  1501. if (scanToEnd === true) {
  1502. while (eos() !== true && (code = advance())) {
  1503. if (code === CHAR_LEFT_PARENTHESES) {
  1504. backslashes = token.backslashes = true;
  1505. code = advance();
  1506. continue;
  1507. }
  1508. if (code === CHAR_RIGHT_PARENTHESES) {
  1509. finished = true;
  1510. break;
  1511. }
  1512. }
  1513. continue;
  1514. }
  1515. break;
  1516. }
  1517. if (isGlob === true) {
  1518. finished = true;
  1519. if (scanToEnd === true) {
  1520. continue;
  1521. }
  1522. break;
  1523. }
  1524. }
  1525. if (opts.noext === true) {
  1526. isExtglob = false;
  1527. isGlob = false;
  1528. }
  1529. let base = str;
  1530. let prefix = '';
  1531. let glob = '';
  1532. if (start > 0) {
  1533. prefix = str.slice(0, start);
  1534. str = str.slice(start);
  1535. lastIndex -= start;
  1536. }
  1537. if (base && isGlob === true && lastIndex > 0) {
  1538. base = str.slice(0, lastIndex);
  1539. glob = str.slice(lastIndex);
  1540. } else if (isGlob === true) {
  1541. base = '';
  1542. glob = str;
  1543. } else {
  1544. base = str;
  1545. }
  1546. if (base && base !== '' && base !== '/' && base !== str) {
  1547. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  1548. base = base.slice(0, -1);
  1549. }
  1550. }
  1551. if (opts.unescape === true) {
  1552. if (glob) glob = utils$2.removeBackslashes(glob);
  1553. if (base && backslashes === true) {
  1554. base = utils$2.removeBackslashes(base);
  1555. }
  1556. }
  1557. const state = {
  1558. prefix,
  1559. input,
  1560. start,
  1561. base,
  1562. glob,
  1563. isBrace,
  1564. isBracket,
  1565. isGlob,
  1566. isExtglob,
  1567. isGlobstar,
  1568. negated,
  1569. negatedExtglob
  1570. };
  1571. if (opts.tokens === true) {
  1572. state.maxDepth = 0;
  1573. if (!isPathSeparator(code)) {
  1574. tokens.push(token);
  1575. }
  1576. state.tokens = tokens;
  1577. }
  1578. if (opts.parts === true || opts.tokens === true) {
  1579. let prevIndex;
  1580. for (let idx = 0; idx < slashes.length; idx++) {
  1581. const n = prevIndex ? prevIndex + 1 : start;
  1582. const i = slashes[idx];
  1583. const value = input.slice(n, i);
  1584. if (opts.tokens) {
  1585. if (idx === 0 && start !== 0) {
  1586. tokens[idx].isPrefix = true;
  1587. tokens[idx].value = prefix;
  1588. } else {
  1589. tokens[idx].value = value;
  1590. }
  1591. depth(tokens[idx]);
  1592. state.maxDepth += tokens[idx].depth;
  1593. }
  1594. if (idx !== 0 || value !== '') {
  1595. parts.push(value);
  1596. }
  1597. prevIndex = i;
  1598. }
  1599. if (prevIndex && prevIndex + 1 < input.length) {
  1600. const value = input.slice(prevIndex + 1);
  1601. parts.push(value);
  1602. if (opts.tokens) {
  1603. tokens[tokens.length - 1].value = value;
  1604. depth(tokens[tokens.length - 1]);
  1605. state.maxDepth += tokens[tokens.length - 1].depth;
  1606. }
  1607. }
  1608. state.slashes = slashes;
  1609. state.parts = parts;
  1610. }
  1611. return state;
  1612. };
  1613. var scan_1 = scan$1;
  1614. const constants$1 = constants$2;
  1615. const utils$1 = utils$3;
  1616. /**
  1617. * Constants
  1618. */
  1619. const {
  1620. MAX_LENGTH,
  1621. POSIX_REGEX_SOURCE,
  1622. REGEX_NON_SPECIAL_CHARS,
  1623. REGEX_SPECIAL_CHARS_BACKREF,
  1624. REPLACEMENTS
  1625. } = constants$1;
  1626. /**
  1627. * Helpers
  1628. */
  1629. const expandRange = (args, options) => {
  1630. if (typeof options.expandRange === 'function') {
  1631. return options.expandRange(...args, options);
  1632. }
  1633. args.sort();
  1634. const value = `[${args.join('-')}]`;
  1635. return value;
  1636. };
  1637. /**
  1638. * Create the message for a syntax error
  1639. */
  1640. const syntaxError = (type, char) => {
  1641. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  1642. };
  1643. /**
  1644. * Parse the given input string.
  1645. * @param {String} input
  1646. * @param {Object} options
  1647. * @return {Object}
  1648. */
  1649. const parse$2 = (input, options) => {
  1650. if (typeof input !== 'string') {
  1651. throw new TypeError('Expected a string');
  1652. }
  1653. input = REPLACEMENTS[input] || input;
  1654. const opts = { ...options };
  1655. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1656. let len = input.length;
  1657. if (len > max) {
  1658. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1659. }
  1660. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  1661. const tokens = [bos];
  1662. const capture = opts.capture ? '' : '?:';
  1663. const win32 = utils$1.isWindows(options);
  1664. // create constants based on platform, for windows or posix
  1665. const PLATFORM_CHARS = constants$1.globChars(win32);
  1666. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  1667. const {
  1668. DOT_LITERAL,
  1669. PLUS_LITERAL,
  1670. SLASH_LITERAL,
  1671. ONE_CHAR,
  1672. DOTS_SLASH,
  1673. NO_DOT,
  1674. NO_DOT_SLASH,
  1675. NO_DOTS_SLASH,
  1676. QMARK,
  1677. QMARK_NO_DOT,
  1678. STAR,
  1679. START_ANCHOR
  1680. } = PLATFORM_CHARS;
  1681. const globstar = opts => {
  1682. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1683. };
  1684. const nodot = opts.dot ? '' : NO_DOT;
  1685. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  1686. let star = opts.bash === true ? globstar(opts) : STAR;
  1687. if (opts.capture) {
  1688. star = `(${star})`;
  1689. }
  1690. // minimatch options support
  1691. if (typeof opts.noext === 'boolean') {
  1692. opts.noextglob = opts.noext;
  1693. }
  1694. const state = {
  1695. input,
  1696. index: -1,
  1697. start: 0,
  1698. dot: opts.dot === true,
  1699. consumed: '',
  1700. output: '',
  1701. prefix: '',
  1702. backtrack: false,
  1703. negated: false,
  1704. brackets: 0,
  1705. braces: 0,
  1706. parens: 0,
  1707. quotes: 0,
  1708. globstar: false,
  1709. tokens
  1710. };
  1711. input = utils$1.removePrefix(input, state);
  1712. len = input.length;
  1713. const extglobs = [];
  1714. const braces = [];
  1715. const stack = [];
  1716. let prev = bos;
  1717. let value;
  1718. /**
  1719. * Tokenizing helpers
  1720. */
  1721. const eos = () => state.index === len - 1;
  1722. const peek = state.peek = (n = 1) => input[state.index + n];
  1723. const advance = state.advance = () => input[++state.index] || '';
  1724. const remaining = () => input.slice(state.index + 1);
  1725. const consume = (value = '', num = 0) => {
  1726. state.consumed += value;
  1727. state.index += num;
  1728. };
  1729. const append = token => {
  1730. state.output += token.output != null ? token.output : token.value;
  1731. consume(token.value);
  1732. };
  1733. const negate = () => {
  1734. let count = 1;
  1735. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1736. advance();
  1737. state.start++;
  1738. count++;
  1739. }
  1740. if (count % 2 === 0) {
  1741. return false;
  1742. }
  1743. state.negated = true;
  1744. state.start++;
  1745. return true;
  1746. };
  1747. const increment = type => {
  1748. state[type]++;
  1749. stack.push(type);
  1750. };
  1751. const decrement = type => {
  1752. state[type]--;
  1753. stack.pop();
  1754. };
  1755. /**
  1756. * Push tokens onto the tokens array. This helper speeds up
  1757. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1758. * and 2) helping us avoid creating extra tokens when consecutive
  1759. * characters are plain text. This improves performance and simplifies
  1760. * lookbehinds.
  1761. */
  1762. const push = tok => {
  1763. if (prev.type === 'globstar') {
  1764. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1765. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1766. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1767. state.output = state.output.slice(0, -prev.output.length);
  1768. prev.type = 'star';
  1769. prev.value = '*';
  1770. prev.output = star;
  1771. state.output += prev.output;
  1772. }
  1773. }
  1774. if (extglobs.length && tok.type !== 'paren') {
  1775. extglobs[extglobs.length - 1].inner += tok.value;
  1776. }
  1777. if (tok.value || tok.output) append(tok);
  1778. if (prev && prev.type === 'text' && tok.type === 'text') {
  1779. prev.value += tok.value;
  1780. prev.output = (prev.output || '') + tok.value;
  1781. return;
  1782. }
  1783. tok.prev = prev;
  1784. tokens.push(tok);
  1785. prev = tok;
  1786. };
  1787. const extglobOpen = (type, value) => {
  1788. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1789. token.prev = prev;
  1790. token.parens = state.parens;
  1791. token.output = state.output;
  1792. const output = (opts.capture ? '(' : '') + token.open;
  1793. increment('parens');
  1794. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1795. push({ type: 'paren', extglob: true, value: advance(), output });
  1796. extglobs.push(token);
  1797. };
  1798. const extglobClose = token => {
  1799. let output = token.close + (opts.capture ? ')' : '');
  1800. let rest;
  1801. if (token.type === 'negate') {
  1802. let extglobStar = star;
  1803. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1804. extglobStar = globstar(opts);
  1805. }
  1806. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1807. output = token.close = `)$))${extglobStar}`;
  1808. }
  1809. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1810. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1811. // In this case, we need to parse the string and use it in the output of the original pattern.
  1812. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1813. //
  1814. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1815. const expression = parse$2(rest, { ...options, fastpaths: false }).output;
  1816. output = token.close = `)${expression})${extglobStar})`;
  1817. }
  1818. if (token.prev.type === 'bos') {
  1819. state.negatedExtglob = true;
  1820. }
  1821. }
  1822. push({ type: 'paren', extglob: true, value, output });
  1823. decrement('parens');
  1824. };
  1825. /**
  1826. * Fast paths
  1827. */
  1828. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1829. let backslashes = false;
  1830. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1831. if (first === '\\') {
  1832. backslashes = true;
  1833. return m;
  1834. }
  1835. if (first === '?') {
  1836. if (esc) {
  1837. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1838. }
  1839. if (index === 0) {
  1840. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1841. }
  1842. return QMARK.repeat(chars.length);
  1843. }
  1844. if (first === '.') {
  1845. return DOT_LITERAL.repeat(chars.length);
  1846. }
  1847. if (first === '*') {
  1848. if (esc) {
  1849. return esc + first + (rest ? star : '');
  1850. }
  1851. return star;
  1852. }
  1853. return esc ? m : `\\${m}`;
  1854. });
  1855. if (backslashes === true) {
  1856. if (opts.unescape === true) {
  1857. output = output.replace(/\\/g, '');
  1858. } else {
  1859. output = output.replace(/\\+/g, m => {
  1860. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1861. });
  1862. }
  1863. }
  1864. if (output === input && opts.contains === true) {
  1865. state.output = input;
  1866. return state;
  1867. }
  1868. state.output = utils$1.wrapOutput(output, state, options);
  1869. return state;
  1870. }
  1871. /**
  1872. * Tokenize input until we reach end-of-string
  1873. */
  1874. while (!eos()) {
  1875. value = advance();
  1876. if (value === '\u0000') {
  1877. continue;
  1878. }
  1879. /**
  1880. * Escaped characters
  1881. */
  1882. if (value === '\\') {
  1883. const next = peek();
  1884. if (next === '/' && opts.bash !== true) {
  1885. continue;
  1886. }
  1887. if (next === '.' || next === ';') {
  1888. continue;
  1889. }
  1890. if (!next) {
  1891. value += '\\';
  1892. push({ type: 'text', value });
  1893. continue;
  1894. }
  1895. // collapse slashes to reduce potential for exploits
  1896. const match = /^\\+/.exec(remaining());
  1897. let slashes = 0;
  1898. if (match && match[0].length > 2) {
  1899. slashes = match[0].length;
  1900. state.index += slashes;
  1901. if (slashes % 2 !== 0) {
  1902. value += '\\';
  1903. }
  1904. }
  1905. if (opts.unescape === true) {
  1906. value = advance();
  1907. } else {
  1908. value += advance();
  1909. }
  1910. if (state.brackets === 0) {
  1911. push({ type: 'text', value });
  1912. continue;
  1913. }
  1914. }
  1915. /**
  1916. * If we're inside a regex character class, continue
  1917. * until we reach the closing bracket.
  1918. */
  1919. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1920. if (opts.posix !== false && value === ':') {
  1921. const inner = prev.value.slice(1);
  1922. if (inner.includes('[')) {
  1923. prev.posix = true;
  1924. if (inner.includes(':')) {
  1925. const idx = prev.value.lastIndexOf('[');
  1926. const pre = prev.value.slice(0, idx);
  1927. const rest = prev.value.slice(idx + 2);
  1928. const posix = POSIX_REGEX_SOURCE[rest];
  1929. if (posix) {
  1930. prev.value = pre + posix;
  1931. state.backtrack = true;
  1932. advance();
  1933. if (!bos.output && tokens.indexOf(prev) === 1) {
  1934. bos.output = ONE_CHAR;
  1935. }
  1936. continue;
  1937. }
  1938. }
  1939. }
  1940. }
  1941. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1942. value = `\\${value}`;
  1943. }
  1944. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1945. value = `\\${value}`;
  1946. }
  1947. if (opts.posix === true && value === '!' && prev.value === '[') {
  1948. value = '^';
  1949. }
  1950. prev.value += value;
  1951. append({ value });
  1952. continue;
  1953. }
  1954. /**
  1955. * If we're inside a quoted string, continue
  1956. * until we reach the closing double quote.
  1957. */
  1958. if (state.quotes === 1 && value !== '"') {
  1959. value = utils$1.escapeRegex(value);
  1960. prev.value += value;
  1961. append({ value });
  1962. continue;
  1963. }
  1964. /**
  1965. * Double quotes
  1966. */
  1967. if (value === '"') {
  1968. state.quotes = state.quotes === 1 ? 0 : 1;
  1969. if (opts.keepQuotes === true) {
  1970. push({ type: 'text', value });
  1971. }
  1972. continue;
  1973. }
  1974. /**
  1975. * Parentheses
  1976. */
  1977. if (value === '(') {
  1978. increment('parens');
  1979. push({ type: 'paren', value });
  1980. continue;
  1981. }
  1982. if (value === ')') {
  1983. if (state.parens === 0 && opts.strictBrackets === true) {
  1984. throw new SyntaxError(syntaxError('opening', '('));
  1985. }
  1986. const extglob = extglobs[extglobs.length - 1];
  1987. if (extglob && state.parens === extglob.parens + 1) {
  1988. extglobClose(extglobs.pop());
  1989. continue;
  1990. }
  1991. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1992. decrement('parens');
  1993. continue;
  1994. }
  1995. /**
  1996. * Square brackets
  1997. */
  1998. if (value === '[') {
  1999. if (opts.nobracket === true || !remaining().includes(']')) {
  2000. if (opts.nobracket !== true && opts.strictBrackets === true) {
  2001. throw new SyntaxError(syntaxError('closing', ']'));
  2002. }
  2003. value = `\\${value}`;
  2004. } else {
  2005. increment('brackets');
  2006. }
  2007. push({ type: 'bracket', value });
  2008. continue;
  2009. }
  2010. if (value === ']') {
  2011. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  2012. push({ type: 'text', value, output: `\\${value}` });
  2013. continue;
  2014. }
  2015. if (state.brackets === 0) {
  2016. if (opts.strictBrackets === true) {
  2017. throw new SyntaxError(syntaxError('opening', '['));
  2018. }
  2019. push({ type: 'text', value, output: `\\${value}` });
  2020. continue;
  2021. }
  2022. decrement('brackets');
  2023. const prevValue = prev.value.slice(1);
  2024. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  2025. value = `/${value}`;
  2026. }
  2027. prev.value += value;
  2028. append({ value });
  2029. // when literal brackets are explicitly disabled
  2030. // assume we should match with a regex character class
  2031. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  2032. continue;
  2033. }
  2034. const escaped = utils$1.escapeRegex(prev.value);
  2035. state.output = state.output.slice(0, -prev.value.length);
  2036. // when literal brackets are explicitly enabled
  2037. // assume we should escape the brackets to match literal characters
  2038. if (opts.literalBrackets === true) {
  2039. state.output += escaped;
  2040. prev.value = escaped;
  2041. continue;
  2042. }
  2043. // when the user specifies nothing, try to match both
  2044. prev.value = `(${capture}${escaped}|${prev.value})`;
  2045. state.output += prev.value;
  2046. continue;
  2047. }
  2048. /**
  2049. * Braces
  2050. */
  2051. if (value === '{' && opts.nobrace !== true) {
  2052. increment('braces');
  2053. const open = {
  2054. type: 'brace',
  2055. value,
  2056. output: '(',
  2057. outputIndex: state.output.length,
  2058. tokensIndex: state.tokens.length
  2059. };
  2060. braces.push(open);
  2061. push(open);
  2062. continue;
  2063. }
  2064. if (value === '}') {
  2065. const brace = braces[braces.length - 1];
  2066. if (opts.nobrace === true || !brace) {
  2067. push({ type: 'text', value, output: value });
  2068. continue;
  2069. }
  2070. let output = ')';
  2071. if (brace.dots === true) {
  2072. const arr = tokens.slice();
  2073. const range = [];
  2074. for (let i = arr.length - 1; i >= 0; i--) {
  2075. tokens.pop();
  2076. if (arr[i].type === 'brace') {
  2077. break;
  2078. }
  2079. if (arr[i].type !== 'dots') {
  2080. range.unshift(arr[i].value);
  2081. }
  2082. }
  2083. output = expandRange(range, opts);
  2084. state.backtrack = true;
  2085. }
  2086. if (brace.comma !== true && brace.dots !== true) {
  2087. const out = state.output.slice(0, brace.outputIndex);
  2088. const toks = state.tokens.slice(brace.tokensIndex);
  2089. brace.value = brace.output = '\\{';
  2090. value = output = '\\}';
  2091. state.output = out;
  2092. for (const t of toks) {
  2093. state.output += (t.output || t.value);
  2094. }
  2095. }
  2096. push({ type: 'brace', value, output });
  2097. decrement('braces');
  2098. braces.pop();
  2099. continue;
  2100. }
  2101. /**
  2102. * Pipes
  2103. */
  2104. if (value === '|') {
  2105. if (extglobs.length > 0) {
  2106. extglobs[extglobs.length - 1].conditions++;
  2107. }
  2108. push({ type: 'text', value });
  2109. continue;
  2110. }
  2111. /**
  2112. * Commas
  2113. */
  2114. if (value === ',') {
  2115. let output = value;
  2116. const brace = braces[braces.length - 1];
  2117. if (brace && stack[stack.length - 1] === 'braces') {
  2118. brace.comma = true;
  2119. output = '|';
  2120. }
  2121. push({ type: 'comma', value, output });
  2122. continue;
  2123. }
  2124. /**
  2125. * Slashes
  2126. */
  2127. if (value === '/') {
  2128. // if the beginning of the glob is "./", advance the start
  2129. // to the current index, and don't add the "./" characters
  2130. // to the state. This greatly simplifies lookbehinds when
  2131. // checking for BOS characters like "!" and "." (not "./")
  2132. if (prev.type === 'dot' && state.index === state.start + 1) {
  2133. state.start = state.index + 1;
  2134. state.consumed = '';
  2135. state.output = '';
  2136. tokens.pop();
  2137. prev = bos; // reset "prev" to the first token
  2138. continue;
  2139. }
  2140. push({ type: 'slash', value, output: SLASH_LITERAL });
  2141. continue;
  2142. }
  2143. /**
  2144. * Dots
  2145. */
  2146. if (value === '.') {
  2147. if (state.braces > 0 && prev.type === 'dot') {
  2148. if (prev.value === '.') prev.output = DOT_LITERAL;
  2149. const brace = braces[braces.length - 1];
  2150. prev.type = 'dots';
  2151. prev.output += value;
  2152. prev.value += value;
  2153. brace.dots = true;
  2154. continue;
  2155. }
  2156. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2157. push({ type: 'text', value, output: DOT_LITERAL });
  2158. continue;
  2159. }
  2160. push({ type: 'dot', value, output: DOT_LITERAL });
  2161. continue;
  2162. }
  2163. /**
  2164. * Question marks
  2165. */
  2166. if (value === '?') {
  2167. const isGroup = prev && prev.value === '(';
  2168. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2169. extglobOpen('qmark', value);
  2170. continue;
  2171. }
  2172. if (prev && prev.type === 'paren') {
  2173. const next = peek();
  2174. let output = value;
  2175. if (next === '<' && !utils$1.supportsLookbehinds()) {
  2176. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  2177. }
  2178. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  2179. output = `\\${value}`;
  2180. }
  2181. push({ type: 'text', value, output });
  2182. continue;
  2183. }
  2184. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2185. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2186. continue;
  2187. }
  2188. push({ type: 'qmark', value, output: QMARK });
  2189. continue;
  2190. }
  2191. /**
  2192. * Exclamation
  2193. */
  2194. if (value === '!') {
  2195. if (opts.noextglob !== true && peek() === '(') {
  2196. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2197. extglobOpen('negate', value);
  2198. continue;
  2199. }
  2200. }
  2201. if (opts.nonegate !== true && state.index === 0) {
  2202. negate();
  2203. continue;
  2204. }
  2205. }
  2206. /**
  2207. * Plus
  2208. */
  2209. if (value === '+') {
  2210. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2211. extglobOpen('plus', value);
  2212. continue;
  2213. }
  2214. if ((prev && prev.value === '(') || opts.regex === false) {
  2215. push({ type: 'plus', value, output: PLUS_LITERAL });
  2216. continue;
  2217. }
  2218. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  2219. push({ type: 'plus', value });
  2220. continue;
  2221. }
  2222. push({ type: 'plus', value: PLUS_LITERAL });
  2223. continue;
  2224. }
  2225. /**
  2226. * Plain text
  2227. */
  2228. if (value === '@') {
  2229. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2230. push({ type: 'at', extglob: true, value, output: '' });
  2231. continue;
  2232. }
  2233. push({ type: 'text', value });
  2234. continue;
  2235. }
  2236. /**
  2237. * Plain text
  2238. */
  2239. if (value !== '*') {
  2240. if (value === '$' || value === '^') {
  2241. value = `\\${value}`;
  2242. }
  2243. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  2244. if (match) {
  2245. value += match[0];
  2246. state.index += match[0].length;
  2247. }
  2248. push({ type: 'text', value });
  2249. continue;
  2250. }
  2251. /**
  2252. * Stars
  2253. */
  2254. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2255. prev.type = 'star';
  2256. prev.star = true;
  2257. prev.value += value;
  2258. prev.output = star;
  2259. state.backtrack = true;
  2260. state.globstar = true;
  2261. consume(value);
  2262. continue;
  2263. }
  2264. let rest = remaining();
  2265. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  2266. extglobOpen('star', value);
  2267. continue;
  2268. }
  2269. if (prev.type === 'star') {
  2270. if (opts.noglobstar === true) {
  2271. consume(value);
  2272. continue;
  2273. }
  2274. const prior = prev.prev;
  2275. const before = prior.prev;
  2276. const isStart = prior.type === 'slash' || prior.type === 'bos';
  2277. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2278. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  2279. push({ type: 'star', value, output: '' });
  2280. continue;
  2281. }
  2282. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2283. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2284. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2285. push({ type: 'star', value, output: '' });
  2286. continue;
  2287. }
  2288. // strip consecutive `/**/`
  2289. while (rest.slice(0, 3) === '/**') {
  2290. const after = input[state.index + 4];
  2291. if (after && after !== '/') {
  2292. break;
  2293. }
  2294. rest = rest.slice(3);
  2295. consume('/**', 3);
  2296. }
  2297. if (prior.type === 'bos' && eos()) {
  2298. prev.type = 'globstar';
  2299. prev.value += value;
  2300. prev.output = globstar(opts);
  2301. state.output = prev.output;
  2302. state.globstar = true;
  2303. consume(value);
  2304. continue;
  2305. }
  2306. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2307. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2308. prior.output = `(?:${prior.output}`;
  2309. prev.type = 'globstar';
  2310. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  2311. prev.value += value;
  2312. state.globstar = true;
  2313. state.output += prior.output + prev.output;
  2314. consume(value);
  2315. continue;
  2316. }
  2317. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  2318. const end = rest[1] !== void 0 ? '|$' : '';
  2319. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2320. prior.output = `(?:${prior.output}`;
  2321. prev.type = 'globstar';
  2322. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2323. prev.value += value;
  2324. state.output += prior.output + prev.output;
  2325. state.globstar = true;
  2326. consume(value + advance());
  2327. push({ type: 'slash', value: '/', output: '' });
  2328. continue;
  2329. }
  2330. if (prior.type === 'bos' && rest[0] === '/') {
  2331. prev.type = 'globstar';
  2332. prev.value += value;
  2333. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2334. state.output = prev.output;
  2335. state.globstar = true;
  2336. consume(value + advance());
  2337. push({ type: 'slash', value: '/', output: '' });
  2338. continue;
  2339. }
  2340. // remove single star from output
  2341. state.output = state.output.slice(0, -prev.output.length);
  2342. // reset previous token to globstar
  2343. prev.type = 'globstar';
  2344. prev.output = globstar(opts);
  2345. prev.value += value;
  2346. // reset output with globstar
  2347. state.output += prev.output;
  2348. state.globstar = true;
  2349. consume(value);
  2350. continue;
  2351. }
  2352. const token = { type: 'star', value, output: star };
  2353. if (opts.bash === true) {
  2354. token.output = '.*?';
  2355. if (prev.type === 'bos' || prev.type === 'slash') {
  2356. token.output = nodot + token.output;
  2357. }
  2358. push(token);
  2359. continue;
  2360. }
  2361. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2362. token.output = value;
  2363. push(token);
  2364. continue;
  2365. }
  2366. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2367. if (prev.type === 'dot') {
  2368. state.output += NO_DOT_SLASH;
  2369. prev.output += NO_DOT_SLASH;
  2370. } else if (opts.dot === true) {
  2371. state.output += NO_DOTS_SLASH;
  2372. prev.output += NO_DOTS_SLASH;
  2373. } else {
  2374. state.output += nodot;
  2375. prev.output += nodot;
  2376. }
  2377. if (peek() !== '*') {
  2378. state.output += ONE_CHAR;
  2379. prev.output += ONE_CHAR;
  2380. }
  2381. }
  2382. push(token);
  2383. }
  2384. while (state.brackets > 0) {
  2385. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  2386. state.output = utils$1.escapeLast(state.output, '[');
  2387. decrement('brackets');
  2388. }
  2389. while (state.parens > 0) {
  2390. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  2391. state.output = utils$1.escapeLast(state.output, '(');
  2392. decrement('parens');
  2393. }
  2394. while (state.braces > 0) {
  2395. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  2396. state.output = utils$1.escapeLast(state.output, '{');
  2397. decrement('braces');
  2398. }
  2399. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2400. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2401. }
  2402. // rebuild the output if we had to backtrack at any point
  2403. if (state.backtrack === true) {
  2404. state.output = '';
  2405. for (const token of state.tokens) {
  2406. state.output += token.output != null ? token.output : token.value;
  2407. if (token.suffix) {
  2408. state.output += token.suffix;
  2409. }
  2410. }
  2411. }
  2412. return state;
  2413. };
  2414. /**
  2415. * Fast paths for creating regular expressions for common glob patterns.
  2416. * This can significantly speed up processing and has very little downside
  2417. * impact when none of the fast paths match.
  2418. */
  2419. parse$2.fastpaths = (input, options) => {
  2420. const opts = { ...options };
  2421. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2422. const len = input.length;
  2423. if (len > max) {
  2424. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2425. }
  2426. input = REPLACEMENTS[input] || input;
  2427. const win32 = utils$1.isWindows(options);
  2428. // create constants based on platform, for windows or posix
  2429. const {
  2430. DOT_LITERAL,
  2431. SLASH_LITERAL,
  2432. ONE_CHAR,
  2433. DOTS_SLASH,
  2434. NO_DOT,
  2435. NO_DOTS,
  2436. NO_DOTS_SLASH,
  2437. STAR,
  2438. START_ANCHOR
  2439. } = constants$1.globChars(win32);
  2440. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  2441. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2442. const capture = opts.capture ? '' : '?:';
  2443. const state = { negated: false, prefix: '' };
  2444. let star = opts.bash === true ? '.*?' : STAR;
  2445. if (opts.capture) {
  2446. star = `(${star})`;
  2447. }
  2448. const globstar = opts => {
  2449. if (opts.noglobstar === true) return star;
  2450. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2451. };
  2452. const create = str => {
  2453. switch (str) {
  2454. case '*':
  2455. return `${nodot}${ONE_CHAR}${star}`;
  2456. case '.*':
  2457. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2458. case '*.*':
  2459. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2460. case '*/*':
  2461. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2462. case '**':
  2463. return nodot + globstar(opts);
  2464. case '**/*':
  2465. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2466. case '**/*.*':
  2467. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2468. case '**/.*':
  2469. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2470. default: {
  2471. const match = /^(.*?)\.(\w+)$/.exec(str);
  2472. if (!match) return;
  2473. const source = create(match[1]);
  2474. if (!source) return;
  2475. return source + DOT_LITERAL + match[2];
  2476. }
  2477. }
  2478. };
  2479. const output = utils$1.removePrefix(input, state);
  2480. let source = create(output);
  2481. if (source && opts.strictSlashes !== true) {
  2482. source += `${SLASH_LITERAL}?`;
  2483. }
  2484. return source;
  2485. };
  2486. var parse_1$1 = parse$2;
  2487. const path$1 = require$$0$1;
  2488. const scan = scan_1;
  2489. const parse$1 = parse_1$1;
  2490. const utils = utils$3;
  2491. const constants = constants$2;
  2492. const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
  2493. /**
  2494. * Creates a matcher function from one or more glob patterns. The
  2495. * returned function takes a string to match as its first argument,
  2496. * and returns true if the string is a match. The returned matcher
  2497. * function also takes a boolean as the second argument that, when true,
  2498. * returns an object with additional information.
  2499. *
  2500. * ```js
  2501. * const picomatch = require('picomatch');
  2502. * // picomatch(glob[, options]);
  2503. *
  2504. * const isMatch = picomatch('*.!(*a)');
  2505. * console.log(isMatch('a.a')); //=> false
  2506. * console.log(isMatch('a.b')); //=> true
  2507. * ```
  2508. * @name picomatch
  2509. * @param {String|Array} `globs` One or more glob patterns.
  2510. * @param {Object=} `options`
  2511. * @return {Function=} Returns a matcher function.
  2512. * @api public
  2513. */
  2514. const picomatch$1 = (glob, options, returnState = false) => {
  2515. if (Array.isArray(glob)) {
  2516. const fns = glob.map(input => picomatch$1(input, options, returnState));
  2517. const arrayMatcher = str => {
  2518. for (const isMatch of fns) {
  2519. const state = isMatch(str);
  2520. if (state) return state;
  2521. }
  2522. return false;
  2523. };
  2524. return arrayMatcher;
  2525. }
  2526. const isState = isObject$2(glob) && glob.tokens && glob.input;
  2527. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  2528. throw new TypeError('Expected pattern to be a non-empty string');
  2529. }
  2530. const opts = options || {};
  2531. const posix = utils.isWindows(options);
  2532. const regex = isState
  2533. ? picomatch$1.compileRe(glob, options)
  2534. : picomatch$1.makeRe(glob, options, false, true);
  2535. const state = regex.state;
  2536. delete regex.state;
  2537. let isIgnored = () => false;
  2538. if (opts.ignore) {
  2539. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  2540. isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
  2541. }
  2542. const matcher = (input, returnObject = false) => {
  2543. const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
  2544. const result = { glob, state, regex, posix, input, output, match, isMatch };
  2545. if (typeof opts.onResult === 'function') {
  2546. opts.onResult(result);
  2547. }
  2548. if (isMatch === false) {
  2549. result.isMatch = false;
  2550. return returnObject ? result : false;
  2551. }
  2552. if (isIgnored(input)) {
  2553. if (typeof opts.onIgnore === 'function') {
  2554. opts.onIgnore(result);
  2555. }
  2556. result.isMatch = false;
  2557. return returnObject ? result : false;
  2558. }
  2559. if (typeof opts.onMatch === 'function') {
  2560. opts.onMatch(result);
  2561. }
  2562. return returnObject ? result : true;
  2563. };
  2564. if (returnState) {
  2565. matcher.state = state;
  2566. }
  2567. return matcher;
  2568. };
  2569. /**
  2570. * Test `input` with the given `regex`. This is used by the main
  2571. * `picomatch()` function to test the input string.
  2572. *
  2573. * ```js
  2574. * const picomatch = require('picomatch');
  2575. * // picomatch.test(input, regex[, options]);
  2576. *
  2577. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  2578. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  2579. * ```
  2580. * @param {String} `input` String to test.
  2581. * @param {RegExp} `regex`
  2582. * @return {Object} Returns an object with matching info.
  2583. * @api public
  2584. */
  2585. picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
  2586. if (typeof input !== 'string') {
  2587. throw new TypeError('Expected input to be a string');
  2588. }
  2589. if (input === '') {
  2590. return { isMatch: false, output: '' };
  2591. }
  2592. const opts = options || {};
  2593. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  2594. let match = input === glob;
  2595. let output = (match && format) ? format(input) : input;
  2596. if (match === false) {
  2597. output = format ? format(input) : input;
  2598. match = output === glob;
  2599. }
  2600. if (match === false || opts.capture === true) {
  2601. if (opts.matchBase === true || opts.basename === true) {
  2602. match = picomatch$1.matchBase(input, regex, options, posix);
  2603. } else {
  2604. match = regex.exec(output);
  2605. }
  2606. }
  2607. return { isMatch: Boolean(match), match, output };
  2608. };
  2609. /**
  2610. * Match the basename of a filepath.
  2611. *
  2612. * ```js
  2613. * const picomatch = require('picomatch');
  2614. * // picomatch.matchBase(input, glob[, options]);
  2615. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  2616. * ```
  2617. * @param {String} `input` String to test.
  2618. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  2619. * @return {Boolean}
  2620. * @api public
  2621. */
  2622. picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  2623. const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
  2624. return regex.test(path$1.basename(input));
  2625. };
  2626. /**
  2627. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2628. *
  2629. * ```js
  2630. * const picomatch = require('picomatch');
  2631. * // picomatch.isMatch(string, patterns[, options]);
  2632. *
  2633. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2634. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  2635. * ```
  2636. * @param {String|Array} str The string to test.
  2637. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2638. * @param {Object} [options] See available [options](#options).
  2639. * @return {Boolean} Returns true if any patterns match `str`
  2640. * @api public
  2641. */
  2642. picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  2643. /**
  2644. * Parse a glob pattern to create the source string for a regular
  2645. * expression.
  2646. *
  2647. * ```js
  2648. * const picomatch = require('picomatch');
  2649. * const result = picomatch.parse(pattern[, options]);
  2650. * ```
  2651. * @param {String} `pattern`
  2652. * @param {Object} `options`
  2653. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  2654. * @api public
  2655. */
  2656. picomatch$1.parse = (pattern, options) => {
  2657. if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
  2658. return parse$1(pattern, { ...options, fastpaths: false });
  2659. };
  2660. /**
  2661. * Scan a glob pattern to separate the pattern into segments.
  2662. *
  2663. * ```js
  2664. * const picomatch = require('picomatch');
  2665. * // picomatch.scan(input[, options]);
  2666. *
  2667. * const result = picomatch.scan('!./foo/*.js');
  2668. * console.log(result);
  2669. * { prefix: '!./',
  2670. * input: '!./foo/*.js',
  2671. * start: 3,
  2672. * base: 'foo',
  2673. * glob: '*.js',
  2674. * isBrace: false,
  2675. * isBracket: false,
  2676. * isGlob: true,
  2677. * isExtglob: false,
  2678. * isGlobstar: false,
  2679. * negated: true }
  2680. * ```
  2681. * @param {String} `input` Glob pattern to scan.
  2682. * @param {Object} `options`
  2683. * @return {Object} Returns an object with
  2684. * @api public
  2685. */
  2686. picomatch$1.scan = (input, options) => scan(input, options);
  2687. /**
  2688. * Compile a regular expression from the `state` object returned by the
  2689. * [parse()](#parse) method.
  2690. *
  2691. * @param {Object} `state`
  2692. * @param {Object} `options`
  2693. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  2694. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  2695. * @return {RegExp}
  2696. * @api public
  2697. */
  2698. picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
  2699. if (returnOutput === true) {
  2700. return state.output;
  2701. }
  2702. const opts = options || {};
  2703. const prepend = opts.contains ? '' : '^';
  2704. const append = opts.contains ? '' : '$';
  2705. let source = `${prepend}(?:${state.output})${append}`;
  2706. if (state && state.negated === true) {
  2707. source = `^(?!${source}).*$`;
  2708. }
  2709. const regex = picomatch$1.toRegex(source, options);
  2710. if (returnState === true) {
  2711. regex.state = state;
  2712. }
  2713. return regex;
  2714. };
  2715. /**
  2716. * Create a regular expression from a parsed glob pattern.
  2717. *
  2718. * ```js
  2719. * const picomatch = require('picomatch');
  2720. * const state = picomatch.parse('*.js');
  2721. * // picomatch.compileRe(state[, options]);
  2722. *
  2723. * console.log(picomatch.compileRe(state));
  2724. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2725. * ```
  2726. * @param {String} `state` The object returned from the `.parse` method.
  2727. * @param {Object} `options`
  2728. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  2729. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  2730. * @return {RegExp} Returns a regex created from the given pattern.
  2731. * @api public
  2732. */
  2733. picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  2734. if (!input || typeof input !== 'string') {
  2735. throw new TypeError('Expected a non-empty string');
  2736. }
  2737. let parsed = { negated: false, fastpaths: true };
  2738. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2739. parsed.output = parse$1.fastpaths(input, options);
  2740. }
  2741. if (!parsed.output) {
  2742. parsed = parse$1(input, options);
  2743. }
  2744. return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
  2745. };
  2746. /**
  2747. * Create a regular expression from the given regex source string.
  2748. *
  2749. * ```js
  2750. * const picomatch = require('picomatch');
  2751. * // picomatch.toRegex(source[, options]);
  2752. *
  2753. * const { output } = picomatch.parse('*.js');
  2754. * console.log(picomatch.toRegex(output));
  2755. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2756. * ```
  2757. * @param {String} `source` Regular expression source string.
  2758. * @param {Object} `options`
  2759. * @return {RegExp}
  2760. * @api public
  2761. */
  2762. picomatch$1.toRegex = (source, options) => {
  2763. try {
  2764. const opts = options || {};
  2765. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2766. } catch (err) {
  2767. if (options && options.debug === true) throw err;
  2768. return /$^/;
  2769. }
  2770. };
  2771. /**
  2772. * Picomatch constants.
  2773. * @return {Object}
  2774. */
  2775. picomatch$1.constants = constants;
  2776. /**
  2777. * Expose "picomatch"
  2778. */
  2779. var picomatch_1 = picomatch$1;
  2780. var picomatch = picomatch_1;
  2781. var pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch);
  2782. // Helper since Typescript can't detect readonly arrays with Array.isArray
  2783. function isArray(arg) {
  2784. return Array.isArray(arg);
  2785. }
  2786. function ensureArray(thing) {
  2787. if (isArray(thing))
  2788. return thing;
  2789. if (thing == null)
  2790. return [];
  2791. return [thing];
  2792. }
  2793. const normalizePath$1 = function normalizePath(filename) {
  2794. return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep);
  2795. };
  2796. function getMatcherString(id, resolutionBase) {
  2797. if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('**')) {
  2798. return normalizePath$1(id);
  2799. }
  2800. // resolve('') is valid and will default to process.cwd()
  2801. const basePath = normalizePath$1(require$$0$1.resolve(resolutionBase || ''))
  2802. // escape all possible (posix + win) path characters that might interfere with regex
  2803. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  2804. // Note that we use posix.join because:
  2805. // 1. the basePath has been normalized to use /
  2806. // 2. the incoming glob (id) matcher, also uses /
  2807. // otherwise Node will force backslash (\) on windows
  2808. return require$$0$1.posix.join(basePath, normalizePath$1(id));
  2809. }
  2810. const createFilter$1 = function createFilter(include, exclude, options) {
  2811. const resolutionBase = options && options.resolve;
  2812. const getMatcher = (id) => id instanceof RegExp
  2813. ? id
  2814. : {
  2815. test: (what) => {
  2816. // this refactor is a tad overly verbose but makes for easy debugging
  2817. const pattern = getMatcherString(id, resolutionBase);
  2818. const fn = pm(pattern, { dot: true });
  2819. const result = fn(what);
  2820. return result;
  2821. }
  2822. };
  2823. const includeMatchers = ensureArray(include).map(getMatcher);
  2824. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  2825. return function result(id) {
  2826. if (typeof id !== 'string')
  2827. return false;
  2828. if (/\0/.test(id))
  2829. return false;
  2830. const pathId = normalizePath$1(id);
  2831. for (let i = 0; i < excludeMatchers.length; ++i) {
  2832. const matcher = excludeMatchers[i];
  2833. if (matcher.test(pathId))
  2834. return false;
  2835. }
  2836. for (let i = 0; i < includeMatchers.length; ++i) {
  2837. const matcher = includeMatchers[i];
  2838. if (matcher.test(pathId))
  2839. return true;
  2840. }
  2841. return !includeMatchers.length;
  2842. };
  2843. };
  2844. const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  2845. const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  2846. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  2847. forbiddenIdentifiers.add('');
  2848. const isWindows = typeof process !== 'undefined' && process.platform === 'win32';
  2849. const windowsSlashRE = /\\/g;
  2850. function slash(p) {
  2851. return p.replace(windowsSlashRE, '/');
  2852. }
  2853. const postfixRE = /[?#].*$/;
  2854. function cleanUrl(url) {
  2855. return url.replace(postfixRE, '');
  2856. }
  2857. function withTrailingSlash(path) {
  2858. if (path[path.length - 1] !== '/') {
  2859. return `${path}/`;
  2860. }
  2861. return path;
  2862. }
  2863. if (process.versions.pnp) {
  2864. try {
  2865. node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))('pnpapi');
  2866. }
  2867. catch { }
  2868. }
  2869. const createFilter = createFilter$1;
  2870. // Some runtimes like Bun injects namespaced modules here, which is not a node builtin
  2871. node_module.builtinModules.filter((id) => !id.includes(':'));
  2872. function isInNodeModules(id) {
  2873. return id.includes('node_modules');
  2874. }
  2875. // TODO: use import()
  2876. const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)));
  2877. function resolveDependencyVersion(dep, pkgRelativePath = '../../package.json') {
  2878. const pkgPath = path$3.resolve(_require.resolve(dep), pkgRelativePath);
  2879. return JSON.parse(fs$1.readFileSync(pkgPath, 'utf-8')).version;
  2880. }
  2881. const rollupVersion = resolveDependencyVersion('rollup');
  2882. // set in bin/vite.js
  2883. const filter = process.env.VITE_DEBUG_FILTER;
  2884. const DEBUG = process.env.DEBUG;
  2885. function createDebugger(namespace, options = {}) {
  2886. const log = debug$2(namespace);
  2887. const { onlyWhenFocused } = options;
  2888. let enabled = log.enabled;
  2889. if (enabled && onlyWhenFocused) {
  2890. const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace;
  2891. enabled = !!DEBUG?.includes(ns);
  2892. }
  2893. if (enabled) {
  2894. return (...args) => {
  2895. if (!filter || args.some((a) => a?.includes?.(filter))) {
  2896. log(...args);
  2897. }
  2898. };
  2899. }
  2900. }
  2901. function testCaseInsensitiveFS() {
  2902. if (!CLIENT_ENTRY.endsWith('client.mjs')) {
  2903. throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`);
  2904. }
  2905. if (!fs$1.existsSync(CLIENT_ENTRY)) {
  2906. throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' +
  2907. CLIENT_ENTRY);
  2908. }
  2909. return fs$1.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'));
  2910. }
  2911. const isCaseInsensitiveFS = testCaseInsensitiveFS();
  2912. const VOLUME_RE = /^[A-Z]:/i;
  2913. function normalizePath(id) {
  2914. return path$3.posix.normalize(isWindows ? slash(id) : id);
  2915. }
  2916. function fsPathFromId(id) {
  2917. const fsPath = normalizePath(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
  2918. return fsPath[0] === '/' || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
  2919. }
  2920. function fsPathFromUrl(url) {
  2921. return fsPathFromId(cleanUrl(url));
  2922. }
  2923. /**
  2924. * Check if dir is a parent of file
  2925. *
  2926. * Warning: parameters are not validated, only works with normalized absolute paths
  2927. *
  2928. * @param dir - normalized absolute path
  2929. * @param file - normalized absolute path
  2930. * @returns true if dir is a parent of file
  2931. */
  2932. function isParentDirectory(dir, file) {
  2933. dir = withTrailingSlash(dir);
  2934. return (file.startsWith(dir) ||
  2935. (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
  2936. }
  2937. /**
  2938. * Check if 2 file name are identical
  2939. *
  2940. * Warning: parameters are not validated, only works with normalized absolute paths
  2941. *
  2942. * @param file1 - normalized absolute path
  2943. * @param file2 - normalized absolute path
  2944. * @returns true if both files url are identical
  2945. */
  2946. function isSameFileUri(file1, file2) {
  2947. return (file1 === file2 ||
  2948. (isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase()));
  2949. }
  2950. const trailingSeparatorRE = /[?&]$/;
  2951. const timestampRE = /\bt=\d{13}&?\b/;
  2952. function removeTimestampQuery(url) {
  2953. return url.replace(timestampRE, '').replace(trailingSeparatorRE, '');
  2954. }
  2955. function isObject$1(value) {
  2956. return Object.prototype.toString.call(value) === '[object Object]';
  2957. }
  2958. function tryStatSync(file) {
  2959. try {
  2960. // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
  2961. return fs$1.statSync(file, { throwIfNoEntry: false });
  2962. }
  2963. catch {
  2964. // Ignore errors
  2965. }
  2966. }
  2967. function isFileReadable(filename) {
  2968. if (!tryStatSync(filename)) {
  2969. return false;
  2970. }
  2971. try {
  2972. // Check if current process has read permission to the file
  2973. fs$1.accessSync(filename, fs$1.constants.R_OK);
  2974. return true;
  2975. }
  2976. catch {
  2977. return false;
  2978. }
  2979. }
  2980. function arraify(target) {
  2981. return Array.isArray(target) ? target : [target];
  2982. }
  2983. path$3.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))));
  2984. function backwardCompatibleWorkerPlugins(plugins) {
  2985. if (Array.isArray(plugins)) {
  2986. return plugins;
  2987. }
  2988. if (typeof plugins === 'function') {
  2989. return plugins();
  2990. }
  2991. return [];
  2992. }
  2993. function mergeConfigRecursively(defaults, overrides, rootPath) {
  2994. const merged = { ...defaults };
  2995. for (const key in overrides) {
  2996. const value = overrides[key];
  2997. if (value == null) {
  2998. continue;
  2999. }
  3000. const existing = merged[key];
  3001. if (existing == null) {
  3002. merged[key] = value;
  3003. continue;
  3004. }
  3005. // fields that require special handling
  3006. if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
  3007. merged[key] = mergeAlias(existing, value);
  3008. continue;
  3009. }
  3010. else if (key === 'assetsInclude' && rootPath === '') {
  3011. merged[key] = [].concat(existing, value);
  3012. continue;
  3013. }
  3014. else if (key === 'noExternal' &&
  3015. rootPath === 'ssr' &&
  3016. (existing === true || value === true)) {
  3017. merged[key] = true;
  3018. continue;
  3019. }
  3020. else if (key === 'plugins' && rootPath === 'worker') {
  3021. merged[key] = () => [
  3022. ...backwardCompatibleWorkerPlugins(existing),
  3023. ...backwardCompatibleWorkerPlugins(value),
  3024. ];
  3025. continue;
  3026. }
  3027. if (Array.isArray(existing) || Array.isArray(value)) {
  3028. merged[key] = [...arraify(existing), ...arraify(value)];
  3029. continue;
  3030. }
  3031. if (isObject$1(existing) && isObject$1(value)) {
  3032. merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
  3033. continue;
  3034. }
  3035. merged[key] = value;
  3036. }
  3037. return merged;
  3038. }
  3039. function mergeConfig(defaults, overrides, isRoot = true) {
  3040. if (typeof defaults === 'function' || typeof overrides === 'function') {
  3041. throw new Error(`Cannot merge config in form of callback`);
  3042. }
  3043. return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.');
  3044. }
  3045. function mergeAlias(a, b) {
  3046. if (!a)
  3047. return b;
  3048. if (!b)
  3049. return a;
  3050. if (isObject$1(a) && isObject$1(b)) {
  3051. return { ...a, ...b };
  3052. }
  3053. // the order is flipped because the alias is resolved from top-down,
  3054. // where the later should have higher priority
  3055. return [...normalizeAlias(b), ...normalizeAlias(a)];
  3056. }
  3057. function normalizeAlias(o = []) {
  3058. return Array.isArray(o)
  3059. ? o.map(normalizeSingleAlias)
  3060. : Object.keys(o).map((find) => normalizeSingleAlias({
  3061. find,
  3062. replacement: o[find],
  3063. }));
  3064. }
  3065. // https://github.com/vitejs/vite/issues/1363
  3066. // work around https://github.com/rollup/plugins/issues/759
  3067. function normalizeSingleAlias({ find, replacement, customResolver, }) {
  3068. if (typeof find === 'string' &&
  3069. find[find.length - 1] === '/' &&
  3070. replacement[replacement.length - 1] === '/') {
  3071. find = find.slice(0, find.length - 1);
  3072. replacement = replacement.slice(0, replacement.length - 1);
  3073. }
  3074. const alias = {
  3075. find,
  3076. replacement,
  3077. };
  3078. if (customResolver) {
  3079. alias.customResolver = customResolver;
  3080. }
  3081. return alias;
  3082. }
  3083. // This file will be built for both ESM and CJS. Avoid relying on other modules as possible.
  3084. // copy from constants.ts
  3085. const CSS_LANGS_RE =
  3086. // eslint-disable-next-line regexp/no-unused-capturing-group
  3087. /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
  3088. const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
  3089. // Use splitVendorChunkPlugin() to get the same manualChunks strategy as Vite 2.7
  3090. // We don't recommend using this strategy as a general solution moving forward
  3091. // splitVendorChunk is a simple index/vendor strategy that was used in Vite
  3092. // until v2.8. It is exposed to let people continue to use it in case it was
  3093. // working well for their setups.
  3094. // The cache needs to be reset on buildStart for watch mode to work correctly
  3095. // Don't use this manualChunks strategy for ssr, lib mode, and 'umd' or 'iife'
  3096. /**
  3097. * @deprecated use build.rollupOutput.manualChunks or framework specific configuration
  3098. */
  3099. class SplitVendorChunkCache {
  3100. cache;
  3101. constructor() {
  3102. this.cache = new Map();
  3103. }
  3104. reset() {
  3105. this.cache = new Map();
  3106. }
  3107. }
  3108. /**
  3109. * @deprecated use build.rollupOutput.manualChunks or framework specific configuration
  3110. */
  3111. function splitVendorChunk(options = {}) {
  3112. const cache = options.cache ?? new SplitVendorChunkCache();
  3113. return (id, { getModuleInfo }) => {
  3114. if (isInNodeModules(id) &&
  3115. !isCSSRequest(id) &&
  3116. staticImportedByEntry(id, getModuleInfo, cache.cache)) {
  3117. return 'vendor';
  3118. }
  3119. };
  3120. }
  3121. function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
  3122. if (cache.has(id)) {
  3123. return cache.get(id);
  3124. }
  3125. if (importStack.includes(id)) {
  3126. // circular deps!
  3127. cache.set(id, false);
  3128. return false;
  3129. }
  3130. const mod = getModuleInfo(id);
  3131. if (!mod) {
  3132. cache.set(id, false);
  3133. return false;
  3134. }
  3135. if (mod.isEntry) {
  3136. cache.set(id, true);
  3137. return true;
  3138. }
  3139. const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id)));
  3140. cache.set(id, someImporterIs);
  3141. return someImporterIs;
  3142. }
  3143. /**
  3144. * @deprecated use build.rollupOutput.manualChunks or framework specific configuration
  3145. */
  3146. function splitVendorChunkPlugin() {
  3147. const caches = [];
  3148. function createSplitVendorChunk(output, config) {
  3149. const cache = new SplitVendorChunkCache();
  3150. caches.push(cache);
  3151. const build = config.build ?? {};
  3152. const format = output?.format;
  3153. if (!build.ssr && !build.lib && format !== 'umd' && format !== 'iife') {
  3154. return splitVendorChunk({ cache });
  3155. }
  3156. }
  3157. return {
  3158. name: 'vite:split-vendor-chunk',
  3159. config(config) {
  3160. let outputs = config?.build?.rollupOptions?.output;
  3161. if (outputs) {
  3162. outputs = arraify(outputs);
  3163. for (const output of outputs) {
  3164. const viteManualChunks = createSplitVendorChunk(output, config);
  3165. if (viteManualChunks) {
  3166. if (output.manualChunks) {
  3167. if (typeof output.manualChunks === 'function') {
  3168. const userManualChunks = output.manualChunks;
  3169. output.manualChunks = (id, api) => {
  3170. return userManualChunks(id, api) ?? viteManualChunks(id, api);
  3171. };
  3172. }
  3173. else {
  3174. // else, leave the object form of manualChunks untouched, as
  3175. // we can't safely replicate rollup handling.
  3176. // eslint-disable-next-line no-console
  3177. console.warn("(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead.");
  3178. }
  3179. }
  3180. else {
  3181. output.manualChunks = viteManualChunks;
  3182. }
  3183. }
  3184. }
  3185. }
  3186. else {
  3187. return {
  3188. build: {
  3189. rollupOptions: {
  3190. output: {
  3191. manualChunks: createSplitVendorChunk({}, config),
  3192. },
  3193. },
  3194. },
  3195. };
  3196. }
  3197. },
  3198. buildStart() {
  3199. caches.forEach((cache) => cache.reset());
  3200. },
  3201. };
  3202. }
  3203. var convertSourceMap$1 = {};
  3204. (function (exports) {
  3205. Object.defineProperty(exports, 'commentRegex', {
  3206. get: function getCommentRegex () {
  3207. // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
  3208. return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
  3209. }
  3210. });
  3211. Object.defineProperty(exports, 'mapFileCommentRegex', {
  3212. get: function getMapFileCommentRegex () {
  3213. // Matches sourceMappingURL in either // or /* comment styles.
  3214. return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
  3215. }
  3216. });
  3217. var decodeBase64;
  3218. if (typeof Buffer !== 'undefined') {
  3219. if (typeof Buffer.from === 'function') {
  3220. decodeBase64 = decodeBase64WithBufferFrom;
  3221. } else {
  3222. decodeBase64 = decodeBase64WithNewBuffer;
  3223. }
  3224. } else {
  3225. decodeBase64 = decodeBase64WithAtob;
  3226. }
  3227. function decodeBase64WithBufferFrom(base64) {
  3228. return Buffer.from(base64, 'base64').toString();
  3229. }
  3230. function decodeBase64WithNewBuffer(base64) {
  3231. if (typeof value === 'number') {
  3232. throw new TypeError('The value to decode must not be of type number.');
  3233. }
  3234. return new Buffer(base64, 'base64').toString();
  3235. }
  3236. function decodeBase64WithAtob(base64) {
  3237. return decodeURIComponent(escape(atob(base64)));
  3238. }
  3239. function stripComment(sm) {
  3240. return sm.split(',').pop();
  3241. }
  3242. function readFromFileMap(sm, read) {
  3243. var r = exports.mapFileCommentRegex.exec(sm);
  3244. // for some odd reason //# .. captures in 1 and /* .. */ in 2
  3245. var filename = r[1] || r[2];
  3246. try {
  3247. var sm = read(filename);
  3248. if (sm != null && typeof sm.catch === 'function') {
  3249. return sm.catch(throwError);
  3250. } else {
  3251. return sm;
  3252. }
  3253. } catch (e) {
  3254. throwError(e);
  3255. }
  3256. function throwError(e) {
  3257. throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack);
  3258. }
  3259. }
  3260. function Converter (sm, opts) {
  3261. opts = opts || {};
  3262. if (opts.hasComment) {
  3263. sm = stripComment(sm);
  3264. }
  3265. if (opts.encoding === 'base64') {
  3266. sm = decodeBase64(sm);
  3267. } else if (opts.encoding === 'uri') {
  3268. sm = decodeURIComponent(sm);
  3269. }
  3270. if (opts.isJSON || opts.encoding) {
  3271. sm = JSON.parse(sm);
  3272. }
  3273. this.sourcemap = sm;
  3274. }
  3275. Converter.prototype.toJSON = function (space) {
  3276. return JSON.stringify(this.sourcemap, null, space);
  3277. };
  3278. if (typeof Buffer !== 'undefined') {
  3279. if (typeof Buffer.from === 'function') {
  3280. Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
  3281. } else {
  3282. Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
  3283. }
  3284. } else {
  3285. Converter.prototype.toBase64 = encodeBase64WithBtoa;
  3286. }
  3287. function encodeBase64WithBufferFrom() {
  3288. var json = this.toJSON();
  3289. return Buffer.from(json, 'utf8').toString('base64');
  3290. }
  3291. function encodeBase64WithNewBuffer() {
  3292. var json = this.toJSON();
  3293. if (typeof json === 'number') {
  3294. throw new TypeError('The json to encode must not be of type number.');
  3295. }
  3296. return new Buffer(json, 'utf8').toString('base64');
  3297. }
  3298. function encodeBase64WithBtoa() {
  3299. var json = this.toJSON();
  3300. return btoa(unescape(encodeURIComponent(json)));
  3301. }
  3302. Converter.prototype.toURI = function () {
  3303. var json = this.toJSON();
  3304. return encodeURIComponent(json);
  3305. };
  3306. Converter.prototype.toComment = function (options) {
  3307. var encoding, content, data;
  3308. if (options != null && options.encoding === 'uri') {
  3309. encoding = '';
  3310. content = this.toURI();
  3311. } else {
  3312. encoding = ';base64';
  3313. content = this.toBase64();
  3314. }
  3315. data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content;
  3316. return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  3317. };
  3318. // returns copy instead of original
  3319. Converter.prototype.toObject = function () {
  3320. return JSON.parse(this.toJSON());
  3321. };
  3322. Converter.prototype.addProperty = function (key, value) {
  3323. if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
  3324. return this.setProperty(key, value);
  3325. };
  3326. Converter.prototype.setProperty = function (key, value) {
  3327. this.sourcemap[key] = value;
  3328. return this;
  3329. };
  3330. Converter.prototype.getProperty = function (key) {
  3331. return this.sourcemap[key];
  3332. };
  3333. exports.fromObject = function (obj) {
  3334. return new Converter(obj);
  3335. };
  3336. exports.fromJSON = function (json) {
  3337. return new Converter(json, { isJSON: true });
  3338. };
  3339. exports.fromURI = function (uri) {
  3340. return new Converter(uri, { encoding: 'uri' });
  3341. };
  3342. exports.fromBase64 = function (base64) {
  3343. return new Converter(base64, { encoding: 'base64' });
  3344. };
  3345. exports.fromComment = function (comment) {
  3346. var m, encoding;
  3347. comment = comment
  3348. .replace(/^\/\*/g, '//')
  3349. .replace(/\*\/$/g, '');
  3350. m = exports.commentRegex.exec(comment);
  3351. encoding = m && m[4] || 'uri';
  3352. return new Converter(comment, { encoding: encoding, hasComment: true });
  3353. };
  3354. function makeConverter(sm) {
  3355. return new Converter(sm, { isJSON: true });
  3356. }
  3357. exports.fromMapFileComment = function (comment, read) {
  3358. if (typeof read === 'string') {
  3359. throw new Error(
  3360. 'String directory paths are no longer supported with `fromMapFileComment`\n' +
  3361. 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
  3362. )
  3363. }
  3364. var sm = readFromFileMap(comment, read);
  3365. if (sm != null && typeof sm.then === 'function') {
  3366. return sm.then(makeConverter);
  3367. } else {
  3368. return makeConverter(sm);
  3369. }
  3370. };
  3371. // Finds last sourcemap comment in file or returns null if none was found
  3372. exports.fromSource = function (content) {
  3373. var m = content.match(exports.commentRegex);
  3374. return m ? exports.fromComment(m.pop()) : null;
  3375. };
  3376. // Finds last sourcemap comment in file or returns null if none was found
  3377. exports.fromMapFileSource = function (content, read) {
  3378. if (typeof read === 'string') {
  3379. throw new Error(
  3380. 'String directory paths are no longer supported with `fromMapFileSource`\n' +
  3381. 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
  3382. )
  3383. }
  3384. var m = content.match(exports.mapFileCommentRegex);
  3385. return m ? exports.fromMapFileComment(m.pop(), read) : null;
  3386. };
  3387. exports.removeComments = function (src) {
  3388. return src.replace(exports.commentRegex, '');
  3389. };
  3390. exports.removeMapFileComments = function (src) {
  3391. return src.replace(exports.mapFileCommentRegex, '');
  3392. };
  3393. exports.generateMapFileComment = function (file, options) {
  3394. var data = 'sourceMappingURL=' + file;
  3395. return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  3396. };
  3397. } (convertSourceMap$1));
  3398. var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1);
  3399. /*!
  3400. * etag
  3401. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  3402. * MIT Licensed
  3403. */
  3404. /**
  3405. * Module exports.
  3406. * @public
  3407. */
  3408. var etag_1 = etag;
  3409. /**
  3410. * Module dependencies.
  3411. * @private
  3412. */
  3413. var crypto$1 = require$$0$2;
  3414. var Stats = fs$2.Stats;
  3415. /**
  3416. * Module variables.
  3417. * @private
  3418. */
  3419. var toString$1 = Object.prototype.toString;
  3420. /**
  3421. * Generate an entity tag.
  3422. *
  3423. * @param {Buffer|string} entity
  3424. * @return {string}
  3425. * @private
  3426. */
  3427. function entitytag (entity) {
  3428. if (entity.length === 0) {
  3429. // fast-path empty
  3430. return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
  3431. }
  3432. // compute hash of entity
  3433. var hash = crypto$1
  3434. .createHash('sha1')
  3435. .update(entity, 'utf8')
  3436. .digest('base64')
  3437. .substring(0, 27);
  3438. // compute length of entity
  3439. var len = typeof entity === 'string'
  3440. ? Buffer.byteLength(entity, 'utf8')
  3441. : entity.length;
  3442. return '"' + len.toString(16) + '-' + hash + '"'
  3443. }
  3444. /**
  3445. * Create a simple ETag.
  3446. *
  3447. * @param {string|Buffer|Stats} entity
  3448. * @param {object} [options]
  3449. * @param {boolean} [options.weak]
  3450. * @return {String}
  3451. * @public
  3452. */
  3453. function etag (entity, options) {
  3454. if (entity == null) {
  3455. throw new TypeError('argument entity is required')
  3456. }
  3457. // support fs.Stats object
  3458. var isStats = isstats(entity);
  3459. var weak = options && typeof options.weak === 'boolean'
  3460. ? options.weak
  3461. : isStats;
  3462. // validate argument
  3463. if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
  3464. throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
  3465. }
  3466. // generate entity tag
  3467. var tag = isStats
  3468. ? stattag(entity)
  3469. : entitytag(entity);
  3470. return weak
  3471. ? 'W/' + tag
  3472. : tag
  3473. }
  3474. /**
  3475. * Determine if object is a Stats object.
  3476. *
  3477. * @param {object} obj
  3478. * @return {boolean}
  3479. * @api private
  3480. */
  3481. function isstats (obj) {
  3482. // genuine fs.Stats
  3483. if (typeof Stats === 'function' && obj instanceof Stats) {
  3484. return true
  3485. }
  3486. // quack quack
  3487. return obj && typeof obj === 'object' &&
  3488. 'ctime' in obj && toString$1.call(obj.ctime) === '[object Date]' &&
  3489. 'mtime' in obj && toString$1.call(obj.mtime) === '[object Date]' &&
  3490. 'ino' in obj && typeof obj.ino === 'number' &&
  3491. 'size' in obj && typeof obj.size === 'number'
  3492. }
  3493. /**
  3494. * Generate a tag for a stat.
  3495. *
  3496. * @param {object} stat
  3497. * @return {string}
  3498. * @private
  3499. */
  3500. function stattag (stat) {
  3501. var mtime = stat.mtime.getTime().toString(16);
  3502. var size = stat.size.toString(16);
  3503. return '"' + size + '-' + mtime + '"'
  3504. }
  3505. var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1);
  3506. class BitSet {
  3507. constructor(arg) {
  3508. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  3509. }
  3510. add(n) {
  3511. this.bits[n >> 5] |= 1 << (n & 31);
  3512. }
  3513. has(n) {
  3514. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  3515. }
  3516. }
  3517. class Chunk {
  3518. constructor(start, end, content) {
  3519. this.start = start;
  3520. this.end = end;
  3521. this.original = content;
  3522. this.intro = '';
  3523. this.outro = '';
  3524. this.content = content;
  3525. this.storeName = false;
  3526. this.edited = false;
  3527. {
  3528. this.previous = null;
  3529. this.next = null;
  3530. }
  3531. }
  3532. appendLeft(content) {
  3533. this.outro += content;
  3534. }
  3535. appendRight(content) {
  3536. this.intro = this.intro + content;
  3537. }
  3538. clone() {
  3539. const chunk = new Chunk(this.start, this.end, this.original);
  3540. chunk.intro = this.intro;
  3541. chunk.outro = this.outro;
  3542. chunk.content = this.content;
  3543. chunk.storeName = this.storeName;
  3544. chunk.edited = this.edited;
  3545. return chunk;
  3546. }
  3547. contains(index) {
  3548. return this.start < index && index < this.end;
  3549. }
  3550. eachNext(fn) {
  3551. let chunk = this;
  3552. while (chunk) {
  3553. fn(chunk);
  3554. chunk = chunk.next;
  3555. }
  3556. }
  3557. eachPrevious(fn) {
  3558. let chunk = this;
  3559. while (chunk) {
  3560. fn(chunk);
  3561. chunk = chunk.previous;
  3562. }
  3563. }
  3564. edit(content, storeName, contentOnly) {
  3565. this.content = content;
  3566. if (!contentOnly) {
  3567. this.intro = '';
  3568. this.outro = '';
  3569. }
  3570. this.storeName = storeName;
  3571. this.edited = true;
  3572. return this;
  3573. }
  3574. prependLeft(content) {
  3575. this.outro = content + this.outro;
  3576. }
  3577. prependRight(content) {
  3578. this.intro = content + this.intro;
  3579. }
  3580. reset() {
  3581. this.intro = '';
  3582. this.outro = '';
  3583. if (this.edited) {
  3584. this.content = this.original;
  3585. this.storeName = false;
  3586. this.edited = false;
  3587. }
  3588. }
  3589. split(index) {
  3590. const sliceIndex = index - this.start;
  3591. const originalBefore = this.original.slice(0, sliceIndex);
  3592. const originalAfter = this.original.slice(sliceIndex);
  3593. this.original = originalBefore;
  3594. const newChunk = new Chunk(index, this.end, originalAfter);
  3595. newChunk.outro = this.outro;
  3596. this.outro = '';
  3597. this.end = index;
  3598. if (this.edited) {
  3599. // after split we should save the edit content record into the correct chunk
  3600. // to make sure sourcemap correct
  3601. // For example:
  3602. // ' test'.trim()
  3603. // split -> ' ' + 'test'
  3604. // ✔️ edit -> '' + 'test'
  3605. // ✖️ edit -> 'test' + ''
  3606. // TODO is this block necessary?...
  3607. newChunk.edit('', false);
  3608. this.content = '';
  3609. } else {
  3610. this.content = originalBefore;
  3611. }
  3612. newChunk.next = this.next;
  3613. if (newChunk.next) newChunk.next.previous = newChunk;
  3614. newChunk.previous = this;
  3615. this.next = newChunk;
  3616. return newChunk;
  3617. }
  3618. toString() {
  3619. return this.intro + this.content + this.outro;
  3620. }
  3621. trimEnd(rx) {
  3622. this.outro = this.outro.replace(rx, '');
  3623. if (this.outro.length) return true;
  3624. const trimmed = this.content.replace(rx, '');
  3625. if (trimmed.length) {
  3626. if (trimmed !== this.content) {
  3627. this.split(this.start + trimmed.length).edit('', undefined, true);
  3628. if (this.edited) {
  3629. // save the change, if it has been edited
  3630. this.edit(trimmed, this.storeName, true);
  3631. }
  3632. }
  3633. return true;
  3634. } else {
  3635. this.edit('', undefined, true);
  3636. this.intro = this.intro.replace(rx, '');
  3637. if (this.intro.length) return true;
  3638. }
  3639. }
  3640. trimStart(rx) {
  3641. this.intro = this.intro.replace(rx, '');
  3642. if (this.intro.length) return true;
  3643. const trimmed = this.content.replace(rx, '');
  3644. if (trimmed.length) {
  3645. if (trimmed !== this.content) {
  3646. const newChunk = this.split(this.end - trimmed.length);
  3647. if (this.edited) {
  3648. // save the change, if it has been edited
  3649. newChunk.edit(trimmed, this.storeName, true);
  3650. }
  3651. this.edit('', undefined, true);
  3652. }
  3653. return true;
  3654. } else {
  3655. this.edit('', undefined, true);
  3656. this.outro = this.outro.replace(rx, '');
  3657. if (this.outro.length) return true;
  3658. }
  3659. }
  3660. }
  3661. function getBtoa() {
  3662. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  3663. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  3664. } else if (typeof Buffer === 'function') {
  3665. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  3666. } else {
  3667. return () => {
  3668. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  3669. };
  3670. }
  3671. }
  3672. const btoa$1 = /*#__PURE__*/ getBtoa();
  3673. class SourceMap {
  3674. constructor(properties) {
  3675. this.version = 3;
  3676. this.file = properties.file;
  3677. this.sources = properties.sources;
  3678. this.sourcesContent = properties.sourcesContent;
  3679. this.names = properties.names;
  3680. this.mappings = encode(properties.mappings);
  3681. if (typeof properties.x_google_ignoreList !== 'undefined') {
  3682. this.x_google_ignoreList = properties.x_google_ignoreList;
  3683. }
  3684. }
  3685. toString() {
  3686. return JSON.stringify(this);
  3687. }
  3688. toUrl() {
  3689. return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
  3690. }
  3691. }
  3692. function guessIndent(code) {
  3693. const lines = code.split('\n');
  3694. const tabbed = lines.filter((line) => /^\t+/.test(line));
  3695. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  3696. if (tabbed.length === 0 && spaced.length === 0) {
  3697. return null;
  3698. }
  3699. // More lines tabbed than spaced? Assume tabs, and
  3700. // default to tabs in the case of a tie (or nothing
  3701. // to go on)
  3702. if (tabbed.length >= spaced.length) {
  3703. return '\t';
  3704. }
  3705. // Otherwise, we need to guess the multiple
  3706. const min = spaced.reduce((previous, current) => {
  3707. const numSpaces = /^ +/.exec(current)[0].length;
  3708. return Math.min(numSpaces, previous);
  3709. }, Infinity);
  3710. return new Array(min + 1).join(' ');
  3711. }
  3712. function getRelativePath(from, to) {
  3713. const fromParts = from.split(/[/\\]/);
  3714. const toParts = to.split(/[/\\]/);
  3715. fromParts.pop(); // get dirname
  3716. while (fromParts[0] === toParts[0]) {
  3717. fromParts.shift();
  3718. toParts.shift();
  3719. }
  3720. if (fromParts.length) {
  3721. let i = fromParts.length;
  3722. while (i--) fromParts[i] = '..';
  3723. }
  3724. return fromParts.concat(toParts).join('/');
  3725. }
  3726. const toString = Object.prototype.toString;
  3727. function isObject(thing) {
  3728. return toString.call(thing) === '[object Object]';
  3729. }
  3730. function getLocator(source) {
  3731. const originalLines = source.split('\n');
  3732. const lineOffsets = [];
  3733. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  3734. lineOffsets.push(pos);
  3735. pos += originalLines[i].length + 1;
  3736. }
  3737. return function locate(index) {
  3738. let i = 0;
  3739. let j = lineOffsets.length;
  3740. while (i < j) {
  3741. const m = (i + j) >> 1;
  3742. if (index < lineOffsets[m]) {
  3743. j = m;
  3744. } else {
  3745. i = m + 1;
  3746. }
  3747. }
  3748. const line = i - 1;
  3749. const column = index - lineOffsets[line];
  3750. return { line, column };
  3751. };
  3752. }
  3753. const wordRegex = /\w/;
  3754. class Mappings {
  3755. constructor(hires) {
  3756. this.hires = hires;
  3757. this.generatedCodeLine = 0;
  3758. this.generatedCodeColumn = 0;
  3759. this.raw = [];
  3760. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  3761. this.pending = null;
  3762. }
  3763. addEdit(sourceIndex, content, loc, nameIndex) {
  3764. if (content.length) {
  3765. const contentLengthMinusOne = content.length - 1;
  3766. let contentLineEnd = content.indexOf('\n', 0);
  3767. let previousContentLineEnd = -1;
  3768. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  3769. // else code afterwards would fill one line too many
  3770. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  3771. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3772. if (nameIndex >= 0) {
  3773. segment.push(nameIndex);
  3774. }
  3775. this.rawSegments.push(segment);
  3776. this.generatedCodeLine += 1;
  3777. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3778. this.generatedCodeColumn = 0;
  3779. previousContentLineEnd = contentLineEnd;
  3780. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  3781. }
  3782. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3783. if (nameIndex >= 0) {
  3784. segment.push(nameIndex);
  3785. }
  3786. this.rawSegments.push(segment);
  3787. this.advance(content.slice(previousContentLineEnd + 1));
  3788. } else if (this.pending) {
  3789. this.rawSegments.push(this.pending);
  3790. this.advance(content);
  3791. }
  3792. this.pending = null;
  3793. }
  3794. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  3795. let originalCharIndex = chunk.start;
  3796. let first = true;
  3797. // when iterating each char, check if it's in a word boundary
  3798. let charInHiresBoundary = false;
  3799. while (originalCharIndex < chunk.end) {
  3800. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  3801. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3802. if (this.hires === 'boundary') {
  3803. // in hires "boundary", group segments per word boundary than per char
  3804. if (wordRegex.test(original[originalCharIndex])) {
  3805. // for first char in the boundary found, start the boundary by pushing a segment
  3806. if (!charInHiresBoundary) {
  3807. this.rawSegments.push(segment);
  3808. charInHiresBoundary = true;
  3809. }
  3810. } else {
  3811. // for non-word char, end the boundary by pushing a segment
  3812. this.rawSegments.push(segment);
  3813. charInHiresBoundary = false;
  3814. }
  3815. } else {
  3816. this.rawSegments.push(segment);
  3817. }
  3818. }
  3819. if (original[originalCharIndex] === '\n') {
  3820. loc.line += 1;
  3821. loc.column = 0;
  3822. this.generatedCodeLine += 1;
  3823. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3824. this.generatedCodeColumn = 0;
  3825. first = true;
  3826. } else {
  3827. loc.column += 1;
  3828. this.generatedCodeColumn += 1;
  3829. first = false;
  3830. }
  3831. originalCharIndex += 1;
  3832. }
  3833. this.pending = null;
  3834. }
  3835. advance(str) {
  3836. if (!str) return;
  3837. const lines = str.split('\n');
  3838. if (lines.length > 1) {
  3839. for (let i = 0; i < lines.length - 1; i++) {
  3840. this.generatedCodeLine++;
  3841. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3842. }
  3843. this.generatedCodeColumn = 0;
  3844. }
  3845. this.generatedCodeColumn += lines[lines.length - 1].length;
  3846. }
  3847. }
  3848. const n = '\n';
  3849. const warned = {
  3850. insertLeft: false,
  3851. insertRight: false,
  3852. storeName: false,
  3853. };
  3854. class MagicString {
  3855. constructor(string, options = {}) {
  3856. const chunk = new Chunk(0, string.length, string);
  3857. Object.defineProperties(this, {
  3858. original: { writable: true, value: string },
  3859. outro: { writable: true, value: '' },
  3860. intro: { writable: true, value: '' },
  3861. firstChunk: { writable: true, value: chunk },
  3862. lastChunk: { writable: true, value: chunk },
  3863. lastSearchedChunk: { writable: true, value: chunk },
  3864. byStart: { writable: true, value: {} },
  3865. byEnd: { writable: true, value: {} },
  3866. filename: { writable: true, value: options.filename },
  3867. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  3868. sourcemapLocations: { writable: true, value: new BitSet() },
  3869. storedNames: { writable: true, value: {} },
  3870. indentStr: { writable: true, value: undefined },
  3871. ignoreList: { writable: true, value: options.ignoreList },
  3872. });
  3873. this.byStart[0] = chunk;
  3874. this.byEnd[string.length] = chunk;
  3875. }
  3876. addSourcemapLocation(char) {
  3877. this.sourcemapLocations.add(char);
  3878. }
  3879. append(content) {
  3880. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  3881. this.outro += content;
  3882. return this;
  3883. }
  3884. appendLeft(index, content) {
  3885. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3886. this._split(index);
  3887. const chunk = this.byEnd[index];
  3888. if (chunk) {
  3889. chunk.appendLeft(content);
  3890. } else {
  3891. this.intro += content;
  3892. }
  3893. return this;
  3894. }
  3895. appendRight(index, content) {
  3896. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3897. this._split(index);
  3898. const chunk = this.byStart[index];
  3899. if (chunk) {
  3900. chunk.appendRight(content);
  3901. } else {
  3902. this.outro += content;
  3903. }
  3904. return this;
  3905. }
  3906. clone() {
  3907. const cloned = new MagicString(this.original, { filename: this.filename });
  3908. let originalChunk = this.firstChunk;
  3909. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  3910. while (originalChunk) {
  3911. cloned.byStart[clonedChunk.start] = clonedChunk;
  3912. cloned.byEnd[clonedChunk.end] = clonedChunk;
  3913. const nextOriginalChunk = originalChunk.next;
  3914. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  3915. if (nextClonedChunk) {
  3916. clonedChunk.next = nextClonedChunk;
  3917. nextClonedChunk.previous = clonedChunk;
  3918. clonedChunk = nextClonedChunk;
  3919. }
  3920. originalChunk = nextOriginalChunk;
  3921. }
  3922. cloned.lastChunk = clonedChunk;
  3923. if (this.indentExclusionRanges) {
  3924. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  3925. }
  3926. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  3927. cloned.intro = this.intro;
  3928. cloned.outro = this.outro;
  3929. return cloned;
  3930. }
  3931. generateDecodedMap(options) {
  3932. options = options || {};
  3933. const sourceIndex = 0;
  3934. const names = Object.keys(this.storedNames);
  3935. const mappings = new Mappings(options.hires);
  3936. const locate = getLocator(this.original);
  3937. if (this.intro) {
  3938. mappings.advance(this.intro);
  3939. }
  3940. this.firstChunk.eachNext((chunk) => {
  3941. const loc = locate(chunk.start);
  3942. if (chunk.intro.length) mappings.advance(chunk.intro);
  3943. if (chunk.edited) {
  3944. mappings.addEdit(
  3945. sourceIndex,
  3946. chunk.content,
  3947. loc,
  3948. chunk.storeName ? names.indexOf(chunk.original) : -1,
  3949. );
  3950. } else {
  3951. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  3952. }
  3953. if (chunk.outro.length) mappings.advance(chunk.outro);
  3954. });
  3955. return {
  3956. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  3957. sources: [
  3958. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  3959. ],
  3960. sourcesContent: options.includeContent ? [this.original] : undefined,
  3961. names,
  3962. mappings: mappings.raw,
  3963. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  3964. };
  3965. }
  3966. generateMap(options) {
  3967. return new SourceMap(this.generateDecodedMap(options));
  3968. }
  3969. _ensureindentStr() {
  3970. if (this.indentStr === undefined) {
  3971. this.indentStr = guessIndent(this.original);
  3972. }
  3973. }
  3974. _getRawIndentString() {
  3975. this._ensureindentStr();
  3976. return this.indentStr;
  3977. }
  3978. getIndentString() {
  3979. this._ensureindentStr();
  3980. return this.indentStr === null ? '\t' : this.indentStr;
  3981. }
  3982. indent(indentStr, options) {
  3983. const pattern = /^[^\r\n]/gm;
  3984. if (isObject(indentStr)) {
  3985. options = indentStr;
  3986. indentStr = undefined;
  3987. }
  3988. if (indentStr === undefined) {
  3989. this._ensureindentStr();
  3990. indentStr = this.indentStr || '\t';
  3991. }
  3992. if (indentStr === '') return this; // noop
  3993. options = options || {};
  3994. // Process exclusion ranges
  3995. const isExcluded = {};
  3996. if (options.exclude) {
  3997. const exclusions =
  3998. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  3999. exclusions.forEach((exclusion) => {
  4000. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  4001. isExcluded[i] = true;
  4002. }
  4003. });
  4004. }
  4005. let shouldIndentNextCharacter = options.indentStart !== false;
  4006. const replacer = (match) => {
  4007. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  4008. shouldIndentNextCharacter = true;
  4009. return match;
  4010. };
  4011. this.intro = this.intro.replace(pattern, replacer);
  4012. let charIndex = 0;
  4013. let chunk = this.firstChunk;
  4014. while (chunk) {
  4015. const end = chunk.end;
  4016. if (chunk.edited) {
  4017. if (!isExcluded[charIndex]) {
  4018. chunk.content = chunk.content.replace(pattern, replacer);
  4019. if (chunk.content.length) {
  4020. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  4021. }
  4022. }
  4023. } else {
  4024. charIndex = chunk.start;
  4025. while (charIndex < end) {
  4026. if (!isExcluded[charIndex]) {
  4027. const char = this.original[charIndex];
  4028. if (char === '\n') {
  4029. shouldIndentNextCharacter = true;
  4030. } else if (char !== '\r' && shouldIndentNextCharacter) {
  4031. shouldIndentNextCharacter = false;
  4032. if (charIndex === chunk.start) {
  4033. chunk.prependRight(indentStr);
  4034. } else {
  4035. this._splitChunk(chunk, charIndex);
  4036. chunk = chunk.next;
  4037. chunk.prependRight(indentStr);
  4038. }
  4039. }
  4040. }
  4041. charIndex += 1;
  4042. }
  4043. }
  4044. charIndex = chunk.end;
  4045. chunk = chunk.next;
  4046. }
  4047. this.outro = this.outro.replace(pattern, replacer);
  4048. return this;
  4049. }
  4050. insert() {
  4051. throw new Error(
  4052. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  4053. );
  4054. }
  4055. insertLeft(index, content) {
  4056. if (!warned.insertLeft) {
  4057. console.warn(
  4058. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  4059. ); // eslint-disable-line no-console
  4060. warned.insertLeft = true;
  4061. }
  4062. return this.appendLeft(index, content);
  4063. }
  4064. insertRight(index, content) {
  4065. if (!warned.insertRight) {
  4066. console.warn(
  4067. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  4068. ); // eslint-disable-line no-console
  4069. warned.insertRight = true;
  4070. }
  4071. return this.prependRight(index, content);
  4072. }
  4073. move(start, end, index) {
  4074. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  4075. this._split(start);
  4076. this._split(end);
  4077. this._split(index);
  4078. const first = this.byStart[start];
  4079. const last = this.byEnd[end];
  4080. const oldLeft = first.previous;
  4081. const oldRight = last.next;
  4082. const newRight = this.byStart[index];
  4083. if (!newRight && last === this.lastChunk) return this;
  4084. const newLeft = newRight ? newRight.previous : this.lastChunk;
  4085. if (oldLeft) oldLeft.next = oldRight;
  4086. if (oldRight) oldRight.previous = oldLeft;
  4087. if (newLeft) newLeft.next = first;
  4088. if (newRight) newRight.previous = last;
  4089. if (!first.previous) this.firstChunk = last.next;
  4090. if (!last.next) {
  4091. this.lastChunk = first.previous;
  4092. this.lastChunk.next = null;
  4093. }
  4094. first.previous = newLeft;
  4095. last.next = newRight || null;
  4096. if (!newLeft) this.firstChunk = first;
  4097. if (!newRight) this.lastChunk = last;
  4098. return this;
  4099. }
  4100. overwrite(start, end, content, options) {
  4101. options = options || {};
  4102. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  4103. }
  4104. update(start, end, content, options) {
  4105. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  4106. while (start < 0) start += this.original.length;
  4107. while (end < 0) end += this.original.length;
  4108. if (end > this.original.length) throw new Error('end is out of bounds');
  4109. if (start === end)
  4110. throw new Error(
  4111. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  4112. );
  4113. this._split(start);
  4114. this._split(end);
  4115. if (options === true) {
  4116. if (!warned.storeName) {
  4117. console.warn(
  4118. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  4119. ); // eslint-disable-line no-console
  4120. warned.storeName = true;
  4121. }
  4122. options = { storeName: true };
  4123. }
  4124. const storeName = options !== undefined ? options.storeName : false;
  4125. const overwrite = options !== undefined ? options.overwrite : false;
  4126. if (storeName) {
  4127. const original = this.original.slice(start, end);
  4128. Object.defineProperty(this.storedNames, original, {
  4129. writable: true,
  4130. value: true,
  4131. enumerable: true,
  4132. });
  4133. }
  4134. const first = this.byStart[start];
  4135. const last = this.byEnd[end];
  4136. if (first) {
  4137. let chunk = first;
  4138. while (chunk !== last) {
  4139. if (chunk.next !== this.byStart[chunk.end]) {
  4140. throw new Error('Cannot overwrite across a split point');
  4141. }
  4142. chunk = chunk.next;
  4143. chunk.edit('', false);
  4144. }
  4145. first.edit(content, storeName, !overwrite);
  4146. } else {
  4147. // must be inserting at the end
  4148. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  4149. // TODO last chunk in the array may not be the last chunk, if it's moved...
  4150. last.next = newChunk;
  4151. newChunk.previous = last;
  4152. }
  4153. return this;
  4154. }
  4155. prepend(content) {
  4156. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  4157. this.intro = content + this.intro;
  4158. return this;
  4159. }
  4160. prependLeft(index, content) {
  4161. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4162. this._split(index);
  4163. const chunk = this.byEnd[index];
  4164. if (chunk) {
  4165. chunk.prependLeft(content);
  4166. } else {
  4167. this.intro = content + this.intro;
  4168. }
  4169. return this;
  4170. }
  4171. prependRight(index, content) {
  4172. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4173. this._split(index);
  4174. const chunk = this.byStart[index];
  4175. if (chunk) {
  4176. chunk.prependRight(content);
  4177. } else {
  4178. this.outro = content + this.outro;
  4179. }
  4180. return this;
  4181. }
  4182. remove(start, end) {
  4183. while (start < 0) start += this.original.length;
  4184. while (end < 0) end += this.original.length;
  4185. if (start === end) return this;
  4186. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  4187. if (start > end) throw new Error('end must be greater than start');
  4188. this._split(start);
  4189. this._split(end);
  4190. let chunk = this.byStart[start];
  4191. while (chunk) {
  4192. chunk.intro = '';
  4193. chunk.outro = '';
  4194. chunk.edit('');
  4195. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4196. }
  4197. return this;
  4198. }
  4199. reset(start, end) {
  4200. while (start < 0) start += this.original.length;
  4201. while (end < 0) end += this.original.length;
  4202. if (start === end) return this;
  4203. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  4204. if (start > end) throw new Error('end must be greater than start');
  4205. this._split(start);
  4206. this._split(end);
  4207. let chunk = this.byStart[start];
  4208. while (chunk) {
  4209. chunk.reset();
  4210. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4211. }
  4212. return this;
  4213. }
  4214. lastChar() {
  4215. if (this.outro.length) return this.outro[this.outro.length - 1];
  4216. let chunk = this.lastChunk;
  4217. do {
  4218. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  4219. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  4220. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  4221. } while ((chunk = chunk.previous));
  4222. if (this.intro.length) return this.intro[this.intro.length - 1];
  4223. return '';
  4224. }
  4225. lastLine() {
  4226. let lineIndex = this.outro.lastIndexOf(n);
  4227. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  4228. let lineStr = this.outro;
  4229. let chunk = this.lastChunk;
  4230. do {
  4231. if (chunk.outro.length > 0) {
  4232. lineIndex = chunk.outro.lastIndexOf(n);
  4233. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  4234. lineStr = chunk.outro + lineStr;
  4235. }
  4236. if (chunk.content.length > 0) {
  4237. lineIndex = chunk.content.lastIndexOf(n);
  4238. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  4239. lineStr = chunk.content + lineStr;
  4240. }
  4241. if (chunk.intro.length > 0) {
  4242. lineIndex = chunk.intro.lastIndexOf(n);
  4243. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  4244. lineStr = chunk.intro + lineStr;
  4245. }
  4246. } while ((chunk = chunk.previous));
  4247. lineIndex = this.intro.lastIndexOf(n);
  4248. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  4249. return this.intro + lineStr;
  4250. }
  4251. slice(start = 0, end = this.original.length) {
  4252. while (start < 0) start += this.original.length;
  4253. while (end < 0) end += this.original.length;
  4254. let result = '';
  4255. // find start chunk
  4256. let chunk = this.firstChunk;
  4257. while (chunk && (chunk.start > start || chunk.end <= start)) {
  4258. // found end chunk before start
  4259. if (chunk.start < end && chunk.end >= end) {
  4260. return result;
  4261. }
  4262. chunk = chunk.next;
  4263. }
  4264. if (chunk && chunk.edited && chunk.start !== start)
  4265. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  4266. const startChunk = chunk;
  4267. while (chunk) {
  4268. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  4269. result += chunk.intro;
  4270. }
  4271. const containsEnd = chunk.start < end && chunk.end >= end;
  4272. if (containsEnd && chunk.edited && chunk.end !== end)
  4273. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  4274. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  4275. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  4276. result += chunk.content.slice(sliceStart, sliceEnd);
  4277. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  4278. result += chunk.outro;
  4279. }
  4280. if (containsEnd) {
  4281. break;
  4282. }
  4283. chunk = chunk.next;
  4284. }
  4285. return result;
  4286. }
  4287. // TODO deprecate this? not really very useful
  4288. snip(start, end) {
  4289. const clone = this.clone();
  4290. clone.remove(0, start);
  4291. clone.remove(end, clone.original.length);
  4292. return clone;
  4293. }
  4294. _split(index) {
  4295. if (this.byStart[index] || this.byEnd[index]) return;
  4296. let chunk = this.lastSearchedChunk;
  4297. const searchForward = index > chunk.end;
  4298. while (chunk) {
  4299. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  4300. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  4301. }
  4302. }
  4303. _splitChunk(chunk, index) {
  4304. if (chunk.edited && chunk.content.length) {
  4305. // zero-length edited chunks are a special case (overlapping replacements)
  4306. const loc = getLocator(this.original)(index);
  4307. throw new Error(
  4308. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  4309. );
  4310. }
  4311. const newChunk = chunk.split(index);
  4312. this.byEnd[index] = chunk;
  4313. this.byStart[index] = newChunk;
  4314. this.byEnd[newChunk.end] = newChunk;
  4315. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  4316. this.lastSearchedChunk = chunk;
  4317. return true;
  4318. }
  4319. toString() {
  4320. let str = this.intro;
  4321. let chunk = this.firstChunk;
  4322. while (chunk) {
  4323. str += chunk.toString();
  4324. chunk = chunk.next;
  4325. }
  4326. return str + this.outro;
  4327. }
  4328. isEmpty() {
  4329. let chunk = this.firstChunk;
  4330. do {
  4331. if (
  4332. (chunk.intro.length && chunk.intro.trim()) ||
  4333. (chunk.content.length && chunk.content.trim()) ||
  4334. (chunk.outro.length && chunk.outro.trim())
  4335. )
  4336. return false;
  4337. } while ((chunk = chunk.next));
  4338. return true;
  4339. }
  4340. length() {
  4341. let chunk = this.firstChunk;
  4342. let length = 0;
  4343. do {
  4344. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  4345. } while ((chunk = chunk.next));
  4346. return length;
  4347. }
  4348. trimLines() {
  4349. return this.trim('[\\r\\n]');
  4350. }
  4351. trim(charType) {
  4352. return this.trimStart(charType).trimEnd(charType);
  4353. }
  4354. trimEndAborted(charType) {
  4355. const rx = new RegExp((charType || '\\s') + '+$');
  4356. this.outro = this.outro.replace(rx, '');
  4357. if (this.outro.length) return true;
  4358. let chunk = this.lastChunk;
  4359. do {
  4360. const end = chunk.end;
  4361. const aborted = chunk.trimEnd(rx);
  4362. // if chunk was trimmed, we have a new lastChunk
  4363. if (chunk.end !== end) {
  4364. if (this.lastChunk === chunk) {
  4365. this.lastChunk = chunk.next;
  4366. }
  4367. this.byEnd[chunk.end] = chunk;
  4368. this.byStart[chunk.next.start] = chunk.next;
  4369. this.byEnd[chunk.next.end] = chunk.next;
  4370. }
  4371. if (aborted) return true;
  4372. chunk = chunk.previous;
  4373. } while (chunk);
  4374. return false;
  4375. }
  4376. trimEnd(charType) {
  4377. this.trimEndAborted(charType);
  4378. return this;
  4379. }
  4380. trimStartAborted(charType) {
  4381. const rx = new RegExp('^' + (charType || '\\s') + '+');
  4382. this.intro = this.intro.replace(rx, '');
  4383. if (this.intro.length) return true;
  4384. let chunk = this.firstChunk;
  4385. do {
  4386. const end = chunk.end;
  4387. const aborted = chunk.trimStart(rx);
  4388. if (chunk.end !== end) {
  4389. // special case...
  4390. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  4391. this.byEnd[chunk.end] = chunk;
  4392. this.byStart[chunk.next.start] = chunk.next;
  4393. this.byEnd[chunk.next.end] = chunk.next;
  4394. }
  4395. if (aborted) return true;
  4396. chunk = chunk.next;
  4397. } while (chunk);
  4398. return false;
  4399. }
  4400. trimStart(charType) {
  4401. this.trimStartAborted(charType);
  4402. return this;
  4403. }
  4404. hasChanged() {
  4405. return this.original !== this.toString();
  4406. }
  4407. _replaceRegexp(searchValue, replacement) {
  4408. function getReplacement(match, str) {
  4409. if (typeof replacement === 'string') {
  4410. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  4411. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  4412. if (i === '$') return '$';
  4413. if (i === '&') return match[0];
  4414. const num = +i;
  4415. if (num < match.length) return match[+i];
  4416. return `$${i}`;
  4417. });
  4418. } else {
  4419. return replacement(...match, match.index, str, match.groups);
  4420. }
  4421. }
  4422. function matchAll(re, str) {
  4423. let match;
  4424. const matches = [];
  4425. while ((match = re.exec(str))) {
  4426. matches.push(match);
  4427. }
  4428. return matches;
  4429. }
  4430. if (searchValue.global) {
  4431. const matches = matchAll(searchValue, this.original);
  4432. matches.forEach((match) => {
  4433. if (match.index != null) {
  4434. const replacement = getReplacement(match, this.original);
  4435. if (replacement !== match[0]) {
  4436. this.overwrite(
  4437. match.index,
  4438. match.index + match[0].length,
  4439. replacement
  4440. );
  4441. }
  4442. }
  4443. });
  4444. } else {
  4445. const match = this.original.match(searchValue);
  4446. if (match && match.index != null) {
  4447. const replacement = getReplacement(match, this.original);
  4448. if (replacement !== match[0]) {
  4449. this.overwrite(
  4450. match.index,
  4451. match.index + match[0].length,
  4452. replacement
  4453. );
  4454. }
  4455. }
  4456. }
  4457. return this;
  4458. }
  4459. _replaceString(string, replacement) {
  4460. const { original } = this;
  4461. const index = original.indexOf(string);
  4462. if (index !== -1) {
  4463. this.overwrite(index, index + string.length, replacement);
  4464. }
  4465. return this;
  4466. }
  4467. replace(searchValue, replacement) {
  4468. if (typeof searchValue === 'string') {
  4469. return this._replaceString(searchValue, replacement);
  4470. }
  4471. return this._replaceRegexp(searchValue, replacement);
  4472. }
  4473. _replaceAllString(string, replacement) {
  4474. const { original } = this;
  4475. const stringLength = string.length;
  4476. for (
  4477. let index = original.indexOf(string);
  4478. index !== -1;
  4479. index = original.indexOf(string, index + stringLength)
  4480. ) {
  4481. const previous = original.slice(index, index + stringLength);
  4482. if (previous !== replacement)
  4483. this.overwrite(index, index + stringLength, replacement);
  4484. }
  4485. return this;
  4486. }
  4487. replaceAll(searchValue, replacement) {
  4488. if (typeof searchValue === 'string') {
  4489. return this._replaceAllString(searchValue, replacement);
  4490. }
  4491. if (!searchValue.global) {
  4492. throw new TypeError(
  4493. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  4494. );
  4495. }
  4496. return this._replaceRegexp(searchValue, replacement);
  4497. }
  4498. }
  4499. const debug$1 = createDebugger('vite:sourcemap', {
  4500. onlyWhenFocused: true,
  4501. });
  4502. function genSourceMapUrl(map) {
  4503. if (typeof map !== 'string') {
  4504. map = JSON.stringify(map);
  4505. }
  4506. return `data:application/json;base64,${Buffer.from(map).toString('base64')}`;
  4507. }
  4508. function getCodeWithSourcemap(type, code, map) {
  4509. if (debug$1) {
  4510. code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
  4511. }
  4512. if (type === 'js') {
  4513. code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  4514. }
  4515. else if (type === 'css') {
  4516. code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
  4517. }
  4518. return code;
  4519. }
  4520. const debug = createDebugger('vite:send', {
  4521. onlyWhenFocused: true,
  4522. });
  4523. const alias = {
  4524. js: 'text/javascript',
  4525. css: 'text/css',
  4526. html: 'text/html',
  4527. json: 'application/json',
  4528. };
  4529. function send(req, res, content, type, options) {
  4530. const { etag = getEtag(content, { weak: true }), cacheControl = 'no-cache', headers, map, } = options;
  4531. if (res.writableEnded) {
  4532. return;
  4533. }
  4534. if (req.headers['if-none-match'] === etag) {
  4535. res.statusCode = 304;
  4536. res.end();
  4537. return;
  4538. }
  4539. res.setHeader('Content-Type', alias[type] || type);
  4540. res.setHeader('Cache-Control', cacheControl);
  4541. res.setHeader('Etag', etag);
  4542. if (headers) {
  4543. for (const name in headers) {
  4544. res.setHeader(name, headers[name]);
  4545. }
  4546. }
  4547. // inject source map reference
  4548. if (map && 'version' in map && map.mappings) {
  4549. if (type === 'js' || type === 'css') {
  4550. content = getCodeWithSourcemap(type, content.toString(), map);
  4551. }
  4552. }
  4553. // inject fallback sourcemap for js for improved debugging
  4554. // https://github.com/vitejs/vite/pull/13514#issuecomment-1592431496
  4555. else if (type === 'js' && (!map || map.mappings !== '')) {
  4556. const code = content.toString();
  4557. // if the code has existing inline sourcemap, assume it's correct and skip
  4558. if (convertSourceMap.mapFileCommentRegex.test(code)) {
  4559. debug?.(`Skipped injecting fallback sourcemap for ${req.url}`);
  4560. }
  4561. else {
  4562. const urlWithoutTimestamp = removeTimestampQuery(req.url);
  4563. const ms = new MagicString(code);
  4564. content = getCodeWithSourcemap(type, code, ms.generateMap({
  4565. source: path$3.basename(urlWithoutTimestamp),
  4566. hires: 'boundary',
  4567. includeContent: true,
  4568. }));
  4569. }
  4570. }
  4571. res.statusCode = 200;
  4572. res.end(content);
  4573. return;
  4574. }
  4575. /* eslint no-console: 0 */
  4576. const LogLevels = {
  4577. silent: 0,
  4578. error: 1,
  4579. warn: 2,
  4580. info: 3,
  4581. };
  4582. let lastType;
  4583. let lastMsg;
  4584. let sameCount = 0;
  4585. function clearScreen() {
  4586. const repeatCount = process.stdout.rows - 2;
  4587. const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : '';
  4588. console.log(blank);
  4589. readline.cursorTo(process.stdout, 0, 0);
  4590. readline.clearScreenDown(process.stdout);
  4591. }
  4592. // Only initialize the timeFormatter when the timestamp option is used, and
  4593. // reuse it across all loggers
  4594. let timeFormatter;
  4595. function getTimeFormatter() {
  4596. timeFormatter ??= new Intl.DateTimeFormat(undefined, {
  4597. hour: 'numeric',
  4598. minute: 'numeric',
  4599. second: 'numeric',
  4600. });
  4601. return timeFormatter;
  4602. }
  4603. function createLogger(level = 'info', options = {}) {
  4604. if (options.customLogger) {
  4605. return options.customLogger;
  4606. }
  4607. const loggedErrors = new WeakSet();
  4608. const { prefix = '[vite]', allowClearScreen = true } = options;
  4609. const thresh = LogLevels[level];
  4610. const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  4611. const clear = canClearScreen ? clearScreen : () => { };
  4612. function format(type, msg, options = {}) {
  4613. if (options.timestamp) {
  4614. const tag = type === 'info'
  4615. ? colors.cyan(colors.bold(prefix))
  4616. : type === 'warn'
  4617. ? colors.yellow(colors.bold(prefix))
  4618. : colors.red(colors.bold(prefix));
  4619. return `${colors.dim(getTimeFormatter().format(new Date()))} ${tag} ${msg}`;
  4620. }
  4621. else {
  4622. return msg;
  4623. }
  4624. }
  4625. function output(type, msg, options = {}) {
  4626. if (thresh >= LogLevels[type]) {
  4627. const method = type === 'info' ? 'log' : type;
  4628. if (options.error) {
  4629. loggedErrors.add(options.error);
  4630. }
  4631. if (canClearScreen) {
  4632. if (type === lastType && msg === lastMsg) {
  4633. sameCount++;
  4634. clear();
  4635. console[method](format(type, msg, options), colors.yellow(`(x${sameCount + 1})`));
  4636. }
  4637. else {
  4638. sameCount = 0;
  4639. lastMsg = msg;
  4640. lastType = type;
  4641. if (options.clear) {
  4642. clear();
  4643. }
  4644. console[method](format(type, msg, options));
  4645. }
  4646. }
  4647. else {
  4648. console[method](format(type, msg, options));
  4649. }
  4650. }
  4651. }
  4652. const warnedMessages = new Set();
  4653. const logger = {
  4654. hasWarned: false,
  4655. info(msg, opts) {
  4656. output('info', msg, opts);
  4657. },
  4658. warn(msg, opts) {
  4659. logger.hasWarned = true;
  4660. output('warn', msg, opts);
  4661. },
  4662. warnOnce(msg, opts) {
  4663. if (warnedMessages.has(msg))
  4664. return;
  4665. logger.hasWarned = true;
  4666. output('warn', msg, opts);
  4667. warnedMessages.add(msg);
  4668. },
  4669. error(msg, opts) {
  4670. logger.hasWarned = true;
  4671. output('error', msg, opts);
  4672. },
  4673. clearScreen(type) {
  4674. if (thresh >= LogLevels[type]) {
  4675. clear();
  4676. }
  4677. },
  4678. hasErrorLogged(error) {
  4679. return loggedErrors.has(error);
  4680. },
  4681. };
  4682. return logger;
  4683. }
  4684. // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
  4685. const ROOT_FILES = [
  4686. // '.git',
  4687. // https://pnpm.io/workspaces/
  4688. 'pnpm-workspace.yaml',
  4689. // https://rushjs.io/pages/advanced/config_files/
  4690. // 'rush.json',
  4691. // https://nx.dev/latest/react/getting-started/nx-setup
  4692. // 'workspace.json',
  4693. // 'nx.json',
  4694. // https://github.com/lerna/lerna#lernajson
  4695. 'lerna.json',
  4696. ];
  4697. // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
  4698. // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
  4699. function hasWorkspacePackageJSON(root) {
  4700. const path = path$3.join(root, 'package.json');
  4701. if (!isFileReadable(path)) {
  4702. return false;
  4703. }
  4704. try {
  4705. const content = JSON.parse(fs$1.readFileSync(path, 'utf-8')) || {};
  4706. return !!content.workspaces;
  4707. }
  4708. catch {
  4709. return false;
  4710. }
  4711. }
  4712. function hasRootFile(root) {
  4713. return ROOT_FILES.some((file) => fs$1.existsSync(path$3.join(root, file)));
  4714. }
  4715. function hasPackageJSON(root) {
  4716. const path = path$3.join(root, 'package.json');
  4717. return fs$1.existsSync(path);
  4718. }
  4719. /**
  4720. * Search up for the nearest `package.json`
  4721. */
  4722. function searchForPackageRoot(current, root = current) {
  4723. if (hasPackageJSON(current))
  4724. return current;
  4725. const dir = path$3.dirname(current);
  4726. // reach the fs root
  4727. if (!dir || dir === current)
  4728. return root;
  4729. return searchForPackageRoot(dir, root);
  4730. }
  4731. /**
  4732. * Search up for the nearest workspace root
  4733. */
  4734. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  4735. if (hasRootFile(current))
  4736. return current;
  4737. if (hasWorkspacePackageJSON(current))
  4738. return current;
  4739. const dir = path$3.dirname(current);
  4740. // reach the fs root
  4741. if (!dir || dir === current)
  4742. return root;
  4743. return searchForWorkspaceRoot(dir, root);
  4744. }
  4745. /**
  4746. * Check if the url is allowed to be served, via the `server.fs` config.
  4747. */
  4748. function isFileServingAllowed(url, server) {
  4749. if (!server.config.server.fs.strict)
  4750. return true;
  4751. const file = fsPathFromUrl(url);
  4752. if (server._fsDenyGlob(file))
  4753. return false;
  4754. if (server.moduleGraph.safeModulesPath.has(file))
  4755. return true;
  4756. if (server.config.server.fs.allow.some((uri) => isSameFileUri(uri, file) || isParentDirectory(uri, file)))
  4757. return true;
  4758. return false;
  4759. }
  4760. var main$1 = {exports: {}};
  4761. var name = "dotenv";
  4762. var version$1 = "16.4.5";
  4763. var description = "Loads environment variables from .env file";
  4764. var main = "lib/main.js";
  4765. var types = "lib/main.d.ts";
  4766. var exports$1 = {
  4767. ".": {
  4768. types: "./lib/main.d.ts",
  4769. require: "./lib/main.js",
  4770. "default": "./lib/main.js"
  4771. },
  4772. "./config": "./config.js",
  4773. "./config.js": "./config.js",
  4774. "./lib/env-options": "./lib/env-options.js",
  4775. "./lib/env-options.js": "./lib/env-options.js",
  4776. "./lib/cli-options": "./lib/cli-options.js",
  4777. "./lib/cli-options.js": "./lib/cli-options.js",
  4778. "./package.json": "./package.json"
  4779. };
  4780. var scripts = {
  4781. "dts-check": "tsc --project tests/types/tsconfig.json",
  4782. lint: "standard",
  4783. "lint-readme": "standard-markdown",
  4784. pretest: "npm run lint && npm run dts-check",
  4785. test: "tap tests/*.js --100 -Rspec",
  4786. "test:coverage": "tap --coverage-report=lcov",
  4787. prerelease: "npm test",
  4788. release: "standard-version"
  4789. };
  4790. var repository = {
  4791. type: "git",
  4792. url: "git://github.com/motdotla/dotenv.git"
  4793. };
  4794. var funding = "https://dotenvx.com";
  4795. var keywords = [
  4796. "dotenv",
  4797. "env",
  4798. ".env",
  4799. "environment",
  4800. "variables",
  4801. "config",
  4802. "settings"
  4803. ];
  4804. var readmeFilename = "README.md";
  4805. var license = "BSD-2-Clause";
  4806. var devDependencies = {
  4807. "@definitelytyped/dtslint": "^0.0.133",
  4808. "@types/node": "^18.11.3",
  4809. decache: "^4.6.1",
  4810. sinon: "^14.0.1",
  4811. standard: "^17.0.0",
  4812. "standard-markdown": "^7.1.0",
  4813. "standard-version": "^9.5.0",
  4814. tap: "^16.3.0",
  4815. tar: "^6.1.11",
  4816. typescript: "^4.8.4"
  4817. };
  4818. var engines = {
  4819. node: ">=12"
  4820. };
  4821. var browser = {
  4822. fs: false
  4823. };
  4824. var require$$4 = {
  4825. name: name,
  4826. version: version$1,
  4827. description: description,
  4828. main: main,
  4829. types: types,
  4830. exports: exports$1,
  4831. scripts: scripts,
  4832. repository: repository,
  4833. funding: funding,
  4834. keywords: keywords,
  4835. readmeFilename: readmeFilename,
  4836. license: license,
  4837. devDependencies: devDependencies,
  4838. engines: engines,
  4839. browser: browser
  4840. };
  4841. const fs = fs$2;
  4842. const path = require$$0$1;
  4843. const os = require$$2;
  4844. const crypto = require$$0$2;
  4845. const packageJson = require$$4;
  4846. const version = packageJson.version;
  4847. const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
  4848. // Parse src into an Object
  4849. function parse (src) {
  4850. const obj = {};
  4851. // Convert buffer to string
  4852. let lines = src.toString();
  4853. // Convert line breaks to same format
  4854. lines = lines.replace(/\r\n?/mg, '\n');
  4855. let match;
  4856. while ((match = LINE.exec(lines)) != null) {
  4857. const key = match[1];
  4858. // Default undefined or null to empty string
  4859. let value = (match[2] || '');
  4860. // Remove whitespace
  4861. value = value.trim();
  4862. // Check if double quoted
  4863. const maybeQuote = value[0];
  4864. // Remove surrounding quotes
  4865. value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2');
  4866. // Expand newlines if double quoted
  4867. if (maybeQuote === '"') {
  4868. value = value.replace(/\\n/g, '\n');
  4869. value = value.replace(/\\r/g, '\r');
  4870. }
  4871. // Add to object
  4872. obj[key] = value;
  4873. }
  4874. return obj
  4875. }
  4876. function _parseVault (options) {
  4877. const vaultPath = _vaultPath(options);
  4878. // Parse .env.vault
  4879. const result = DotenvModule.configDotenv({ path: vaultPath });
  4880. if (!result.parsed) {
  4881. const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
  4882. err.code = 'MISSING_DATA';
  4883. throw err
  4884. }
  4885. // handle scenario for comma separated keys - for use with key rotation
  4886. // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod"
  4887. const keys = _dotenvKey(options).split(',');
  4888. const length = keys.length;
  4889. let decrypted;
  4890. for (let i = 0; i < length; i++) {
  4891. try {
  4892. // Get full key
  4893. const key = keys[i].trim();
  4894. // Get instructions for decrypt
  4895. const attrs = _instructions(result, key);
  4896. // Decrypt
  4897. decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
  4898. break
  4899. } catch (error) {
  4900. // last key
  4901. if (i + 1 >= length) {
  4902. throw error
  4903. }
  4904. // try next key
  4905. }
  4906. }
  4907. // Parse decrypted .env string
  4908. return DotenvModule.parse(decrypted)
  4909. }
  4910. function _log (message) {
  4911. console.log(`[dotenv@${version}][INFO] ${message}`);
  4912. }
  4913. function _warn (message) {
  4914. console.log(`[dotenv@${version}][WARN] ${message}`);
  4915. }
  4916. function _debug (message) {
  4917. console.log(`[dotenv@${version}][DEBUG] ${message}`);
  4918. }
  4919. function _dotenvKey (options) {
  4920. // prioritize developer directly setting options.DOTENV_KEY
  4921. if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
  4922. return options.DOTENV_KEY
  4923. }
  4924. // secondary infra already contains a DOTENV_KEY environment variable
  4925. if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
  4926. return process.env.DOTENV_KEY
  4927. }
  4928. // fallback to empty string
  4929. return ''
  4930. }
  4931. function _instructions (result, dotenvKey) {
  4932. // Parse DOTENV_KEY. Format is a URI
  4933. let uri;
  4934. try {
  4935. uri = new URL(dotenvKey);
  4936. } catch (error) {
  4937. if (error.code === 'ERR_INVALID_URL') {
  4938. const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development');
  4939. err.code = 'INVALID_DOTENV_KEY';
  4940. throw err
  4941. }
  4942. throw error
  4943. }
  4944. // Get decrypt key
  4945. const key = uri.password;
  4946. if (!key) {
  4947. const err = new Error('INVALID_DOTENV_KEY: Missing key part');
  4948. err.code = 'INVALID_DOTENV_KEY';
  4949. throw err
  4950. }
  4951. // Get environment
  4952. const environment = uri.searchParams.get('environment');
  4953. if (!environment) {
  4954. const err = new Error('INVALID_DOTENV_KEY: Missing environment part');
  4955. err.code = 'INVALID_DOTENV_KEY';
  4956. throw err
  4957. }
  4958. // Get ciphertext payload
  4959. const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
  4960. const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION
  4961. if (!ciphertext) {
  4962. const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
  4963. err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT';
  4964. throw err
  4965. }
  4966. return { ciphertext, key }
  4967. }
  4968. function _vaultPath (options) {
  4969. let possibleVaultPath = null;
  4970. if (options && options.path && options.path.length > 0) {
  4971. if (Array.isArray(options.path)) {
  4972. for (const filepath of options.path) {
  4973. if (fs.existsSync(filepath)) {
  4974. possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`;
  4975. }
  4976. }
  4977. } else {
  4978. possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`;
  4979. }
  4980. } else {
  4981. possibleVaultPath = path.resolve(process.cwd(), '.env.vault');
  4982. }
  4983. if (fs.existsSync(possibleVaultPath)) {
  4984. return possibleVaultPath
  4985. }
  4986. return null
  4987. }
  4988. function _resolveHome (envPath) {
  4989. return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
  4990. }
  4991. function _configVault (options) {
  4992. _log('Loading env from encrypted .env.vault');
  4993. const parsed = DotenvModule._parseVault(options);
  4994. let processEnv = process.env;
  4995. if (options && options.processEnv != null) {
  4996. processEnv = options.processEnv;
  4997. }
  4998. DotenvModule.populate(processEnv, parsed, options);
  4999. return { parsed }
  5000. }
  5001. function configDotenv (options) {
  5002. const dotenvPath = path.resolve(process.cwd(), '.env');
  5003. let encoding = 'utf8';
  5004. const debug = Boolean(options && options.debug);
  5005. if (options && options.encoding) {
  5006. encoding = options.encoding;
  5007. } else {
  5008. if (debug) {
  5009. _debug('No encoding is specified. UTF-8 is used by default');
  5010. }
  5011. }
  5012. let optionPaths = [dotenvPath]; // default, look for .env
  5013. if (options && options.path) {
  5014. if (!Array.isArray(options.path)) {
  5015. optionPaths = [_resolveHome(options.path)];
  5016. } else {
  5017. optionPaths = []; // reset default
  5018. for (const filepath of options.path) {
  5019. optionPaths.push(_resolveHome(filepath));
  5020. }
  5021. }
  5022. }
  5023. // Build the parsed data in a temporary object (because we need to return it). Once we have the final
  5024. // parsed data, we will combine it with process.env (or options.processEnv if provided).
  5025. let lastError;
  5026. const parsedAll = {};
  5027. for (const path of optionPaths) {
  5028. try {
  5029. // Specifying an encoding returns a string instead of a buffer
  5030. const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }));
  5031. DotenvModule.populate(parsedAll, parsed, options);
  5032. } catch (e) {
  5033. if (debug) {
  5034. _debug(`Failed to load ${path} ${e.message}`);
  5035. }
  5036. lastError = e;
  5037. }
  5038. }
  5039. let processEnv = process.env;
  5040. if (options && options.processEnv != null) {
  5041. processEnv = options.processEnv;
  5042. }
  5043. DotenvModule.populate(processEnv, parsedAll, options);
  5044. if (lastError) {
  5045. return { parsed: parsedAll, error: lastError }
  5046. } else {
  5047. return { parsed: parsedAll }
  5048. }
  5049. }
  5050. // Populates process.env from .env file
  5051. function config (options) {
  5052. // fallback to original dotenv if DOTENV_KEY is not set
  5053. if (_dotenvKey(options).length === 0) {
  5054. return DotenvModule.configDotenv(options)
  5055. }
  5056. const vaultPath = _vaultPath(options);
  5057. // dotenvKey exists but .env.vault file does not exist
  5058. if (!vaultPath) {
  5059. _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
  5060. return DotenvModule.configDotenv(options)
  5061. }
  5062. return DotenvModule._configVault(options)
  5063. }
  5064. function decrypt (encrypted, keyStr) {
  5065. const key = Buffer.from(keyStr.slice(-64), 'hex');
  5066. let ciphertext = Buffer.from(encrypted, 'base64');
  5067. const nonce = ciphertext.subarray(0, 12);
  5068. const authTag = ciphertext.subarray(-16);
  5069. ciphertext = ciphertext.subarray(12, -16);
  5070. try {
  5071. const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce);
  5072. aesgcm.setAuthTag(authTag);
  5073. return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
  5074. } catch (error) {
  5075. const isRange = error instanceof RangeError;
  5076. const invalidKeyLength = error.message === 'Invalid key length';
  5077. const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data';
  5078. if (isRange || invalidKeyLength) {
  5079. const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)');
  5080. err.code = 'INVALID_DOTENV_KEY';
  5081. throw err
  5082. } else if (decryptionFailed) {
  5083. const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY');
  5084. err.code = 'DECRYPTION_FAILED';
  5085. throw err
  5086. } else {
  5087. throw error
  5088. }
  5089. }
  5090. }
  5091. // Populate process.env with parsed values
  5092. function populate (processEnv, parsed, options = {}) {
  5093. const debug = Boolean(options && options.debug);
  5094. const override = Boolean(options && options.override);
  5095. if (typeof parsed !== 'object') {
  5096. const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate');
  5097. err.code = 'OBJECT_REQUIRED';
  5098. throw err
  5099. }
  5100. // Set process.env
  5101. for (const key of Object.keys(parsed)) {
  5102. if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
  5103. if (override === true) {
  5104. processEnv[key] = parsed[key];
  5105. }
  5106. if (debug) {
  5107. if (override === true) {
  5108. _debug(`"${key}" is already defined and WAS overwritten`);
  5109. } else {
  5110. _debug(`"${key}" is already defined and was NOT overwritten`);
  5111. }
  5112. }
  5113. } else {
  5114. processEnv[key] = parsed[key];
  5115. }
  5116. }
  5117. }
  5118. const DotenvModule = {
  5119. configDotenv,
  5120. _configVault,
  5121. _parseVault,
  5122. config,
  5123. decrypt,
  5124. parse,
  5125. populate
  5126. };
  5127. main$1.exports.configDotenv = DotenvModule.configDotenv;
  5128. main$1.exports._configVault = DotenvModule._configVault;
  5129. main$1.exports._parseVault = DotenvModule._parseVault;
  5130. main$1.exports.config = DotenvModule.config;
  5131. main$1.exports.decrypt = DotenvModule.decrypt;
  5132. var parse_1 = main$1.exports.parse = DotenvModule.parse;
  5133. main$1.exports.populate = DotenvModule.populate;
  5134. main$1.exports = DotenvModule;
  5135. // * /
  5136. // * (\\)? # is it escaped with a backslash?
  5137. // * (\$) # literal $
  5138. // * (?!\() # shouldnt be followed by parenthesis
  5139. // * (\{?) # first brace wrap opening
  5140. // * ([\w.]+) # key
  5141. // * (?::-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))? # optional default nested 3 times
  5142. // * (\}?) # last brace warp closing
  5143. // * /xi
  5144. const DOTENV_SUBSTITUTION_REGEX = /(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;
  5145. function _resolveEscapeSequences (value) {
  5146. return value.replace(/\\\$/g, '$')
  5147. }
  5148. function interpolate (value, processEnv, parsed) {
  5149. return value.replace(DOTENV_SUBSTITUTION_REGEX, (match, escaped, dollarSign, openBrace, key, defaultValue, closeBrace) => {
  5150. if (escaped === '\\') {
  5151. return match.slice(1)
  5152. } else {
  5153. if (processEnv[key]) {
  5154. if (processEnv[key] === parsed[key]) {
  5155. return processEnv[key]
  5156. } else {
  5157. // scenario: PASSWORD_EXPAND_NESTED=${PASSWORD_EXPAND}
  5158. return interpolate(processEnv[key], processEnv, parsed)
  5159. }
  5160. }
  5161. if (parsed[key]) {
  5162. // avoid recursion from EXPAND_SELF=$EXPAND_SELF
  5163. if (parsed[key] === value) {
  5164. return parsed[key]
  5165. } else {
  5166. return interpolate(parsed[key], processEnv, parsed)
  5167. }
  5168. }
  5169. if (defaultValue) {
  5170. if (defaultValue.startsWith('$')) {
  5171. return interpolate(defaultValue, processEnv, parsed)
  5172. } else {
  5173. return defaultValue
  5174. }
  5175. }
  5176. return ''
  5177. }
  5178. })
  5179. }
  5180. function expand (options) {
  5181. let processEnv = process.env;
  5182. if (options && options.processEnv != null) {
  5183. processEnv = options.processEnv;
  5184. }
  5185. for (const key in options.parsed) {
  5186. let value = options.parsed[key];
  5187. const inProcessEnv = Object.prototype.hasOwnProperty.call(processEnv, key);
  5188. if (inProcessEnv) {
  5189. if (processEnv[key] === options.parsed[key]) {
  5190. // assume was set to processEnv from the .env file if the values match and therefore interpolate
  5191. value = interpolate(value, processEnv, options.parsed);
  5192. } else {
  5193. // do not interpolate - assume processEnv had the intended value even if containing a $.
  5194. value = processEnv[key];
  5195. }
  5196. } else {
  5197. // not inProcessEnv so assume interpolation for this .env key
  5198. value = interpolate(value, processEnv, options.parsed);
  5199. }
  5200. options.parsed[key] = _resolveEscapeSequences(value);
  5201. }
  5202. for (const processKey in options.parsed) {
  5203. processEnv[processKey] = options.parsed[processKey];
  5204. }
  5205. return options
  5206. }
  5207. var expand_1 = expand;
  5208. function getEnvFilesForMode(mode, envDir) {
  5209. return [
  5210. /** default file */ `.env`,
  5211. /** local file */ `.env.local`,
  5212. /** mode file */ `.env.${mode}`,
  5213. /** mode local file */ `.env.${mode}.local`,
  5214. ].map((file) => normalizePath(path$3.join(envDir, file)));
  5215. }
  5216. function loadEnv(mode, envDir, prefixes = 'VITE_') {
  5217. if (mode === 'local') {
  5218. throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
  5219. `the .local postfix for .env files.`);
  5220. }
  5221. prefixes = arraify(prefixes);
  5222. const env = {};
  5223. const envFiles = getEnvFilesForMode(mode, envDir);
  5224. const parsed = Object.fromEntries(envFiles.flatMap((filePath) => {
  5225. if (!tryStatSync(filePath)?.isFile())
  5226. return [];
  5227. return Object.entries(parse_1(fs$1.readFileSync(filePath)));
  5228. }));
  5229. // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this
  5230. if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {
  5231. process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
  5232. }
  5233. // support BROWSER and BROWSER_ARGS env variables
  5234. if (parsed.BROWSER && process.env.BROWSER === undefined) {
  5235. process.env.BROWSER = parsed.BROWSER;
  5236. }
  5237. if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) {
  5238. process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
  5239. }
  5240. // let environment variables use each other. make a copy of `process.env` so that `dotenv-expand`
  5241. // doesn't re-assign the expanded values to the global `process.env`.
  5242. const processEnv = { ...process.env };
  5243. expand_1({ parsed, processEnv });
  5244. // only keys that start with prefix are exposed to client
  5245. for (const [key, value] of Object.entries(parsed)) {
  5246. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  5247. env[key] = value;
  5248. }
  5249. }
  5250. // check if there are actual env variables starting with VITE_*
  5251. // these are typically provided inline and should be prioritized
  5252. for (const key in process.env) {
  5253. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  5254. env[key] = process.env[key];
  5255. }
  5256. }
  5257. return env;
  5258. }
  5259. function resolveEnvPrefix({ envPrefix = 'VITE_', }) {
  5260. envPrefix = arraify(envPrefix);
  5261. if (envPrefix.includes('')) {
  5262. throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
  5263. }
  5264. return envPrefix;
  5265. }
  5266. exports.esbuildVersion = esbuild.version;
  5267. exports.createFilter = createFilter;
  5268. exports.createLogger = createLogger;
  5269. exports.isCSSRequest = isCSSRequest;
  5270. exports.isFileServingAllowed = isFileServingAllowed;
  5271. exports.loadEnv = loadEnv;
  5272. exports.mergeAlias = mergeAlias;
  5273. exports.mergeConfig = mergeConfig;
  5274. exports.normalizePath = normalizePath;
  5275. exports.resolveEnvPrefix = resolveEnvPrefix;
  5276. exports.rollupVersion = rollupVersion;
  5277. exports.searchForWorkspaceRoot = searchForWorkspaceRoot;
  5278. exports.send = send;
  5279. exports.splitVendorChunk = splitVendorChunk;
  5280. exports.splitVendorChunkPlugin = splitVendorChunkPlugin;
  5281. exports.version = VERSION;