dep-1be34a63.js 2.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266
  1. 'use strict';
  2. var fs$v = require('fs');
  3. var path$w = require('path');
  4. var require$$0$5 = require('os');
  5. var require$$0$4 = require('tty');
  6. var require$$0$7 = require('util');
  7. var require$$4$1 = require('net');
  8. var require$$0$b = require('events');
  9. var require$$0$a = require('url');
  10. var require$$1$3 = require('http');
  11. var require$$0$6 = require('stream');
  12. var resolve$4 = require('resolve');
  13. var require$$0$9 = require('module');
  14. var require$$1$4 = require('https');
  15. var require$$4$2 = require('tls');
  16. var require$$1$1 = require('crypto');
  17. var require$$0$8 = require('zlib');
  18. var require$$6 = require('assert');
  19. var require$$0$c = require('buffer');
  20. var qs = require('querystring');
  21. var require$$3$1 = require('repl');
  22. var require$$4 = require('vm');
  23. var require$$7 = require('console');
  24. var esbuild = require('esbuild');
  25. var require$$1$2 = require('worker_threads');
  26. var require$$1$5 = require('child_process');
  27. var readline = require('readline');
  28. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
  29. function _interopNamespace(e) {
  30. if (e && e.__esModule) return e;
  31. var n = Object.create(null);
  32. if (e) {
  33. Object.keys(e).forEach(function (k) {
  34. n[k] = e[k];
  35. });
  36. }
  37. n['default'] = e;
  38. return n;
  39. }
  40. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$v);
  41. var fs__namespace = /*#__PURE__*/_interopNamespace(fs$v);
  42. var path__default = /*#__PURE__*/_interopDefaultLegacy(path$w);
  43. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$5);
  44. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$4);
  45. var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7);
  46. var require$$4__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$4$1);
  47. var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$b);
  48. var require$$0__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$0$a);
  49. var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3);
  50. var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6);
  51. var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve$4);
  52. var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$9);
  53. var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$4);
  54. var require$$4__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$4$2);
  55. var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
  56. var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$8);
  57. var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6);
  58. var require$$0__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$0$c);
  59. var qs__namespace = /*#__PURE__*/_interopNamespace(qs);
  60. var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3$1);
  61. var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4);
  62. var require$$7__default = /*#__PURE__*/_interopDefaultLegacy(require$$7);
  63. var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1$2);
  64. var require$$1__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$1$5);
  65. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  66. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  67. function getDefaultExportFromCjs (x) {
  68. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  69. }
  70. function getAugmentedNamespace(n) {
  71. if (n.__esModule) return n;
  72. var a = Object.defineProperty({}, '__esModule', {value: true});
  73. Object.keys(n).forEach(function (k) {
  74. var d = Object.getOwnPropertyDescriptor(n, k);
  75. Object.defineProperty(a, k, d.get ? d : {
  76. enumerable: true,
  77. get: function () {
  78. return n[k];
  79. }
  80. });
  81. });
  82. return a;
  83. }
  84. function commonjsRequire (path) {
  85. throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  86. }
  87. var ansiStyles$2 = {exports: {}};
  88. var colorName$1 = {
  89. "aliceblue": [240, 248, 255],
  90. "antiquewhite": [250, 235, 215],
  91. "aqua": [0, 255, 255],
  92. "aquamarine": [127, 255, 212],
  93. "azure": [240, 255, 255],
  94. "beige": [245, 245, 220],
  95. "bisque": [255, 228, 196],
  96. "black": [0, 0, 0],
  97. "blanchedalmond": [255, 235, 205],
  98. "blue": [0, 0, 255],
  99. "blueviolet": [138, 43, 226],
  100. "brown": [165, 42, 42],
  101. "burlywood": [222, 184, 135],
  102. "cadetblue": [95, 158, 160],
  103. "chartreuse": [127, 255, 0],
  104. "chocolate": [210, 105, 30],
  105. "coral": [255, 127, 80],
  106. "cornflowerblue": [100, 149, 237],
  107. "cornsilk": [255, 248, 220],
  108. "crimson": [220, 20, 60],
  109. "cyan": [0, 255, 255],
  110. "darkblue": [0, 0, 139],
  111. "darkcyan": [0, 139, 139],
  112. "darkgoldenrod": [184, 134, 11],
  113. "darkgray": [169, 169, 169],
  114. "darkgreen": [0, 100, 0],
  115. "darkgrey": [169, 169, 169],
  116. "darkkhaki": [189, 183, 107],
  117. "darkmagenta": [139, 0, 139],
  118. "darkolivegreen": [85, 107, 47],
  119. "darkorange": [255, 140, 0],
  120. "darkorchid": [153, 50, 204],
  121. "darkred": [139, 0, 0],
  122. "darksalmon": [233, 150, 122],
  123. "darkseagreen": [143, 188, 143],
  124. "darkslateblue": [72, 61, 139],
  125. "darkslategray": [47, 79, 79],
  126. "darkslategrey": [47, 79, 79],
  127. "darkturquoise": [0, 206, 209],
  128. "darkviolet": [148, 0, 211],
  129. "deeppink": [255, 20, 147],
  130. "deepskyblue": [0, 191, 255],
  131. "dimgray": [105, 105, 105],
  132. "dimgrey": [105, 105, 105],
  133. "dodgerblue": [30, 144, 255],
  134. "firebrick": [178, 34, 34],
  135. "floralwhite": [255, 250, 240],
  136. "forestgreen": [34, 139, 34],
  137. "fuchsia": [255, 0, 255],
  138. "gainsboro": [220, 220, 220],
  139. "ghostwhite": [248, 248, 255],
  140. "gold": [255, 215, 0],
  141. "goldenrod": [218, 165, 32],
  142. "gray": [128, 128, 128],
  143. "green": [0, 128, 0],
  144. "greenyellow": [173, 255, 47],
  145. "grey": [128, 128, 128],
  146. "honeydew": [240, 255, 240],
  147. "hotpink": [255, 105, 180],
  148. "indianred": [205, 92, 92],
  149. "indigo": [75, 0, 130],
  150. "ivory": [255, 255, 240],
  151. "khaki": [240, 230, 140],
  152. "lavender": [230, 230, 250],
  153. "lavenderblush": [255, 240, 245],
  154. "lawngreen": [124, 252, 0],
  155. "lemonchiffon": [255, 250, 205],
  156. "lightblue": [173, 216, 230],
  157. "lightcoral": [240, 128, 128],
  158. "lightcyan": [224, 255, 255],
  159. "lightgoldenrodyellow": [250, 250, 210],
  160. "lightgray": [211, 211, 211],
  161. "lightgreen": [144, 238, 144],
  162. "lightgrey": [211, 211, 211],
  163. "lightpink": [255, 182, 193],
  164. "lightsalmon": [255, 160, 122],
  165. "lightseagreen": [32, 178, 170],
  166. "lightskyblue": [135, 206, 250],
  167. "lightslategray": [119, 136, 153],
  168. "lightslategrey": [119, 136, 153],
  169. "lightsteelblue": [176, 196, 222],
  170. "lightyellow": [255, 255, 224],
  171. "lime": [0, 255, 0],
  172. "limegreen": [50, 205, 50],
  173. "linen": [250, 240, 230],
  174. "magenta": [255, 0, 255],
  175. "maroon": [128, 0, 0],
  176. "mediumaquamarine": [102, 205, 170],
  177. "mediumblue": [0, 0, 205],
  178. "mediumorchid": [186, 85, 211],
  179. "mediumpurple": [147, 112, 219],
  180. "mediumseagreen": [60, 179, 113],
  181. "mediumslateblue": [123, 104, 238],
  182. "mediumspringgreen": [0, 250, 154],
  183. "mediumturquoise": [72, 209, 204],
  184. "mediumvioletred": [199, 21, 133],
  185. "midnightblue": [25, 25, 112],
  186. "mintcream": [245, 255, 250],
  187. "mistyrose": [255, 228, 225],
  188. "moccasin": [255, 228, 181],
  189. "navajowhite": [255, 222, 173],
  190. "navy": [0, 0, 128],
  191. "oldlace": [253, 245, 230],
  192. "olive": [128, 128, 0],
  193. "olivedrab": [107, 142, 35],
  194. "orange": [255, 165, 0],
  195. "orangered": [255, 69, 0],
  196. "orchid": [218, 112, 214],
  197. "palegoldenrod": [238, 232, 170],
  198. "palegreen": [152, 251, 152],
  199. "paleturquoise": [175, 238, 238],
  200. "palevioletred": [219, 112, 147],
  201. "papayawhip": [255, 239, 213],
  202. "peachpuff": [255, 218, 185],
  203. "peru": [205, 133, 63],
  204. "pink": [255, 192, 203],
  205. "plum": [221, 160, 221],
  206. "powderblue": [176, 224, 230],
  207. "purple": [128, 0, 128],
  208. "rebeccapurple": [102, 51, 153],
  209. "red": [255, 0, 0],
  210. "rosybrown": [188, 143, 143],
  211. "royalblue": [65, 105, 225],
  212. "saddlebrown": [139, 69, 19],
  213. "salmon": [250, 128, 114],
  214. "sandybrown": [244, 164, 96],
  215. "seagreen": [46, 139, 87],
  216. "seashell": [255, 245, 238],
  217. "sienna": [160, 82, 45],
  218. "silver": [192, 192, 192],
  219. "skyblue": [135, 206, 235],
  220. "slateblue": [106, 90, 205],
  221. "slategray": [112, 128, 144],
  222. "slategrey": [112, 128, 144],
  223. "snow": [255, 250, 250],
  224. "springgreen": [0, 255, 127],
  225. "steelblue": [70, 130, 180],
  226. "tan": [210, 180, 140],
  227. "teal": [0, 128, 128],
  228. "thistle": [216, 191, 216],
  229. "tomato": [255, 99, 71],
  230. "turquoise": [64, 224, 208],
  231. "violet": [238, 130, 238],
  232. "wheat": [245, 222, 179],
  233. "white": [255, 255, 255],
  234. "whitesmoke": [245, 245, 245],
  235. "yellow": [255, 255, 0],
  236. "yellowgreen": [154, 205, 50]
  237. };
  238. /* MIT license */
  239. /* eslint-disable no-mixed-operators */
  240. const cssKeywords$1 = colorName$1;
  241. // NOTE: conversions should only return primitive values (i.e. arrays, or
  242. // values that give correct `typeof` results).
  243. // do not use box values types (i.e. Number(), String(), etc.)
  244. const reverseKeywords$1 = {};
  245. for (const key of Object.keys(cssKeywords$1)) {
  246. reverseKeywords$1[cssKeywords$1[key]] = key;
  247. }
  248. const convert$3 = {
  249. rgb: {channels: 3, labels: 'rgb'},
  250. hsl: {channels: 3, labels: 'hsl'},
  251. hsv: {channels: 3, labels: 'hsv'},
  252. hwb: {channels: 3, labels: 'hwb'},
  253. cmyk: {channels: 4, labels: 'cmyk'},
  254. xyz: {channels: 3, labels: 'xyz'},
  255. lab: {channels: 3, labels: 'lab'},
  256. lch: {channels: 3, labels: 'lch'},
  257. hex: {channels: 1, labels: ['hex']},
  258. keyword: {channels: 1, labels: ['keyword']},
  259. ansi16: {channels: 1, labels: ['ansi16']},
  260. ansi256: {channels: 1, labels: ['ansi256']},
  261. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  262. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  263. gray: {channels: 1, labels: ['gray']}
  264. };
  265. var conversions$5 = convert$3;
  266. // Hide .channels and .labels properties
  267. for (const model of Object.keys(convert$3)) {
  268. if (!('channels' in convert$3[model])) {
  269. throw new Error('missing channels property: ' + model);
  270. }
  271. if (!('labels' in convert$3[model])) {
  272. throw new Error('missing channel labels property: ' + model);
  273. }
  274. if (convert$3[model].labels.length !== convert$3[model].channels) {
  275. throw new Error('channel and label counts mismatch: ' + model);
  276. }
  277. const {channels, labels} = convert$3[model];
  278. delete convert$3[model].channels;
  279. delete convert$3[model].labels;
  280. Object.defineProperty(convert$3[model], 'channels', {value: channels});
  281. Object.defineProperty(convert$3[model], 'labels', {value: labels});
  282. }
  283. convert$3.rgb.hsl = function (rgb) {
  284. const r = rgb[0] / 255;
  285. const g = rgb[1] / 255;
  286. const b = rgb[2] / 255;
  287. const min = Math.min(r, g, b);
  288. const max = Math.max(r, g, b);
  289. const delta = max - min;
  290. let h;
  291. let s;
  292. if (max === min) {
  293. h = 0;
  294. } else if (r === max) {
  295. h = (g - b) / delta;
  296. } else if (g === max) {
  297. h = 2 + (b - r) / delta;
  298. } else if (b === max) {
  299. h = 4 + (r - g) / delta;
  300. }
  301. h = Math.min(h * 60, 360);
  302. if (h < 0) {
  303. h += 360;
  304. }
  305. const l = (min + max) / 2;
  306. if (max === min) {
  307. s = 0;
  308. } else if (l <= 0.5) {
  309. s = delta / (max + min);
  310. } else {
  311. s = delta / (2 - max - min);
  312. }
  313. return [h, s * 100, l * 100];
  314. };
  315. convert$3.rgb.hsv = function (rgb) {
  316. let rdif;
  317. let gdif;
  318. let bdif;
  319. let h;
  320. let s;
  321. const r = rgb[0] / 255;
  322. const g = rgb[1] / 255;
  323. const b = rgb[2] / 255;
  324. const v = Math.max(r, g, b);
  325. const diff = v - Math.min(r, g, b);
  326. const diffc = function (c) {
  327. return (v - c) / 6 / diff + 1 / 2;
  328. };
  329. if (diff === 0) {
  330. h = 0;
  331. s = 0;
  332. } else {
  333. s = diff / v;
  334. rdif = diffc(r);
  335. gdif = diffc(g);
  336. bdif = diffc(b);
  337. if (r === v) {
  338. h = bdif - gdif;
  339. } else if (g === v) {
  340. h = (1 / 3) + rdif - bdif;
  341. } else if (b === v) {
  342. h = (2 / 3) + gdif - rdif;
  343. }
  344. if (h < 0) {
  345. h += 1;
  346. } else if (h > 1) {
  347. h -= 1;
  348. }
  349. }
  350. return [
  351. h * 360,
  352. s * 100,
  353. v * 100
  354. ];
  355. };
  356. convert$3.rgb.hwb = function (rgb) {
  357. const r = rgb[0];
  358. const g = rgb[1];
  359. let b = rgb[2];
  360. const h = convert$3.rgb.hsl(rgb)[0];
  361. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  362. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  363. return [h, w * 100, b * 100];
  364. };
  365. convert$3.rgb.cmyk = function (rgb) {
  366. const r = rgb[0] / 255;
  367. const g = rgb[1] / 255;
  368. const b = rgb[2] / 255;
  369. const k = Math.min(1 - r, 1 - g, 1 - b);
  370. const c = (1 - r - k) / (1 - k) || 0;
  371. const m = (1 - g - k) / (1 - k) || 0;
  372. const y = (1 - b - k) / (1 - k) || 0;
  373. return [c * 100, m * 100, y * 100, k * 100];
  374. };
  375. function comparativeDistance$1(x, y) {
  376. /*
  377. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  378. */
  379. return (
  380. ((x[0] - y[0]) ** 2) +
  381. ((x[1] - y[1]) ** 2) +
  382. ((x[2] - y[2]) ** 2)
  383. );
  384. }
  385. convert$3.rgb.keyword = function (rgb) {
  386. const reversed = reverseKeywords$1[rgb];
  387. if (reversed) {
  388. return reversed;
  389. }
  390. let currentClosestDistance = Infinity;
  391. let currentClosestKeyword;
  392. for (const keyword of Object.keys(cssKeywords$1)) {
  393. const value = cssKeywords$1[keyword];
  394. // Compute comparative distance
  395. const distance = comparativeDistance$1(rgb, value);
  396. // Check if its less, if so set as closest
  397. if (distance < currentClosestDistance) {
  398. currentClosestDistance = distance;
  399. currentClosestKeyword = keyword;
  400. }
  401. }
  402. return currentClosestKeyword;
  403. };
  404. convert$3.keyword.rgb = function (keyword) {
  405. return cssKeywords$1[keyword];
  406. };
  407. convert$3.rgb.xyz = function (rgb) {
  408. let r = rgb[0] / 255;
  409. let g = rgb[1] / 255;
  410. let b = rgb[2] / 255;
  411. // Assume sRGB
  412. r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
  413. g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
  414. b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
  415. const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  416. const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  417. const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  418. return [x * 100, y * 100, z * 100];
  419. };
  420. convert$3.rgb.lab = function (rgb) {
  421. const xyz = convert$3.rgb.xyz(rgb);
  422. let x = xyz[0];
  423. let y = xyz[1];
  424. let z = xyz[2];
  425. x /= 95.047;
  426. y /= 100;
  427. z /= 108.883;
  428. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  429. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  430. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  431. const l = (116 * y) - 16;
  432. const a = 500 * (x - y);
  433. const b = 200 * (y - z);
  434. return [l, a, b];
  435. };
  436. convert$3.hsl.rgb = function (hsl) {
  437. const h = hsl[0] / 360;
  438. const s = hsl[1] / 100;
  439. const l = hsl[2] / 100;
  440. let t2;
  441. let t3;
  442. let val;
  443. if (s === 0) {
  444. val = l * 255;
  445. return [val, val, val];
  446. }
  447. if (l < 0.5) {
  448. t2 = l * (1 + s);
  449. } else {
  450. t2 = l + s - l * s;
  451. }
  452. const t1 = 2 * l - t2;
  453. const rgb = [0, 0, 0];
  454. for (let i = 0; i < 3; i++) {
  455. t3 = h + 1 / 3 * -(i - 1);
  456. if (t3 < 0) {
  457. t3++;
  458. }
  459. if (t3 > 1) {
  460. t3--;
  461. }
  462. if (6 * t3 < 1) {
  463. val = t1 + (t2 - t1) * 6 * t3;
  464. } else if (2 * t3 < 1) {
  465. val = t2;
  466. } else if (3 * t3 < 2) {
  467. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  468. } else {
  469. val = t1;
  470. }
  471. rgb[i] = val * 255;
  472. }
  473. return rgb;
  474. };
  475. convert$3.hsl.hsv = function (hsl) {
  476. const h = hsl[0];
  477. let s = hsl[1] / 100;
  478. let l = hsl[2] / 100;
  479. let smin = s;
  480. const lmin = Math.max(l, 0.01);
  481. l *= 2;
  482. s *= (l <= 1) ? l : 2 - l;
  483. smin *= lmin <= 1 ? lmin : 2 - lmin;
  484. const v = (l + s) / 2;
  485. const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  486. return [h, sv * 100, v * 100];
  487. };
  488. convert$3.hsv.rgb = function (hsv) {
  489. const h = hsv[0] / 60;
  490. const s = hsv[1] / 100;
  491. let v = hsv[2] / 100;
  492. const hi = Math.floor(h) % 6;
  493. const f = h - Math.floor(h);
  494. const p = 255 * v * (1 - s);
  495. const q = 255 * v * (1 - (s * f));
  496. const t = 255 * v * (1 - (s * (1 - f)));
  497. v *= 255;
  498. switch (hi) {
  499. case 0:
  500. return [v, t, p];
  501. case 1:
  502. return [q, v, p];
  503. case 2:
  504. return [p, v, t];
  505. case 3:
  506. return [p, q, v];
  507. case 4:
  508. return [t, p, v];
  509. case 5:
  510. return [v, p, q];
  511. }
  512. };
  513. convert$3.hsv.hsl = function (hsv) {
  514. const h = hsv[0];
  515. const s = hsv[1] / 100;
  516. const v = hsv[2] / 100;
  517. const vmin = Math.max(v, 0.01);
  518. let sl;
  519. let l;
  520. l = (2 - s) * v;
  521. const lmin = (2 - s) * vmin;
  522. sl = s * vmin;
  523. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  524. sl = sl || 0;
  525. l /= 2;
  526. return [h, sl * 100, l * 100];
  527. };
  528. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  529. convert$3.hwb.rgb = function (hwb) {
  530. const h = hwb[0] / 360;
  531. let wh = hwb[1] / 100;
  532. let bl = hwb[2] / 100;
  533. const ratio = wh + bl;
  534. let f;
  535. // Wh + bl cant be > 1
  536. if (ratio > 1) {
  537. wh /= ratio;
  538. bl /= ratio;
  539. }
  540. const i = Math.floor(6 * h);
  541. const v = 1 - bl;
  542. f = 6 * h - i;
  543. if ((i & 0x01) !== 0) {
  544. f = 1 - f;
  545. }
  546. const n = wh + f * (v - wh); // Linear interpolation
  547. let r;
  548. let g;
  549. let b;
  550. /* eslint-disable max-statements-per-line,no-multi-spaces */
  551. switch (i) {
  552. default:
  553. case 6:
  554. case 0: r = v; g = n; b = wh; break;
  555. case 1: r = n; g = v; b = wh; break;
  556. case 2: r = wh; g = v; b = n; break;
  557. case 3: r = wh; g = n; b = v; break;
  558. case 4: r = n; g = wh; b = v; break;
  559. case 5: r = v; g = wh; b = n; break;
  560. }
  561. /* eslint-enable max-statements-per-line,no-multi-spaces */
  562. return [r * 255, g * 255, b * 255];
  563. };
  564. convert$3.cmyk.rgb = function (cmyk) {
  565. const c = cmyk[0] / 100;
  566. const m = cmyk[1] / 100;
  567. const y = cmyk[2] / 100;
  568. const k = cmyk[3] / 100;
  569. const r = 1 - Math.min(1, c * (1 - k) + k);
  570. const g = 1 - Math.min(1, m * (1 - k) + k);
  571. const b = 1 - Math.min(1, y * (1 - k) + k);
  572. return [r * 255, g * 255, b * 255];
  573. };
  574. convert$3.xyz.rgb = function (xyz) {
  575. const x = xyz[0] / 100;
  576. const y = xyz[1] / 100;
  577. const z = xyz[2] / 100;
  578. let r;
  579. let g;
  580. let b;
  581. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  582. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  583. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  584. // Assume sRGB
  585. r = r > 0.0031308
  586. ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
  587. : r * 12.92;
  588. g = g > 0.0031308
  589. ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
  590. : g * 12.92;
  591. b = b > 0.0031308
  592. ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
  593. : b * 12.92;
  594. r = Math.min(Math.max(0, r), 1);
  595. g = Math.min(Math.max(0, g), 1);
  596. b = Math.min(Math.max(0, b), 1);
  597. return [r * 255, g * 255, b * 255];
  598. };
  599. convert$3.xyz.lab = function (xyz) {
  600. let x = xyz[0];
  601. let y = xyz[1];
  602. let z = xyz[2];
  603. x /= 95.047;
  604. y /= 100;
  605. z /= 108.883;
  606. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  607. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  608. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  609. const l = (116 * y) - 16;
  610. const a = 500 * (x - y);
  611. const b = 200 * (y - z);
  612. return [l, a, b];
  613. };
  614. convert$3.lab.xyz = function (lab) {
  615. const l = lab[0];
  616. const a = lab[1];
  617. const b = lab[2];
  618. let x;
  619. let y;
  620. let z;
  621. y = (l + 16) / 116;
  622. x = a / 500 + y;
  623. z = y - b / 200;
  624. const y2 = y ** 3;
  625. const x2 = x ** 3;
  626. const z2 = z ** 3;
  627. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  628. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  629. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  630. x *= 95.047;
  631. y *= 100;
  632. z *= 108.883;
  633. return [x, y, z];
  634. };
  635. convert$3.lab.lch = function (lab) {
  636. const l = lab[0];
  637. const a = lab[1];
  638. const b = lab[2];
  639. let h;
  640. const hr = Math.atan2(b, a);
  641. h = hr * 360 / 2 / Math.PI;
  642. if (h < 0) {
  643. h += 360;
  644. }
  645. const c = Math.sqrt(a * a + b * b);
  646. return [l, c, h];
  647. };
  648. convert$3.lch.lab = function (lch) {
  649. const l = lch[0];
  650. const c = lch[1];
  651. const h = lch[2];
  652. const hr = h / 360 * 2 * Math.PI;
  653. const a = c * Math.cos(hr);
  654. const b = c * Math.sin(hr);
  655. return [l, a, b];
  656. };
  657. convert$3.rgb.ansi16 = function (args, saturation = null) {
  658. const [r, g, b] = args;
  659. let value = saturation === null ? convert$3.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  660. value = Math.round(value / 50);
  661. if (value === 0) {
  662. return 30;
  663. }
  664. let ansi = 30
  665. + ((Math.round(b / 255) << 2)
  666. | (Math.round(g / 255) << 1)
  667. | Math.round(r / 255));
  668. if (value === 2) {
  669. ansi += 60;
  670. }
  671. return ansi;
  672. };
  673. convert$3.hsv.ansi16 = function (args) {
  674. // Optimization here; we already know the value and don't need to get
  675. // it converted for us.
  676. return convert$3.rgb.ansi16(convert$3.hsv.rgb(args), args[2]);
  677. };
  678. convert$3.rgb.ansi256 = function (args) {
  679. const r = args[0];
  680. const g = args[1];
  681. const b = args[2];
  682. // We use the extended greyscale palette here, with the exception of
  683. // black and white. normal palette only has 4 greyscale shades.
  684. if (r === g && g === b) {
  685. if (r < 8) {
  686. return 16;
  687. }
  688. if (r > 248) {
  689. return 231;
  690. }
  691. return Math.round(((r - 8) / 247) * 24) + 232;
  692. }
  693. const ansi = 16
  694. + (36 * Math.round(r / 255 * 5))
  695. + (6 * Math.round(g / 255 * 5))
  696. + Math.round(b / 255 * 5);
  697. return ansi;
  698. };
  699. convert$3.ansi16.rgb = function (args) {
  700. let color = args % 10;
  701. // Handle greyscale
  702. if (color === 0 || color === 7) {
  703. if (args > 50) {
  704. color += 3.5;
  705. }
  706. color = color / 10.5 * 255;
  707. return [color, color, color];
  708. }
  709. const mult = (~~(args > 50) + 1) * 0.5;
  710. const r = ((color & 1) * mult) * 255;
  711. const g = (((color >> 1) & 1) * mult) * 255;
  712. const b = (((color >> 2) & 1) * mult) * 255;
  713. return [r, g, b];
  714. };
  715. convert$3.ansi256.rgb = function (args) {
  716. // Handle greyscale
  717. if (args >= 232) {
  718. const c = (args - 232) * 10 + 8;
  719. return [c, c, c];
  720. }
  721. args -= 16;
  722. let rem;
  723. const r = Math.floor(args / 36) / 5 * 255;
  724. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  725. const b = (rem % 6) / 5 * 255;
  726. return [r, g, b];
  727. };
  728. convert$3.rgb.hex = function (args) {
  729. const integer = ((Math.round(args[0]) & 0xFF) << 16)
  730. + ((Math.round(args[1]) & 0xFF) << 8)
  731. + (Math.round(args[2]) & 0xFF);
  732. const string = integer.toString(16).toUpperCase();
  733. return '000000'.substring(string.length) + string;
  734. };
  735. convert$3.hex.rgb = function (args) {
  736. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  737. if (!match) {
  738. return [0, 0, 0];
  739. }
  740. let colorString = match[0];
  741. if (match[0].length === 3) {
  742. colorString = colorString.split('').map(char => {
  743. return char + char;
  744. }).join('');
  745. }
  746. const integer = parseInt(colorString, 16);
  747. const r = (integer >> 16) & 0xFF;
  748. const g = (integer >> 8) & 0xFF;
  749. const b = integer & 0xFF;
  750. return [r, g, b];
  751. };
  752. convert$3.rgb.hcg = function (rgb) {
  753. const r = rgb[0] / 255;
  754. const g = rgb[1] / 255;
  755. const b = rgb[2] / 255;
  756. const max = Math.max(Math.max(r, g), b);
  757. const min = Math.min(Math.min(r, g), b);
  758. const chroma = (max - min);
  759. let grayscale;
  760. let hue;
  761. if (chroma < 1) {
  762. grayscale = min / (1 - chroma);
  763. } else {
  764. grayscale = 0;
  765. }
  766. if (chroma <= 0) {
  767. hue = 0;
  768. } else
  769. if (max === r) {
  770. hue = ((g - b) / chroma) % 6;
  771. } else
  772. if (max === g) {
  773. hue = 2 + (b - r) / chroma;
  774. } else {
  775. hue = 4 + (r - g) / chroma;
  776. }
  777. hue /= 6;
  778. hue %= 1;
  779. return [hue * 360, chroma * 100, grayscale * 100];
  780. };
  781. convert$3.hsl.hcg = function (hsl) {
  782. const s = hsl[1] / 100;
  783. const l = hsl[2] / 100;
  784. const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
  785. let f = 0;
  786. if (c < 1.0) {
  787. f = (l - 0.5 * c) / (1.0 - c);
  788. }
  789. return [hsl[0], c * 100, f * 100];
  790. };
  791. convert$3.hsv.hcg = function (hsv) {
  792. const s = hsv[1] / 100;
  793. const v = hsv[2] / 100;
  794. const c = s * v;
  795. let f = 0;
  796. if (c < 1.0) {
  797. f = (v - c) / (1 - c);
  798. }
  799. return [hsv[0], c * 100, f * 100];
  800. };
  801. convert$3.hcg.rgb = function (hcg) {
  802. const h = hcg[0] / 360;
  803. const c = hcg[1] / 100;
  804. const g = hcg[2] / 100;
  805. if (c === 0.0) {
  806. return [g * 255, g * 255, g * 255];
  807. }
  808. const pure = [0, 0, 0];
  809. const hi = (h % 1) * 6;
  810. const v = hi % 1;
  811. const w = 1 - v;
  812. let mg = 0;
  813. /* eslint-disable max-statements-per-line */
  814. switch (Math.floor(hi)) {
  815. case 0:
  816. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  817. case 1:
  818. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  819. case 2:
  820. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  821. case 3:
  822. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  823. case 4:
  824. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  825. default:
  826. pure[0] = 1; pure[1] = 0; pure[2] = w;
  827. }
  828. /* eslint-enable max-statements-per-line */
  829. mg = (1.0 - c) * g;
  830. return [
  831. (c * pure[0] + mg) * 255,
  832. (c * pure[1] + mg) * 255,
  833. (c * pure[2] + mg) * 255
  834. ];
  835. };
  836. convert$3.hcg.hsv = function (hcg) {
  837. const c = hcg[1] / 100;
  838. const g = hcg[2] / 100;
  839. const v = c + g * (1.0 - c);
  840. let f = 0;
  841. if (v > 0.0) {
  842. f = c / v;
  843. }
  844. return [hcg[0], f * 100, v * 100];
  845. };
  846. convert$3.hcg.hsl = function (hcg) {
  847. const c = hcg[1] / 100;
  848. const g = hcg[2] / 100;
  849. const l = g * (1.0 - c) + 0.5 * c;
  850. let s = 0;
  851. if (l > 0.0 && l < 0.5) {
  852. s = c / (2 * l);
  853. } else
  854. if (l >= 0.5 && l < 1.0) {
  855. s = c / (2 * (1 - l));
  856. }
  857. return [hcg[0], s * 100, l * 100];
  858. };
  859. convert$3.hcg.hwb = function (hcg) {
  860. const c = hcg[1] / 100;
  861. const g = hcg[2] / 100;
  862. const v = c + g * (1.0 - c);
  863. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  864. };
  865. convert$3.hwb.hcg = function (hwb) {
  866. const w = hwb[1] / 100;
  867. const b = hwb[2] / 100;
  868. const v = 1 - b;
  869. const c = v - w;
  870. let g = 0;
  871. if (c < 1) {
  872. g = (v - c) / (1 - c);
  873. }
  874. return [hwb[0], c * 100, g * 100];
  875. };
  876. convert$3.apple.rgb = function (apple) {
  877. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  878. };
  879. convert$3.rgb.apple = function (rgb) {
  880. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  881. };
  882. convert$3.gray.rgb = function (args) {
  883. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  884. };
  885. convert$3.gray.hsl = function (args) {
  886. return [0, 0, args[0]];
  887. };
  888. convert$3.gray.hsv = convert$3.gray.hsl;
  889. convert$3.gray.hwb = function (gray) {
  890. return [0, 100, gray[0]];
  891. };
  892. convert$3.gray.cmyk = function (gray) {
  893. return [0, 0, 0, gray[0]];
  894. };
  895. convert$3.gray.lab = function (gray) {
  896. return [gray[0], 0, 0];
  897. };
  898. convert$3.gray.hex = function (gray) {
  899. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  900. const integer = (val << 16) + (val << 8) + val;
  901. const string = integer.toString(16).toUpperCase();
  902. return '000000'.substring(string.length) + string;
  903. };
  904. convert$3.rgb.gray = function (rgb) {
  905. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  906. return [val / 255 * 100];
  907. };
  908. const conversions$4 = conversions$5;
  909. /*
  910. This function routes a model to all other models.
  911. all functions that are routed have a property `.conversion` attached
  912. to the returned synthetic function. This property is an array
  913. of strings, each with the steps in between the 'from' and 'to'
  914. color models (inclusive).
  915. conversions that are not possible simply are not included.
  916. */
  917. function buildGraph$1() {
  918. const graph = {};
  919. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  920. const models = Object.keys(conversions$4);
  921. for (let len = models.length, i = 0; i < len; i++) {
  922. graph[models[i]] = {
  923. // http://jsperf.com/1-vs-infinity
  924. // micro-opt, but this is simple.
  925. distance: -1,
  926. parent: null
  927. };
  928. }
  929. return graph;
  930. }
  931. // https://en.wikipedia.org/wiki/Breadth-first_search
  932. function deriveBFS$1(fromModel) {
  933. const graph = buildGraph$1();
  934. const queue = [fromModel]; // Unshift -> queue -> pop
  935. graph[fromModel].distance = 0;
  936. while (queue.length) {
  937. const current = queue.pop();
  938. const adjacents = Object.keys(conversions$4[current]);
  939. for (let len = adjacents.length, i = 0; i < len; i++) {
  940. const adjacent = adjacents[i];
  941. const node = graph[adjacent];
  942. if (node.distance === -1) {
  943. node.distance = graph[current].distance + 1;
  944. node.parent = current;
  945. queue.unshift(adjacent);
  946. }
  947. }
  948. }
  949. return graph;
  950. }
  951. function link$1(from, to) {
  952. return function (args) {
  953. return to(from(args));
  954. };
  955. }
  956. function wrapConversion$1(toModel, graph) {
  957. const path = [graph[toModel].parent, toModel];
  958. let fn = conversions$4[graph[toModel].parent][toModel];
  959. let cur = graph[toModel].parent;
  960. while (graph[cur].parent) {
  961. path.unshift(graph[cur].parent);
  962. fn = link$1(conversions$4[graph[cur].parent][cur], fn);
  963. cur = graph[cur].parent;
  964. }
  965. fn.conversion = path;
  966. return fn;
  967. }
  968. var route$3 = function (fromModel) {
  969. const graph = deriveBFS$1(fromModel);
  970. const conversion = {};
  971. const models = Object.keys(graph);
  972. for (let len = models.length, i = 0; i < len; i++) {
  973. const toModel = models[i];
  974. const node = graph[toModel];
  975. if (node.parent === null) {
  976. // No possible conversion, or this node is the source model.
  977. continue;
  978. }
  979. conversion[toModel] = wrapConversion$1(toModel, graph);
  980. }
  981. return conversion;
  982. };
  983. const conversions$3 = conversions$5;
  984. const route$2 = route$3;
  985. const convert$2 = {};
  986. const models$1 = Object.keys(conversions$3);
  987. function wrapRaw$1(fn) {
  988. const wrappedFn = function (...args) {
  989. const arg0 = args[0];
  990. if (arg0 === undefined || arg0 === null) {
  991. return arg0;
  992. }
  993. if (arg0.length > 1) {
  994. args = arg0;
  995. }
  996. return fn(args);
  997. };
  998. // Preserve .conversion property if there is one
  999. if ('conversion' in fn) {
  1000. wrappedFn.conversion = fn.conversion;
  1001. }
  1002. return wrappedFn;
  1003. }
  1004. function wrapRounded$1(fn) {
  1005. const wrappedFn = function (...args) {
  1006. const arg0 = args[0];
  1007. if (arg0 === undefined || arg0 === null) {
  1008. return arg0;
  1009. }
  1010. if (arg0.length > 1) {
  1011. args = arg0;
  1012. }
  1013. const result = fn(args);
  1014. // We're assuming the result is an array here.
  1015. // see notice in conversions.js; don't use box types
  1016. // in conversion functions.
  1017. if (typeof result === 'object') {
  1018. for (let len = result.length, i = 0; i < len; i++) {
  1019. result[i] = Math.round(result[i]);
  1020. }
  1021. }
  1022. return result;
  1023. };
  1024. // Preserve .conversion property if there is one
  1025. if ('conversion' in fn) {
  1026. wrappedFn.conversion = fn.conversion;
  1027. }
  1028. return wrappedFn;
  1029. }
  1030. models$1.forEach(fromModel => {
  1031. convert$2[fromModel] = {};
  1032. Object.defineProperty(convert$2[fromModel], 'channels', {value: conversions$3[fromModel].channels});
  1033. Object.defineProperty(convert$2[fromModel], 'labels', {value: conversions$3[fromModel].labels});
  1034. const routes = route$2(fromModel);
  1035. const routeModels = Object.keys(routes);
  1036. routeModels.forEach(toModel => {
  1037. const fn = routes[toModel];
  1038. convert$2[fromModel][toModel] = wrapRounded$1(fn);
  1039. convert$2[fromModel][toModel].raw = wrapRaw$1(fn);
  1040. });
  1041. });
  1042. var colorConvert$1 = convert$2;
  1043. (function (module) {
  1044. const wrapAnsi16 = (fn, offset) => (...args) => {
  1045. const code = fn(...args);
  1046. return `\u001B[${code + offset}m`;
  1047. };
  1048. const wrapAnsi256 = (fn, offset) => (...args) => {
  1049. const code = fn(...args);
  1050. return `\u001B[${38 + offset};5;${code}m`;
  1051. };
  1052. const wrapAnsi16m = (fn, offset) => (...args) => {
  1053. const rgb = fn(...args);
  1054. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  1055. };
  1056. const ansi2ansi = n => n;
  1057. const rgb2rgb = (r, g, b) => [r, g, b];
  1058. const setLazyProperty = (object, property, get) => {
  1059. Object.defineProperty(object, property, {
  1060. get: () => {
  1061. const value = get();
  1062. Object.defineProperty(object, property, {
  1063. value,
  1064. enumerable: true,
  1065. configurable: true
  1066. });
  1067. return value;
  1068. },
  1069. enumerable: true,
  1070. configurable: true
  1071. });
  1072. };
  1073. /** @type {typeof import('color-convert')} */
  1074. let colorConvert;
  1075. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  1076. if (colorConvert === undefined) {
  1077. colorConvert = colorConvert$1;
  1078. }
  1079. const offset = isBackground ? 10 : 0;
  1080. const styles = {};
  1081. for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
  1082. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  1083. if (sourceSpace === targetSpace) {
  1084. styles[name] = wrap(identity, offset);
  1085. } else if (typeof suite === 'object') {
  1086. styles[name] = wrap(suite[targetSpace], offset);
  1087. }
  1088. }
  1089. return styles;
  1090. };
  1091. function assembleStyles() {
  1092. const codes = new Map();
  1093. const styles = {
  1094. modifier: {
  1095. reset: [0, 0],
  1096. // 21 isn't widely supported and 22 does the same thing
  1097. bold: [1, 22],
  1098. dim: [2, 22],
  1099. italic: [3, 23],
  1100. underline: [4, 24],
  1101. inverse: [7, 27],
  1102. hidden: [8, 28],
  1103. strikethrough: [9, 29]
  1104. },
  1105. color: {
  1106. black: [30, 39],
  1107. red: [31, 39],
  1108. green: [32, 39],
  1109. yellow: [33, 39],
  1110. blue: [34, 39],
  1111. magenta: [35, 39],
  1112. cyan: [36, 39],
  1113. white: [37, 39],
  1114. // Bright color
  1115. blackBright: [90, 39],
  1116. redBright: [91, 39],
  1117. greenBright: [92, 39],
  1118. yellowBright: [93, 39],
  1119. blueBright: [94, 39],
  1120. magentaBright: [95, 39],
  1121. cyanBright: [96, 39],
  1122. whiteBright: [97, 39]
  1123. },
  1124. bgColor: {
  1125. bgBlack: [40, 49],
  1126. bgRed: [41, 49],
  1127. bgGreen: [42, 49],
  1128. bgYellow: [43, 49],
  1129. bgBlue: [44, 49],
  1130. bgMagenta: [45, 49],
  1131. bgCyan: [46, 49],
  1132. bgWhite: [47, 49],
  1133. // Bright color
  1134. bgBlackBright: [100, 49],
  1135. bgRedBright: [101, 49],
  1136. bgGreenBright: [102, 49],
  1137. bgYellowBright: [103, 49],
  1138. bgBlueBright: [104, 49],
  1139. bgMagentaBright: [105, 49],
  1140. bgCyanBright: [106, 49],
  1141. bgWhiteBright: [107, 49]
  1142. }
  1143. };
  1144. // Alias bright black as gray (and grey)
  1145. styles.color.gray = styles.color.blackBright;
  1146. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  1147. styles.color.grey = styles.color.blackBright;
  1148. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  1149. for (const [groupName, group] of Object.entries(styles)) {
  1150. for (const [styleName, style] of Object.entries(group)) {
  1151. styles[styleName] = {
  1152. open: `\u001B[${style[0]}m`,
  1153. close: `\u001B[${style[1]}m`
  1154. };
  1155. group[styleName] = styles[styleName];
  1156. codes.set(style[0], style[1]);
  1157. }
  1158. Object.defineProperty(styles, groupName, {
  1159. value: group,
  1160. enumerable: false
  1161. });
  1162. }
  1163. Object.defineProperty(styles, 'codes', {
  1164. value: codes,
  1165. enumerable: false
  1166. });
  1167. styles.color.close = '\u001B[39m';
  1168. styles.bgColor.close = '\u001B[49m';
  1169. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  1170. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  1171. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  1172. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  1173. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  1174. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  1175. return styles;
  1176. }
  1177. // Make the export immutable
  1178. Object.defineProperty(module, 'exports', {
  1179. enumerable: true,
  1180. get: assembleStyles
  1181. });
  1182. }(ansiStyles$2));
  1183. var hasFlag$3 = (flag, argv = process.argv) => {
  1184. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  1185. const position = argv.indexOf(prefix + flag);
  1186. const terminatorPosition = argv.indexOf('--');
  1187. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  1188. };
  1189. const os$5 = require$$0__default$1;
  1190. const tty = require$$0__default;
  1191. const hasFlag$2 = hasFlag$3;
  1192. const {env: env$2} = process;
  1193. let forceColor$1;
  1194. if (hasFlag$2('no-color') ||
  1195. hasFlag$2('no-colors') ||
  1196. hasFlag$2('color=false') ||
  1197. hasFlag$2('color=never')) {
  1198. forceColor$1 = 0;
  1199. } else if (hasFlag$2('color') ||
  1200. hasFlag$2('colors') ||
  1201. hasFlag$2('color=true') ||
  1202. hasFlag$2('color=always')) {
  1203. forceColor$1 = 1;
  1204. }
  1205. if ('FORCE_COLOR' in env$2) {
  1206. if (env$2.FORCE_COLOR === 'true') {
  1207. forceColor$1 = 1;
  1208. } else if (env$2.FORCE_COLOR === 'false') {
  1209. forceColor$1 = 0;
  1210. } else {
  1211. forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3);
  1212. }
  1213. }
  1214. function translateLevel$1(level) {
  1215. if (level === 0) {
  1216. return false;
  1217. }
  1218. return {
  1219. level,
  1220. hasBasic: true,
  1221. has256: level >= 2,
  1222. has16m: level >= 3
  1223. };
  1224. }
  1225. function supportsColor$1(haveStream, streamIsTTY) {
  1226. if (forceColor$1 === 0) {
  1227. return 0;
  1228. }
  1229. if (hasFlag$2('color=16m') ||
  1230. hasFlag$2('color=full') ||
  1231. hasFlag$2('color=truecolor')) {
  1232. return 3;
  1233. }
  1234. if (hasFlag$2('color=256')) {
  1235. return 2;
  1236. }
  1237. if (haveStream && !streamIsTTY && forceColor$1 === undefined) {
  1238. return 0;
  1239. }
  1240. const min = forceColor$1 || 0;
  1241. if (env$2.TERM === 'dumb') {
  1242. return min;
  1243. }
  1244. if (process.platform === 'win32') {
  1245. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  1246. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  1247. const osRelease = os$5.release().split('.');
  1248. if (
  1249. Number(osRelease[0]) >= 10 &&
  1250. Number(osRelease[2]) >= 10586
  1251. ) {
  1252. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  1253. }
  1254. return 1;
  1255. }
  1256. if ('CI' in env$2) {
  1257. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') {
  1258. return 1;
  1259. }
  1260. return min;
  1261. }
  1262. if ('TEAMCITY_VERSION' in env$2) {
  1263. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0;
  1264. }
  1265. if (env$2.COLORTERM === 'truecolor') {
  1266. return 3;
  1267. }
  1268. if ('TERM_PROGRAM' in env$2) {
  1269. const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  1270. switch (env$2.TERM_PROGRAM) {
  1271. case 'iTerm.app':
  1272. return version >= 3 ? 3 : 2;
  1273. case 'Apple_Terminal':
  1274. return 2;
  1275. // No default
  1276. }
  1277. }
  1278. if (/-256(color)?$/i.test(env$2.TERM)) {
  1279. return 2;
  1280. }
  1281. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) {
  1282. return 1;
  1283. }
  1284. if ('COLORTERM' in env$2) {
  1285. return 1;
  1286. }
  1287. return min;
  1288. }
  1289. function getSupportLevel$1(stream) {
  1290. const level = supportsColor$1(stream, stream && stream.isTTY);
  1291. return translateLevel$1(level);
  1292. }
  1293. var supportsColor_1$1 = {
  1294. supportsColor: getSupportLevel$1,
  1295. stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))),
  1296. stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2)))
  1297. };
  1298. const stringReplaceAll$1 = (string, substring, replacer) => {
  1299. let index = string.indexOf(substring);
  1300. if (index === -1) {
  1301. return string;
  1302. }
  1303. const substringLength = substring.length;
  1304. let endIndex = 0;
  1305. let returnValue = '';
  1306. do {
  1307. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  1308. endIndex = index + substringLength;
  1309. index = string.indexOf(substring, endIndex);
  1310. } while (index !== -1);
  1311. returnValue += string.substr(endIndex);
  1312. return returnValue;
  1313. };
  1314. const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
  1315. let endIndex = 0;
  1316. let returnValue = '';
  1317. do {
  1318. const gotCR = string[index - 1] === '\r';
  1319. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  1320. endIndex = index + 1;
  1321. index = string.indexOf('\n', endIndex);
  1322. } while (index !== -1);
  1323. returnValue += string.substr(endIndex);
  1324. return returnValue;
  1325. };
  1326. var util$c = {
  1327. stringReplaceAll: stringReplaceAll$1,
  1328. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  1329. };
  1330. const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
  1331. const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  1332. const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  1333. const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  1334. const ESCAPES$1 = new Map([
  1335. ['n', '\n'],
  1336. ['r', '\r'],
  1337. ['t', '\t'],
  1338. ['b', '\b'],
  1339. ['f', '\f'],
  1340. ['v', '\v'],
  1341. ['0', '\0'],
  1342. ['\\', '\\'],
  1343. ['e', '\u001B'],
  1344. ['a', '\u0007']
  1345. ]);
  1346. function unescape$2(c) {
  1347. const u = c[0] === 'u';
  1348. const bracket = c[1] === '{';
  1349. if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
  1350. return String.fromCharCode(parseInt(c.slice(1), 16));
  1351. }
  1352. if (u && bracket) {
  1353. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  1354. }
  1355. return ESCAPES$1.get(c) || c;
  1356. }
  1357. function parseArguments$1(name, arguments_) {
  1358. const results = [];
  1359. const chunks = arguments_.trim().split(/\s*,\s*/g);
  1360. let matches;
  1361. for (const chunk of chunks) {
  1362. const number = Number(chunk);
  1363. if (!Number.isNaN(number)) {
  1364. results.push(number);
  1365. } else if ((matches = chunk.match(STRING_REGEX$1))) {
  1366. results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$2(escape) : character));
  1367. } else {
  1368. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  1369. }
  1370. }
  1371. return results;
  1372. }
  1373. function parseStyle$1(style) {
  1374. STYLE_REGEX$1.lastIndex = 0;
  1375. const results = [];
  1376. let matches;
  1377. while ((matches = STYLE_REGEX$1.exec(style)) !== null) {
  1378. const name = matches[1];
  1379. if (matches[2]) {
  1380. const args = parseArguments$1(name, matches[2]);
  1381. results.push([name].concat(args));
  1382. } else {
  1383. results.push([name]);
  1384. }
  1385. }
  1386. return results;
  1387. }
  1388. function buildStyle$1(chalk, styles) {
  1389. const enabled = {};
  1390. for (const layer of styles) {
  1391. for (const style of layer.styles) {
  1392. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  1393. }
  1394. }
  1395. let current = chalk;
  1396. for (const [styleName, styles] of Object.entries(enabled)) {
  1397. if (!Array.isArray(styles)) {
  1398. continue;
  1399. }
  1400. if (!(styleName in current)) {
  1401. throw new Error(`Unknown Chalk style: ${styleName}`);
  1402. }
  1403. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  1404. }
  1405. return current;
  1406. }
  1407. var templates$1 = (chalk, temporary) => {
  1408. const styles = [];
  1409. const chunks = [];
  1410. let chunk = [];
  1411. // eslint-disable-next-line max-params
  1412. temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => {
  1413. if (escapeCharacter) {
  1414. chunk.push(unescape$2(escapeCharacter));
  1415. } else if (style) {
  1416. const string = chunk.join('');
  1417. chunk = [];
  1418. chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string));
  1419. styles.push({inverse, styles: parseStyle$1(style)});
  1420. } else if (close) {
  1421. if (styles.length === 0) {
  1422. throw new Error('Found extraneous } in Chalk template literal');
  1423. }
  1424. chunks.push(buildStyle$1(chalk, styles)(chunk.join('')));
  1425. chunk = [];
  1426. styles.pop();
  1427. } else {
  1428. chunk.push(character);
  1429. }
  1430. });
  1431. chunks.push(chunk.join(''));
  1432. if (styles.length > 0) {
  1433. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  1434. throw new Error(errMessage);
  1435. }
  1436. return chunks.join('');
  1437. };
  1438. const ansiStyles$1 = ansiStyles$2.exports;
  1439. const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1$1;
  1440. const {
  1441. stringReplaceAll,
  1442. stringEncaseCRLFWithFirstIndex
  1443. } = util$c;
  1444. const {isArray: isArray$4} = Array;
  1445. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  1446. const levelMapping = [
  1447. 'ansi',
  1448. 'ansi',
  1449. 'ansi256',
  1450. 'ansi16m'
  1451. ];
  1452. const styles = Object.create(null);
  1453. const applyOptions = (object, options = {}) => {
  1454. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  1455. throw new Error('The `level` option should be an integer from 0 to 3');
  1456. }
  1457. // Detect level if not set manually
  1458. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  1459. object.level = options.level === undefined ? colorLevel : options.level;
  1460. };
  1461. class ChalkClass {
  1462. constructor(options) {
  1463. // eslint-disable-next-line no-constructor-return
  1464. return chalkFactory(options);
  1465. }
  1466. }
  1467. const chalkFactory = options => {
  1468. const chalk = {};
  1469. applyOptions(chalk, options);
  1470. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  1471. Object.setPrototypeOf(chalk, Chalk.prototype);
  1472. Object.setPrototypeOf(chalk.template, chalk);
  1473. chalk.template.constructor = () => {
  1474. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  1475. };
  1476. chalk.template.Instance = ChalkClass;
  1477. return chalk.template;
  1478. };
  1479. function Chalk(options) {
  1480. return chalkFactory(options);
  1481. }
  1482. for (const [styleName, style] of Object.entries(ansiStyles$1)) {
  1483. styles[styleName] = {
  1484. get() {
  1485. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  1486. Object.defineProperty(this, styleName, {value: builder});
  1487. return builder;
  1488. }
  1489. };
  1490. }
  1491. styles.visible = {
  1492. get() {
  1493. const builder = createBuilder(this, this._styler, true);
  1494. Object.defineProperty(this, 'visible', {value: builder});
  1495. return builder;
  1496. }
  1497. };
  1498. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  1499. for (const model of usedModels) {
  1500. styles[model] = {
  1501. get() {
  1502. const {level} = this;
  1503. return function (...arguments_) {
  1504. const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler);
  1505. return createBuilder(this, styler, this._isEmpty);
  1506. };
  1507. }
  1508. };
  1509. }
  1510. for (const model of usedModels) {
  1511. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  1512. styles[bgModel] = {
  1513. get() {
  1514. const {level} = this;
  1515. return function (...arguments_) {
  1516. const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler);
  1517. return createBuilder(this, styler, this._isEmpty);
  1518. };
  1519. }
  1520. };
  1521. }
  1522. const proto$1 = Object.defineProperties(() => {}, {
  1523. ...styles,
  1524. level: {
  1525. enumerable: true,
  1526. get() {
  1527. return this._generator.level;
  1528. },
  1529. set(level) {
  1530. this._generator.level = level;
  1531. }
  1532. }
  1533. });
  1534. const createStyler = (open, close, parent) => {
  1535. let openAll;
  1536. let closeAll;
  1537. if (parent === undefined) {
  1538. openAll = open;
  1539. closeAll = close;
  1540. } else {
  1541. openAll = parent.openAll + open;
  1542. closeAll = close + parent.closeAll;
  1543. }
  1544. return {
  1545. open,
  1546. close,
  1547. openAll,
  1548. closeAll,
  1549. parent
  1550. };
  1551. };
  1552. const createBuilder = (self, _styler, _isEmpty) => {
  1553. const builder = (...arguments_) => {
  1554. if (isArray$4(arguments_[0]) && isArray$4(arguments_[0].raw)) {
  1555. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  1556. return applyStyle(builder, chalkTag(builder, ...arguments_));
  1557. }
  1558. // Single argument is hot path, implicit coercion is faster than anything
  1559. // eslint-disable-next-line no-implicit-coercion
  1560. return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
  1561. };
  1562. // We alter the prototype because we must return a function, but there is
  1563. // no way to create a function with a different prototype
  1564. Object.setPrototypeOf(builder, proto$1);
  1565. builder._generator = self;
  1566. builder._styler = _styler;
  1567. builder._isEmpty = _isEmpty;
  1568. return builder;
  1569. };
  1570. const applyStyle = (self, string) => {
  1571. if (self.level <= 0 || !string) {
  1572. return self._isEmpty ? '' : string;
  1573. }
  1574. let styler = self._styler;
  1575. if (styler === undefined) {
  1576. return string;
  1577. }
  1578. const {openAll, closeAll} = styler;
  1579. if (string.indexOf('\u001B') !== -1) {
  1580. while (styler !== undefined) {
  1581. // Replace any instances already present with a re-opening code
  1582. // otherwise only the part of the string until said closing code
  1583. // will be colored, and the rest will simply be 'plain'.
  1584. string = stringReplaceAll(string, styler.close, styler.open);
  1585. styler = styler.parent;
  1586. }
  1587. }
  1588. // We can move both next actions out of loop, because remaining actions in loop won't have
  1589. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  1590. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  1591. const lfIndex = string.indexOf('\n');
  1592. if (lfIndex !== -1) {
  1593. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  1594. }
  1595. return openAll + string + closeAll;
  1596. };
  1597. let template;
  1598. const chalkTag = (chalk, ...strings) => {
  1599. const [firstString] = strings;
  1600. if (!isArray$4(firstString) || !isArray$4(firstString.raw)) {
  1601. // If chalk() was called by itself or with a string,
  1602. // return the string itself as a string.
  1603. return strings.join(' ');
  1604. }
  1605. const arguments_ = strings.slice(1);
  1606. const parts = [firstString.raw[0]];
  1607. for (let i = 1; i < firstString.length; i++) {
  1608. parts.push(
  1609. String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
  1610. String(firstString.raw[i])
  1611. );
  1612. }
  1613. if (template === undefined) {
  1614. template = templates$1;
  1615. }
  1616. return template(chalk, parts.join(''));
  1617. };
  1618. Object.defineProperties(Chalk.prototype, styles);
  1619. const chalk$2 = Chalk(); // eslint-disable-line new-cap
  1620. chalk$2.supportsColor = stdoutColor;
  1621. chalk$2.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
  1622. chalk$2.stderr.supportsColor = stderrColor;
  1623. var source = chalk$2;
  1624. var dist$4 = {};
  1625. var Stream$1 = require$$0__default$2;
  1626. var writeMethods = ["write", "end", "destroy"];
  1627. var readMethods = ["resume", "pause"];
  1628. var readEvents = ["data", "close"];
  1629. var slice$2 = Array.prototype.slice;
  1630. var duplexer$1 = duplex;
  1631. function forEach (arr, fn) {
  1632. if (arr.forEach) {
  1633. return arr.forEach(fn)
  1634. }
  1635. for (var i = 0; i < arr.length; i++) {
  1636. fn(arr[i], i);
  1637. }
  1638. }
  1639. function duplex(writer, reader) {
  1640. var stream = new Stream$1();
  1641. var ended = false;
  1642. forEach(writeMethods, proxyWriter);
  1643. forEach(readMethods, proxyReader);
  1644. forEach(readEvents, proxyStream);
  1645. reader.on("end", handleEnd);
  1646. writer.on("drain", function() {
  1647. stream.emit("drain");
  1648. });
  1649. writer.on("error", reemit);
  1650. reader.on("error", reemit);
  1651. stream.writable = writer.writable;
  1652. stream.readable = reader.readable;
  1653. return stream
  1654. function proxyWriter(methodName) {
  1655. stream[methodName] = method;
  1656. function method() {
  1657. return writer[methodName].apply(writer, arguments)
  1658. }
  1659. }
  1660. function proxyReader(methodName) {
  1661. stream[methodName] = method;
  1662. function method() {
  1663. stream.emit(methodName);
  1664. var func = reader[methodName];
  1665. if (func) {
  1666. return func.apply(reader, arguments)
  1667. }
  1668. reader.emit(methodName);
  1669. }
  1670. }
  1671. function proxyStream(methodName) {
  1672. reader.on(methodName, reemit);
  1673. function reemit() {
  1674. var args = slice$2.call(arguments);
  1675. args.unshift(methodName);
  1676. stream.emit.apply(stream, args);
  1677. }
  1678. }
  1679. function handleEnd() {
  1680. if (ended) {
  1681. return
  1682. }
  1683. ended = true;
  1684. var args = slice$2.call(arguments);
  1685. args.unshift("end");
  1686. stream.emit.apply(stream, args);
  1687. }
  1688. function reemit(err) {
  1689. stream.emit("error", err);
  1690. }
  1691. }
  1692. Object.defineProperty(dist$4, "__esModule", { value: true });
  1693. const zlib_1 = require$$0__default$4;
  1694. const stream_1$6 = require$$0__default$2;
  1695. const fs_1 = fs__default;
  1696. const util_1$3 = require$$0__default$3;
  1697. const duplexer = duplexer$1;
  1698. const readFilePromise = util_1$3.promisify(fs_1.readFile);
  1699. const bufferFormatter = (incoming) => typeof incoming === 'string' ? Buffer.from(incoming, 'utf8') : incoming;
  1700. const optionFormatter = (passed, toEncode) => ({
  1701. params: {
  1702. [zlib_1.constants.BROTLI_PARAM_MODE]: passed && 'mode' in passed && passed.mode || zlib_1.constants.BROTLI_DEFAULT_MODE,
  1703. [zlib_1.constants.BROTLI_PARAM_QUALITY]: passed && 'quality' in passed && passed.quality || zlib_1.constants.BROTLI_MAX_QUALITY,
  1704. [zlib_1.constants.BROTLI_PARAM_SIZE_HINT]: toEncode ? toEncode.byteLength : 0,
  1705. }
  1706. });
  1707. /**
  1708. * @param incoming Either a Buffer or string of the value to encode.
  1709. * @param options Subset of Encoding Parameters.
  1710. * @return Promise that resolves with the encoded Buffer length.
  1711. */
  1712. async function size(incoming, options) {
  1713. const buffer = bufferFormatter(incoming);
  1714. return new Promise(function (resolve, reject) {
  1715. zlib_1.brotliCompress(buffer, optionFormatter(options, buffer), (error, result) => {
  1716. if (error !== null) {
  1717. reject(error);
  1718. }
  1719. resolve(result.byteLength);
  1720. });
  1721. });
  1722. }
  1723. var _default = dist$4.default = size;
  1724. /**
  1725. * @param incoming Either a Buffer or string of the value to encode.
  1726. * @param options Subset of Encoding Parameters.
  1727. * @return Length of encoded Buffer.
  1728. */
  1729. function sync$c(incoming, options) {
  1730. const buffer = bufferFormatter(incoming);
  1731. return zlib_1.brotliCompressSync(buffer, optionFormatter(options, buffer)).byteLength;
  1732. }
  1733. dist$4.sync = sync$c;
  1734. /**
  1735. * @param options
  1736. * @return PassThroughStream for the contents being compressed
  1737. */
  1738. function stream$8(options) {
  1739. const input = new stream_1$6.PassThrough();
  1740. const output = new stream_1$6.PassThrough();
  1741. const wrapper = duplexer(input, output);
  1742. let size = 0;
  1743. const brotli = zlib_1.createBrotliCompress(optionFormatter(options))
  1744. .on('data', buf => {
  1745. size += buf.length;
  1746. })
  1747. .on('error', () => {
  1748. wrapper.brotliSize = 0;
  1749. })
  1750. .on('end', () => {
  1751. wrapper.brotliSize = size;
  1752. wrapper.emit('brotli-size', size);
  1753. output.end();
  1754. });
  1755. input.pipe(brotli);
  1756. input.pipe(output, { end: false });
  1757. return wrapper;
  1758. }
  1759. dist$4.stream = stream$8;
  1760. /**
  1761. * @param path File Path for the file to compress.
  1762. * @param options Subset of Encoding Parameters.
  1763. * @return Promise that resolves with size of encoded file.
  1764. */
  1765. async function file(path, options) {
  1766. const file = await readFilePromise(path);
  1767. return (await size(file, options));
  1768. }
  1769. dist$4.file = file;
  1770. /**
  1771. * @param path File Path for the file to compress.
  1772. * @param options Subset of Encoding Parameters.
  1773. * @return size of encoded file.
  1774. */
  1775. function fileSync(path, options) {
  1776. const file = fs_1.readFileSync(path);
  1777. return sync$c(file, options);
  1778. }
  1779. dist$4.fileSync = fileSync;
  1780. var src$3 = {exports: {}};
  1781. var browser$2 = {exports: {}};
  1782. /**
  1783. * Helpers.
  1784. */
  1785. var s$1 = 1000;
  1786. var m$1 = s$1 * 60;
  1787. var h$1 = m$1 * 60;
  1788. var d$1 = h$1 * 24;
  1789. var w = d$1 * 7;
  1790. var y$1 = d$1 * 365.25;
  1791. /**
  1792. * Parse or format the given `val`.
  1793. *
  1794. * Options:
  1795. *
  1796. * - `long` verbose formatting [false]
  1797. *
  1798. * @param {String|Number} val
  1799. * @param {Object} [options]
  1800. * @throws {Error} throw an error if val is not a non-empty string or a number
  1801. * @return {String|Number}
  1802. * @api public
  1803. */
  1804. var ms$1 = function(val, options) {
  1805. options = options || {};
  1806. var type = typeof val;
  1807. if (type === 'string' && val.length > 0) {
  1808. return parse$l(val);
  1809. } else if (type === 'number' && isFinite(val)) {
  1810. return options.long ? fmtLong$1(val) : fmtShort$1(val);
  1811. }
  1812. throw new Error(
  1813. 'val is not a non-empty string or a valid number. val=' +
  1814. JSON.stringify(val)
  1815. );
  1816. };
  1817. /**
  1818. * Parse the given `str` and return milliseconds.
  1819. *
  1820. * @param {String} str
  1821. * @return {Number}
  1822. * @api private
  1823. */
  1824. function parse$l(str) {
  1825. str = String(str);
  1826. if (str.length > 100) {
  1827. return;
  1828. }
  1829. 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(
  1830. str
  1831. );
  1832. if (!match) {
  1833. return;
  1834. }
  1835. var n = parseFloat(match[1]);
  1836. var type = (match[2] || 'ms').toLowerCase();
  1837. switch (type) {
  1838. case 'years':
  1839. case 'year':
  1840. case 'yrs':
  1841. case 'yr':
  1842. case 'y':
  1843. return n * y$1;
  1844. case 'weeks':
  1845. case 'week':
  1846. case 'w':
  1847. return n * w;
  1848. case 'days':
  1849. case 'day':
  1850. case 'd':
  1851. return n * d$1;
  1852. case 'hours':
  1853. case 'hour':
  1854. case 'hrs':
  1855. case 'hr':
  1856. case 'h':
  1857. return n * h$1;
  1858. case 'minutes':
  1859. case 'minute':
  1860. case 'mins':
  1861. case 'min':
  1862. case 'm':
  1863. return n * m$1;
  1864. case 'seconds':
  1865. case 'second':
  1866. case 'secs':
  1867. case 'sec':
  1868. case 's':
  1869. return n * s$1;
  1870. case 'milliseconds':
  1871. case 'millisecond':
  1872. case 'msecs':
  1873. case 'msec':
  1874. case 'ms':
  1875. return n;
  1876. default:
  1877. return undefined;
  1878. }
  1879. }
  1880. /**
  1881. * Short format for `ms`.
  1882. *
  1883. * @param {Number} ms
  1884. * @return {String}
  1885. * @api private
  1886. */
  1887. function fmtShort$1(ms) {
  1888. var msAbs = Math.abs(ms);
  1889. if (msAbs >= d$1) {
  1890. return Math.round(ms / d$1) + 'd';
  1891. }
  1892. if (msAbs >= h$1) {
  1893. return Math.round(ms / h$1) + 'h';
  1894. }
  1895. if (msAbs >= m$1) {
  1896. return Math.round(ms / m$1) + 'm';
  1897. }
  1898. if (msAbs >= s$1) {
  1899. return Math.round(ms / s$1) + 's';
  1900. }
  1901. return ms + 'ms';
  1902. }
  1903. /**
  1904. * Long format for `ms`.
  1905. *
  1906. * @param {Number} ms
  1907. * @return {String}
  1908. * @api private
  1909. */
  1910. function fmtLong$1(ms) {
  1911. var msAbs = Math.abs(ms);
  1912. if (msAbs >= d$1) {
  1913. return plural$1(ms, msAbs, d$1, 'day');
  1914. }
  1915. if (msAbs >= h$1) {
  1916. return plural$1(ms, msAbs, h$1, 'hour');
  1917. }
  1918. if (msAbs >= m$1) {
  1919. return plural$1(ms, msAbs, m$1, 'minute');
  1920. }
  1921. if (msAbs >= s$1) {
  1922. return plural$1(ms, msAbs, s$1, 'second');
  1923. }
  1924. return ms + ' ms';
  1925. }
  1926. /**
  1927. * Pluralization helper.
  1928. */
  1929. function plural$1(ms, msAbs, n, name) {
  1930. var isPlural = msAbs >= n * 1.5;
  1931. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  1932. }
  1933. /**
  1934. * This is the common logic for both the Node.js and web browser
  1935. * implementations of `debug()`.
  1936. */
  1937. function setup(env) {
  1938. createDebug.debug = createDebug;
  1939. createDebug.default = createDebug;
  1940. createDebug.coerce = coerce;
  1941. createDebug.disable = disable;
  1942. createDebug.enable = enable;
  1943. createDebug.enabled = enabled;
  1944. createDebug.humanize = ms$1;
  1945. createDebug.destroy = destroy;
  1946. Object.keys(env).forEach(key => {
  1947. createDebug[key] = env[key];
  1948. });
  1949. /**
  1950. * The currently active debug mode names, and names to skip.
  1951. */
  1952. createDebug.names = [];
  1953. createDebug.skips = [];
  1954. /**
  1955. * Map of special "%n" handling functions, for the debug "format" argument.
  1956. *
  1957. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  1958. */
  1959. createDebug.formatters = {};
  1960. /**
  1961. * Selects a color for a debug namespace
  1962. * @param {String} namespace The namespace string for the for the debug instance to be colored
  1963. * @return {Number|String} An ANSI color code for the given namespace
  1964. * @api private
  1965. */
  1966. function selectColor(namespace) {
  1967. let hash = 0;
  1968. for (let i = 0; i < namespace.length; i++) {
  1969. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  1970. hash |= 0; // Convert to 32bit integer
  1971. }
  1972. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  1973. }
  1974. createDebug.selectColor = selectColor;
  1975. /**
  1976. * Create a debugger with the given `namespace`.
  1977. *
  1978. * @param {String} namespace
  1979. * @return {Function}
  1980. * @api public
  1981. */
  1982. function createDebug(namespace) {
  1983. let prevTime;
  1984. let enableOverride = null;
  1985. let namespacesCache;
  1986. let enabledCache;
  1987. function debug(...args) {
  1988. // Disabled?
  1989. if (!debug.enabled) {
  1990. return;
  1991. }
  1992. const self = debug;
  1993. // Set `diff` timestamp
  1994. const curr = Number(new Date());
  1995. const ms = curr - (prevTime || curr);
  1996. self.diff = ms;
  1997. self.prev = prevTime;
  1998. self.curr = curr;
  1999. prevTime = curr;
  2000. args[0] = createDebug.coerce(args[0]);
  2001. if (typeof args[0] !== 'string') {
  2002. // Anything else let's inspect with %O
  2003. args.unshift('%O');
  2004. }
  2005. // Apply any `formatters` transformations
  2006. let index = 0;
  2007. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  2008. // If we encounter an escaped % then don't increase the array index
  2009. if (match === '%%') {
  2010. return '%';
  2011. }
  2012. index++;
  2013. const formatter = createDebug.formatters[format];
  2014. if (typeof formatter === 'function') {
  2015. const val = args[index];
  2016. match = formatter.call(self, val);
  2017. // Now we need to remove `args[index]` since it's inlined in the `format`
  2018. args.splice(index, 1);
  2019. index--;
  2020. }
  2021. return match;
  2022. });
  2023. // Apply env-specific formatting (colors, etc.)
  2024. createDebug.formatArgs.call(self, args);
  2025. const logFn = self.log || createDebug.log;
  2026. logFn.apply(self, args);
  2027. }
  2028. debug.namespace = namespace;
  2029. debug.useColors = createDebug.useColors();
  2030. debug.color = createDebug.selectColor(namespace);
  2031. debug.extend = extend;
  2032. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  2033. Object.defineProperty(debug, 'enabled', {
  2034. enumerable: true,
  2035. configurable: false,
  2036. get: () => {
  2037. if (enableOverride !== null) {
  2038. return enableOverride;
  2039. }
  2040. if (namespacesCache !== createDebug.namespaces) {
  2041. namespacesCache = createDebug.namespaces;
  2042. enabledCache = createDebug.enabled(namespace);
  2043. }
  2044. return enabledCache;
  2045. },
  2046. set: v => {
  2047. enableOverride = v;
  2048. }
  2049. });
  2050. // Env-specific initialization logic for debug instances
  2051. if (typeof createDebug.init === 'function') {
  2052. createDebug.init(debug);
  2053. }
  2054. return debug;
  2055. }
  2056. function extend(namespace, delimiter) {
  2057. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  2058. newDebug.log = this.log;
  2059. return newDebug;
  2060. }
  2061. /**
  2062. * Enables a debug mode by namespaces. This can include modes
  2063. * separated by a colon and wildcards.
  2064. *
  2065. * @param {String} namespaces
  2066. * @api public
  2067. */
  2068. function enable(namespaces) {
  2069. createDebug.save(namespaces);
  2070. createDebug.namespaces = namespaces;
  2071. createDebug.names = [];
  2072. createDebug.skips = [];
  2073. let i;
  2074. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  2075. const len = split.length;
  2076. for (i = 0; i < len; i++) {
  2077. if (!split[i]) {
  2078. // ignore empty strings
  2079. continue;
  2080. }
  2081. namespaces = split[i].replace(/\*/g, '.*?');
  2082. if (namespaces[0] === '-') {
  2083. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2084. } else {
  2085. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  2086. }
  2087. }
  2088. }
  2089. /**
  2090. * Disable debug output.
  2091. *
  2092. * @return {String} namespaces
  2093. * @api public
  2094. */
  2095. function disable() {
  2096. const namespaces = [
  2097. ...createDebug.names.map(toNamespace),
  2098. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  2099. ].join(',');
  2100. createDebug.enable('');
  2101. return namespaces;
  2102. }
  2103. /**
  2104. * Returns true if the given mode name is enabled, false otherwise.
  2105. *
  2106. * @param {String} name
  2107. * @return {Boolean}
  2108. * @api public
  2109. */
  2110. function enabled(name) {
  2111. if (name[name.length - 1] === '*') {
  2112. return true;
  2113. }
  2114. let i;
  2115. let len;
  2116. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  2117. if (createDebug.skips[i].test(name)) {
  2118. return false;
  2119. }
  2120. }
  2121. for (i = 0, len = createDebug.names.length; i < len; i++) {
  2122. if (createDebug.names[i].test(name)) {
  2123. return true;
  2124. }
  2125. }
  2126. return false;
  2127. }
  2128. /**
  2129. * Convert regexp to namespace
  2130. *
  2131. * @param {RegExp} regxep
  2132. * @return {String} namespace
  2133. * @api private
  2134. */
  2135. function toNamespace(regexp) {
  2136. return regexp.toString()
  2137. .substring(2, regexp.toString().length - 2)
  2138. .replace(/\.\*\?$/, '*');
  2139. }
  2140. /**
  2141. * Coerce `val`.
  2142. *
  2143. * @param {Mixed} val
  2144. * @return {Mixed}
  2145. * @api private
  2146. */
  2147. function coerce(val) {
  2148. if (val instanceof Error) {
  2149. return val.stack || val.message;
  2150. }
  2151. return val;
  2152. }
  2153. /**
  2154. * XXX DO NOT USE. This is a temporary stub function.
  2155. * XXX It WILL be removed in the next major release.
  2156. */
  2157. function destroy() {
  2158. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  2159. }
  2160. createDebug.enable(createDebug.load());
  2161. return createDebug;
  2162. }
  2163. var common$e = setup;
  2164. /* eslint-env browser */
  2165. (function (module, exports) {
  2166. /**
  2167. * This is the web browser implementation of `debug()`.
  2168. */
  2169. exports.formatArgs = formatArgs;
  2170. exports.save = save;
  2171. exports.load = load;
  2172. exports.useColors = useColors;
  2173. exports.storage = localstorage();
  2174. exports.destroy = (() => {
  2175. let warned = false;
  2176. return () => {
  2177. if (!warned) {
  2178. warned = true;
  2179. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  2180. }
  2181. };
  2182. })();
  2183. /**
  2184. * Colors.
  2185. */
  2186. exports.colors = [
  2187. '#0000CC',
  2188. '#0000FF',
  2189. '#0033CC',
  2190. '#0033FF',
  2191. '#0066CC',
  2192. '#0066FF',
  2193. '#0099CC',
  2194. '#0099FF',
  2195. '#00CC00',
  2196. '#00CC33',
  2197. '#00CC66',
  2198. '#00CC99',
  2199. '#00CCCC',
  2200. '#00CCFF',
  2201. '#3300CC',
  2202. '#3300FF',
  2203. '#3333CC',
  2204. '#3333FF',
  2205. '#3366CC',
  2206. '#3366FF',
  2207. '#3399CC',
  2208. '#3399FF',
  2209. '#33CC00',
  2210. '#33CC33',
  2211. '#33CC66',
  2212. '#33CC99',
  2213. '#33CCCC',
  2214. '#33CCFF',
  2215. '#6600CC',
  2216. '#6600FF',
  2217. '#6633CC',
  2218. '#6633FF',
  2219. '#66CC00',
  2220. '#66CC33',
  2221. '#9900CC',
  2222. '#9900FF',
  2223. '#9933CC',
  2224. '#9933FF',
  2225. '#99CC00',
  2226. '#99CC33',
  2227. '#CC0000',
  2228. '#CC0033',
  2229. '#CC0066',
  2230. '#CC0099',
  2231. '#CC00CC',
  2232. '#CC00FF',
  2233. '#CC3300',
  2234. '#CC3333',
  2235. '#CC3366',
  2236. '#CC3399',
  2237. '#CC33CC',
  2238. '#CC33FF',
  2239. '#CC6600',
  2240. '#CC6633',
  2241. '#CC9900',
  2242. '#CC9933',
  2243. '#CCCC00',
  2244. '#CCCC33',
  2245. '#FF0000',
  2246. '#FF0033',
  2247. '#FF0066',
  2248. '#FF0099',
  2249. '#FF00CC',
  2250. '#FF00FF',
  2251. '#FF3300',
  2252. '#FF3333',
  2253. '#FF3366',
  2254. '#FF3399',
  2255. '#FF33CC',
  2256. '#FF33FF',
  2257. '#FF6600',
  2258. '#FF6633',
  2259. '#FF9900',
  2260. '#FF9933',
  2261. '#FFCC00',
  2262. '#FFCC33'
  2263. ];
  2264. /**
  2265. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2266. * and the Firebug extension (any Firefox version) are known
  2267. * to support "%c" CSS customizations.
  2268. *
  2269. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2270. */
  2271. // eslint-disable-next-line complexity
  2272. function useColors() {
  2273. // NB: In an Electron preload script, document will be defined but not fully
  2274. // initialized. Since we know we're in Chrome, we'll just detect this case
  2275. // explicitly
  2276. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  2277. return true;
  2278. }
  2279. // Internet Explorer and Edge do not support colors.
  2280. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  2281. return false;
  2282. }
  2283. // Is webkit? http://stackoverflow.com/a/16459606/376773
  2284. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  2285. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  2286. // Is firebug? http://stackoverflow.com/a/398120/376773
  2287. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  2288. // Is firefox >= v31?
  2289. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2290. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  2291. // Double check webkit in userAgent just in case we are in a worker
  2292. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  2293. }
  2294. /**
  2295. * Colorize log arguments if enabled.
  2296. *
  2297. * @api public
  2298. */
  2299. function formatArgs(args) {
  2300. args[0] = (this.useColors ? '%c' : '') +
  2301. this.namespace +
  2302. (this.useColors ? ' %c' : ' ') +
  2303. args[0] +
  2304. (this.useColors ? '%c ' : ' ') +
  2305. '+' + module.exports.humanize(this.diff);
  2306. if (!this.useColors) {
  2307. return;
  2308. }
  2309. const c = 'color: ' + this.color;
  2310. args.splice(1, 0, c, 'color: inherit');
  2311. // The final "%c" is somewhat tricky, because there could be other
  2312. // arguments passed either before or after the %c, so we need to
  2313. // figure out the correct index to insert the CSS into
  2314. let index = 0;
  2315. let lastC = 0;
  2316. args[0].replace(/%[a-zA-Z%]/g, match => {
  2317. if (match === '%%') {
  2318. return;
  2319. }
  2320. index++;
  2321. if (match === '%c') {
  2322. // We only are interested in the *last* %c
  2323. // (the user may have provided their own)
  2324. lastC = index;
  2325. }
  2326. });
  2327. args.splice(lastC, 0, c);
  2328. }
  2329. /**
  2330. * Invokes `console.debug()` when available.
  2331. * No-op when `console.debug` is not a "function".
  2332. * If `console.debug` is not available, falls back
  2333. * to `console.log`.
  2334. *
  2335. * @api public
  2336. */
  2337. exports.log = console.debug || console.log || (() => {});
  2338. /**
  2339. * Save `namespaces`.
  2340. *
  2341. * @param {String} namespaces
  2342. * @api private
  2343. */
  2344. function save(namespaces) {
  2345. try {
  2346. if (namespaces) {
  2347. exports.storage.setItem('debug', namespaces);
  2348. } else {
  2349. exports.storage.removeItem('debug');
  2350. }
  2351. } catch (error) {
  2352. // Swallow
  2353. // XXX (@Qix-) should we be logging these?
  2354. }
  2355. }
  2356. /**
  2357. * Load `namespaces`.
  2358. *
  2359. * @return {String} returns the previously persisted debug modes
  2360. * @api private
  2361. */
  2362. function load() {
  2363. let r;
  2364. try {
  2365. r = exports.storage.getItem('debug');
  2366. } catch (error) {
  2367. // Swallow
  2368. // XXX (@Qix-) should we be logging these?
  2369. }
  2370. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  2371. if (!r && typeof process !== 'undefined' && 'env' in process) {
  2372. r = process.env.DEBUG;
  2373. }
  2374. return r;
  2375. }
  2376. /**
  2377. * Localstorage attempts to return the localstorage.
  2378. *
  2379. * This is necessary because safari throws
  2380. * when a user disables cookies/localstorage
  2381. * and you attempt to access it.
  2382. *
  2383. * @return {LocalStorage}
  2384. * @api private
  2385. */
  2386. function localstorage() {
  2387. try {
  2388. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  2389. // The Browser also has localStorage in the global context.
  2390. return localStorage;
  2391. } catch (error) {
  2392. // Swallow
  2393. // XXX (@Qix-) should we be logging these?
  2394. }
  2395. }
  2396. module.exports = common$e(exports);
  2397. const {formatters} = module.exports;
  2398. /**
  2399. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2400. */
  2401. formatters.j = function (v) {
  2402. try {
  2403. return JSON.stringify(v);
  2404. } catch (error) {
  2405. return '[UnexpectedJSONParseError]: ' + error.message;
  2406. }
  2407. };
  2408. }(browser$2, browser$2.exports));
  2409. var node$2 = {exports: {}};
  2410. /**
  2411. * Module dependencies.
  2412. */
  2413. (function (module, exports) {
  2414. const tty = require$$0__default;
  2415. const util = require$$0__default$3;
  2416. /**
  2417. * This is the Node.js implementation of `debug()`.
  2418. */
  2419. exports.init = init;
  2420. exports.log = log;
  2421. exports.formatArgs = formatArgs;
  2422. exports.save = save;
  2423. exports.load = load;
  2424. exports.useColors = useColors;
  2425. exports.destroy = util.deprecate(
  2426. () => {},
  2427. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  2428. );
  2429. /**
  2430. * Colors.
  2431. */
  2432. exports.colors = [6, 2, 3, 4, 5, 1];
  2433. try {
  2434. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  2435. // eslint-disable-next-line import/no-extraneous-dependencies
  2436. const supportsColor = supportsColor_1$1;
  2437. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  2438. exports.colors = [
  2439. 20,
  2440. 21,
  2441. 26,
  2442. 27,
  2443. 32,
  2444. 33,
  2445. 38,
  2446. 39,
  2447. 40,
  2448. 41,
  2449. 42,
  2450. 43,
  2451. 44,
  2452. 45,
  2453. 56,
  2454. 57,
  2455. 62,
  2456. 63,
  2457. 68,
  2458. 69,
  2459. 74,
  2460. 75,
  2461. 76,
  2462. 77,
  2463. 78,
  2464. 79,
  2465. 80,
  2466. 81,
  2467. 92,
  2468. 93,
  2469. 98,
  2470. 99,
  2471. 112,
  2472. 113,
  2473. 128,
  2474. 129,
  2475. 134,
  2476. 135,
  2477. 148,
  2478. 149,
  2479. 160,
  2480. 161,
  2481. 162,
  2482. 163,
  2483. 164,
  2484. 165,
  2485. 166,
  2486. 167,
  2487. 168,
  2488. 169,
  2489. 170,
  2490. 171,
  2491. 172,
  2492. 173,
  2493. 178,
  2494. 179,
  2495. 184,
  2496. 185,
  2497. 196,
  2498. 197,
  2499. 198,
  2500. 199,
  2501. 200,
  2502. 201,
  2503. 202,
  2504. 203,
  2505. 204,
  2506. 205,
  2507. 206,
  2508. 207,
  2509. 208,
  2510. 209,
  2511. 214,
  2512. 215,
  2513. 220,
  2514. 221
  2515. ];
  2516. }
  2517. } catch (error) {
  2518. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  2519. }
  2520. /**
  2521. * Build up the default `inspectOpts` object from the environment variables.
  2522. *
  2523. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  2524. */
  2525. exports.inspectOpts = Object.keys(process.env).filter(key => {
  2526. return /^debug_/i.test(key);
  2527. }).reduce((obj, key) => {
  2528. // Camel-case
  2529. const prop = key
  2530. .substring(6)
  2531. .toLowerCase()
  2532. .replace(/_([a-z])/g, (_, k) => {
  2533. return k.toUpperCase();
  2534. });
  2535. // Coerce string value into JS value
  2536. let val = process.env[key];
  2537. if (/^(yes|on|true|enabled)$/i.test(val)) {
  2538. val = true;
  2539. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  2540. val = false;
  2541. } else if (val === 'null') {
  2542. val = null;
  2543. } else {
  2544. val = Number(val);
  2545. }
  2546. obj[prop] = val;
  2547. return obj;
  2548. }, {});
  2549. /**
  2550. * Is stdout a TTY? Colored output is enabled when `true`.
  2551. */
  2552. function useColors() {
  2553. return 'colors' in exports.inspectOpts ?
  2554. Boolean(exports.inspectOpts.colors) :
  2555. tty.isatty(process.stderr.fd);
  2556. }
  2557. /**
  2558. * Adds ANSI color escape codes if enabled.
  2559. *
  2560. * @api public
  2561. */
  2562. function formatArgs(args) {
  2563. const {namespace: name, useColors} = this;
  2564. if (useColors) {
  2565. const c = this.color;
  2566. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  2567. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  2568. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  2569. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  2570. } else {
  2571. args[0] = getDate() + name + ' ' + args[0];
  2572. }
  2573. }
  2574. function getDate() {
  2575. if (exports.inspectOpts.hideDate) {
  2576. return '';
  2577. }
  2578. return new Date().toISOString() + ' ';
  2579. }
  2580. /**
  2581. * Invokes `util.format()` with the specified arguments and writes to stderr.
  2582. */
  2583. function log(...args) {
  2584. return process.stderr.write(util.format(...args) + '\n');
  2585. }
  2586. /**
  2587. * Save `namespaces`.
  2588. *
  2589. * @param {String} namespaces
  2590. * @api private
  2591. */
  2592. function save(namespaces) {
  2593. if (namespaces) {
  2594. process.env.DEBUG = namespaces;
  2595. } else {
  2596. // If you set a process.env field to null or undefined, it gets cast to the
  2597. // string 'null' or 'undefined'. Just delete instead.
  2598. delete process.env.DEBUG;
  2599. }
  2600. }
  2601. /**
  2602. * Load `namespaces`.
  2603. *
  2604. * @return {String} returns the previously persisted debug modes
  2605. * @api private
  2606. */
  2607. function load() {
  2608. return process.env.DEBUG;
  2609. }
  2610. /**
  2611. * Init logic for `debug` instances.
  2612. *
  2613. * Create a new `inspectOpts` object in case `useColors` is set
  2614. * differently for a particular `debug` instance.
  2615. */
  2616. function init(debug) {
  2617. debug.inspectOpts = {};
  2618. const keys = Object.keys(exports.inspectOpts);
  2619. for (let i = 0; i < keys.length; i++) {
  2620. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  2621. }
  2622. }
  2623. module.exports = common$e(exports);
  2624. const {formatters} = module.exports;
  2625. /**
  2626. * Map %o to `util.inspect()`, all on a single line.
  2627. */
  2628. formatters.o = function (v) {
  2629. this.inspectOpts.colors = this.useColors;
  2630. return util.inspect(v, this.inspectOpts)
  2631. .split('\n')
  2632. .map(str => str.trim())
  2633. .join(' ');
  2634. };
  2635. /**
  2636. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  2637. */
  2638. formatters.O = function (v) {
  2639. this.inspectOpts.colors = this.useColors;
  2640. return util.inspect(v, this.inspectOpts);
  2641. };
  2642. }(node$2, node$2.exports));
  2643. /**
  2644. * Detect Electron renderer / nwjs process, which is node, but we should
  2645. * treat as a browser.
  2646. */
  2647. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  2648. src$3.exports = browser$2.exports;
  2649. } else {
  2650. src$3.exports = node$2.exports;
  2651. }
  2652. var debug$d = src$3.exports;
  2653. const DEFAULT_MAIN_FIELDS = [
  2654. 'module',
  2655. 'jsnext:main',
  2656. 'jsnext'
  2657. ];
  2658. const DEFAULT_EXTENSIONS = [
  2659. '.mjs',
  2660. '.js',
  2661. '.ts',
  2662. '.jsx',
  2663. '.tsx',
  2664. '.json'
  2665. ];
  2666. const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
  2667. const OPTIMIZABLE_ENTRY_RE = /\.(?:m?js|ts)$/;
  2668. const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/;
  2669. /**
  2670. * Prefix for resolved fs paths, since windows paths may not be valid as URLs.
  2671. */
  2672. const FS_PREFIX = `/@fs/`;
  2673. /**
  2674. * Prefix for resolved Ids that are not valid browser import specifiers
  2675. */
  2676. const VALID_ID_PREFIX = `/@id/`;
  2677. /**
  2678. * Some Rollup plugins use ids that starts with the null byte \0 to avoid
  2679. * collisions, but it is not permitted in import URLs so we have to replace
  2680. * them.
  2681. */
  2682. const NULL_BYTE_PLACEHOLDER = `__x00__`;
  2683. const CLIENT_PUBLIC_PATH = `/@vite/client`;
  2684. const ENV_PUBLIC_PATH = `/@vite/env`;
  2685. // eslint-disable-next-line node/no-missing-require
  2686. const CLIENT_ENTRY = require.resolve('vite/dist/client/client.mjs');
  2687. // eslint-disable-next-line node/no-missing-require
  2688. const ENV_ENTRY = require.resolve('vite/dist/client/env.mjs');
  2689. const CLIENT_DIR = path__default.dirname(CLIENT_ENTRY);
  2690. // ** READ THIS ** before editing `KNOWN_ASSET_TYPES`.
  2691. // If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it
  2692. // to the TypeScript declaration file `packages/vite/client.d.ts`.
  2693. const KNOWN_ASSET_TYPES = [
  2694. // images
  2695. 'png',
  2696. 'jpe?g',
  2697. 'gif',
  2698. 'svg',
  2699. 'ico',
  2700. 'webp',
  2701. 'avif',
  2702. // media
  2703. 'mp4',
  2704. 'webm',
  2705. 'ogg',
  2706. 'mp3',
  2707. 'wav',
  2708. 'flac',
  2709. 'aac',
  2710. // fonts
  2711. 'woff2?',
  2712. 'eot',
  2713. 'ttf',
  2714. 'otf',
  2715. // other
  2716. 'wasm',
  2717. 'webmanifest',
  2718. 'pdf'
  2719. ];
  2720. const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`);
  2721. const DEP_VERSION_RE = /[\?&](v=[\w\.-]+)\b/;
  2722. const {builtinModules} = require$$0__default$5;
  2723. const ignoreList = [
  2724. 'sys'
  2725. ];
  2726. // eslint-disable-next-line node/no-deprecated-api
  2727. var builtinModules_1 = (builtinModules || Object.keys(process.binding('natives')))
  2728. .filter(x => !/^_|^(internal|v8|node-inspect)\/|\//.test(x) && !ignoreList.includes(x))
  2729. .sort();
  2730. var charToInteger$1 = {};
  2731. var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  2732. for (var i$2 = 0; i$2 < chars$2.length; i$2++) {
  2733. charToInteger$1[chars$2.charCodeAt(i$2)] = i$2;
  2734. }
  2735. function decode(mappings) {
  2736. var decoded = [];
  2737. var line = [];
  2738. var segment = [
  2739. 0,
  2740. 0,
  2741. 0,
  2742. 0,
  2743. 0,
  2744. ];
  2745. var j = 0;
  2746. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  2747. var c = mappings.charCodeAt(i);
  2748. if (c === 44) { // ","
  2749. segmentify(line, segment, j);
  2750. j = 0;
  2751. }
  2752. else if (c === 59) { // ";"
  2753. segmentify(line, segment, j);
  2754. j = 0;
  2755. decoded.push(line);
  2756. line = [];
  2757. segment[0] = 0;
  2758. }
  2759. else {
  2760. var integer = charToInteger$1[c];
  2761. if (integer === undefined) {
  2762. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  2763. }
  2764. var hasContinuationBit = integer & 32;
  2765. integer &= 31;
  2766. value += integer << shift;
  2767. if (hasContinuationBit) {
  2768. shift += 5;
  2769. }
  2770. else {
  2771. var shouldNegate = value & 1;
  2772. value >>>= 1;
  2773. if (shouldNegate) {
  2774. value = value === 0 ? -0x80000000 : -value;
  2775. }
  2776. segment[j] += value;
  2777. j++;
  2778. value = shift = 0; // reset
  2779. }
  2780. }
  2781. }
  2782. segmentify(line, segment, j);
  2783. decoded.push(line);
  2784. return decoded;
  2785. }
  2786. function segmentify(line, segment, j) {
  2787. // This looks ugly, but we're creating specialized arrays with a specific
  2788. // length. This is much faster than creating a new array (which v8 expands to
  2789. // a capacity of 17 after pushing the first item), or slicing out a subarray
  2790. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  2791. // length 5 (since not everything will have an associated name), followed by
  2792. // length 1 (it's probably rare for a source substring to not have an
  2793. // associated segment data).
  2794. if (j === 4)
  2795. line.push([segment[0], segment[1], segment[2], segment[3]]);
  2796. else if (j === 5)
  2797. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  2798. else if (j === 1)
  2799. line.push([segment[0]]);
  2800. }
  2801. function encode$1(decoded) {
  2802. var sourceFileIndex = 0; // second field
  2803. var sourceCodeLine = 0; // third field
  2804. var sourceCodeColumn = 0; // fourth field
  2805. var nameIndex = 0; // fifth field
  2806. var mappings = '';
  2807. for (var i = 0; i < decoded.length; i++) {
  2808. var line = decoded[i];
  2809. if (i > 0)
  2810. mappings += ';';
  2811. if (line.length === 0)
  2812. continue;
  2813. var generatedCodeColumn = 0; // first field
  2814. var lineMappings = [];
  2815. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  2816. var segment = line_1[_i];
  2817. var segmentMappings = encodeInteger$1(segment[0] - generatedCodeColumn);
  2818. generatedCodeColumn = segment[0];
  2819. if (segment.length > 1) {
  2820. segmentMappings +=
  2821. encodeInteger$1(segment[1] - sourceFileIndex) +
  2822. encodeInteger$1(segment[2] - sourceCodeLine) +
  2823. encodeInteger$1(segment[3] - sourceCodeColumn);
  2824. sourceFileIndex = segment[1];
  2825. sourceCodeLine = segment[2];
  2826. sourceCodeColumn = segment[3];
  2827. }
  2828. if (segment.length === 5) {
  2829. segmentMappings += encodeInteger$1(segment[4] - nameIndex);
  2830. nameIndex = segment[4];
  2831. }
  2832. lineMappings.push(segmentMappings);
  2833. }
  2834. mappings += lineMappings.join(',');
  2835. }
  2836. return mappings;
  2837. }
  2838. function encodeInteger$1(num) {
  2839. var result = '';
  2840. num = num < 0 ? (-num << 1) | 1 : num << 1;
  2841. do {
  2842. var clamped = num & 31;
  2843. num >>>= 5;
  2844. if (num > 0) {
  2845. clamped |= 32;
  2846. }
  2847. result += chars$2[clamped];
  2848. } while (num > 0);
  2849. return result;
  2850. }
  2851. /**
  2852. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  2853. *
  2854. * Licensed under the Apache License, Version 2.0 (the "License");
  2855. * you may not use this file except in compliance with the License.
  2856. * You may obtain a copy of the License at
  2857. *
  2858. * http://www.apache.org/licenses/LICENSE-2.0
  2859. *
  2860. * Unless required by applicable law or agreed to in writing, software
  2861. * distributed under the License is distributed on an "AS IS" BASIS,
  2862. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2863. * See the License for the specific language governing permissions and
  2864. * limitations under the License.
  2865. */
  2866. /**
  2867. * Creates a brand new (prototype-less) object with the enumerable-own
  2868. * properties of `target`. Any enumerable-own properties from `source` which
  2869. * are not present on `target` will be copied as well.
  2870. */
  2871. function defaults(target, source) {
  2872. return Object.assign(Object.create(null), source, target);
  2873. }
  2874. /**
  2875. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  2876. *
  2877. * Licensed under the Apache License, Version 2.0 (the "License");
  2878. * you may not use this file except in compliance with the License.
  2879. * You may obtain a copy of the License at
  2880. *
  2881. * http://www.apache.org/licenses/LICENSE-2.0
  2882. *
  2883. * Unless required by applicable law or agreed to in writing, software
  2884. * distributed under the License is distributed on an "AS IS" BASIS,
  2885. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2886. * See the License for the specific language governing permissions and
  2887. * limitations under the License.
  2888. */
  2889. /**
  2890. * Decodes an input sourcemap into a `DecodedSourceMap` sourcemap object.
  2891. *
  2892. * Valid input maps include a `DecodedSourceMap`, a `RawSourceMap`, or JSON
  2893. * representations of either type.
  2894. */
  2895. function decodeSourceMap(map) {
  2896. if (typeof map === 'string') {
  2897. map = JSON.parse(map);
  2898. }
  2899. let { mappings } = map;
  2900. if (typeof mappings === 'string') {
  2901. mappings = sortMappings(decode(mappings), true);
  2902. }
  2903. else {
  2904. // Clone the Line so that we can sort it. We don't want to mutate an array
  2905. // that we don't own directly.
  2906. mappings = sortMappings(mappings, false);
  2907. }
  2908. return defaults({ mappings }, map);
  2909. }
  2910. function firstUnsortedSegmentLine(mappings) {
  2911. for (let i = 0; i < mappings.length; i++) {
  2912. const segments = mappings[i];
  2913. for (let j = 1; j < segments.length; j++) {
  2914. if (segments[j][0] < segments[j - 1][0]) {
  2915. return i;
  2916. }
  2917. }
  2918. }
  2919. return mappings.length;
  2920. }
  2921. function sortMappings(mappings, owned) {
  2922. const unosrtedIndex = firstUnsortedSegmentLine(mappings);
  2923. if (unosrtedIndex === mappings.length)
  2924. return mappings;
  2925. if (!owned)
  2926. mappings = mappings.slice();
  2927. for (let i = unosrtedIndex; i < mappings.length; i++) {
  2928. mappings[i] = sortSegments(mappings[i], owned);
  2929. }
  2930. return mappings;
  2931. }
  2932. function sortSegments(segments, owned) {
  2933. if (!owned)
  2934. segments = segments.slice();
  2935. return segments.sort(segmentComparator);
  2936. }
  2937. function segmentComparator(a, b) {
  2938. return a[0] - b[0];
  2939. }
  2940. /**
  2941. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  2942. *
  2943. * Licensed under the Apache License, Version 2.0 (the "License");
  2944. * you may not use this file except in compliance with the License.
  2945. * You may obtain a copy of the License at
  2946. *
  2947. * http://www.apache.org/licenses/LICENSE-2.0
  2948. *
  2949. * Unless required by applicable law or agreed to in writing, software
  2950. * distributed under the License is distributed on an "AS IS" BASIS,
  2951. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2952. * See the License for the specific language governing permissions and
  2953. * limitations under the License.
  2954. */
  2955. /**
  2956. * A "leaf" node in the sourcemap tree, representing an original, unmodified
  2957. * source file. Recursive segment tracing ends at the `OriginalSource`.
  2958. */
  2959. class OriginalSource {
  2960. constructor(filename, content) {
  2961. this.filename = filename;
  2962. this.content = content;
  2963. }
  2964. /**
  2965. * Tracing a `SourceMapSegment` ends when we get to an `OriginalSource`,
  2966. * meaning this line/column location originated from this source file.
  2967. */
  2968. traceSegment(line, column, name) {
  2969. return { column, line, name, source: this };
  2970. }
  2971. }
  2972. /* istanbul ignore next */
  2973. const Url$1 = (typeof URL !== 'undefined' ? URL : require('url').URL);
  2974. // Matches "..", which must be preceeded by "/" or the start of the string, and
  2975. // must be followed by a "/". We do not eat the following "/", so that the next
  2976. // iteration can match on it.
  2977. const parentRegex = /(^|\/)\.\.(?=\/|$)/g;
  2978. function isAbsoluteUrl(url) {
  2979. try {
  2980. return !!new Url$1(url);
  2981. }
  2982. catch (e) {
  2983. return false;
  2984. }
  2985. }
  2986. /**
  2987. * Creates a directory name that is guaranteed to not be in `str`.
  2988. */
  2989. function uniqInStr(str) {
  2990. let uniq = String(Math.random()).slice(2);
  2991. while (str.indexOf(uniq) > -1) {
  2992. /* istanbul ignore next */
  2993. uniq += uniq;
  2994. }
  2995. return uniq;
  2996. }
  2997. /**
  2998. * Removes the filename from the path (everything trailing the last "/"). This
  2999. * is only safe to call on a path, never call with an absolute or protocol
  3000. * relative URL.
  3001. */
  3002. function stripPathFilename(path) {
  3003. path = normalizePath$5(path);
  3004. const index = path.lastIndexOf('/');
  3005. return path.slice(0, index + 1);
  3006. }
  3007. /**
  3008. * Normalizes a protocol-relative URL, but keeps it protocol relative by
  3009. * stripping out the protocl before returning it.
  3010. */
  3011. function normalizeProtocolRelative(input, absoluteBase) {
  3012. const { href, protocol } = new Url$1(input, absoluteBase);
  3013. return href.slice(protocol.length);
  3014. }
  3015. /**
  3016. * Normalizes a simple path (one that has no ".."s, or is absolute so ".."s can
  3017. * be normalized absolutely).
  3018. */
  3019. function normalizeSimplePath(input) {
  3020. const { href } = new Url$1(input, 'https://foo.com/');
  3021. return href.slice('https://foo.com/'.length);
  3022. }
  3023. /**
  3024. * Normalizes a path, ensuring that excess ".."s are preserved for relative
  3025. * paths in the output.
  3026. *
  3027. * If the input is absolute, this will return an absolutey normalized path, but
  3028. * it will not have a leading "/".
  3029. *
  3030. * If the input has a leading "..", the output will have a leading "..".
  3031. *
  3032. * If the input has a leading ".", the output will not have a leading "."
  3033. * unless there are too many ".."s, in which case there will be a leading "..".
  3034. */
  3035. function normalizePath$5(input) {
  3036. // If there are no ".."s, we can treat this as if it were an absolute path.
  3037. // The return won't be an absolute path, so it's easy.
  3038. if (!parentRegex.test(input))
  3039. return normalizeSimplePath(input);
  3040. // We already found one "..". Let's see how many there are.
  3041. let total = 1;
  3042. while (parentRegex.test(input))
  3043. total++;
  3044. // If there are ".."s, we need to prefix the the path with the same number of
  3045. // unique directories. This is to ensure that we "remember" how many parent
  3046. // directories we are accessing. Eg, "../../.." must keep 3, and "foo/../.."
  3047. // must keep 1.
  3048. const uniqDirectory = `z${uniqInStr(input)}/`;
  3049. // uniqDirectory is just a "z", followed by numbers, followed by a "/". So
  3050. // generating a runtime regex from it is safe. We'll use this search regex to
  3051. // strip out our uniq directory names and insert any needed ".."s.
  3052. const search = new RegExp(`^(?:${uniqDirectory})*`);
  3053. // Now we can resolve the total path. If there are excess ".."s, they will
  3054. // eliminate one or more of the unique directories we prefix with.
  3055. const relative = normalizeSimplePath(uniqDirectory.repeat(total) + input);
  3056. // We can now count the number of unique directories that were eliminated. If
  3057. // there were 3, and 1 was eliminated, we know we only need to add 1 "..". If
  3058. // 2 were eliminated, we need to insert 2 ".."s. If all 3 were eliminated,
  3059. // then we need 3, etc. This replace is guranteed to match (it may match 0 or
  3060. // more times), and we can count the total match to see how many were eliminated.
  3061. return relative.replace(search, (all) => {
  3062. const leftover = all.length / uniqDirectory.length;
  3063. return '../'.repeat(total - leftover);
  3064. });
  3065. }
  3066. /**
  3067. * Attempts to resolve `input` URL relative to `base`.
  3068. */
  3069. function resolve$3(input, base) {
  3070. if (!base)
  3071. base = '';
  3072. // Absolute URLs are very easy to resolve right.
  3073. if (isAbsoluteUrl(input))
  3074. return new Url$1(input).href;
  3075. if (base) {
  3076. // Absolute URLs are easy...
  3077. if (isAbsoluteUrl(base))
  3078. return new Url$1(input, base).href;
  3079. // If base is protocol relative, we'll resolve with it but keep the result
  3080. // protocol relative.
  3081. if (base.startsWith('//'))
  3082. return normalizeProtocolRelative(input, `https:${base}`);
  3083. }
  3084. // Normalize input, but keep it protocol relative. We know base doesn't supply
  3085. // a protocol, because that would have been handled above.
  3086. if (input.startsWith('//'))
  3087. return normalizeProtocolRelative(input, 'https://foo.com/');
  3088. // We now know that base (if there is one) and input are paths. We've handled
  3089. // both absolute and protocol-relative variations above.
  3090. // Absolute paths don't need any special handling, because they cannot have
  3091. // extra "." or ".."s. That'll all be stripped away. Input takes priority here,
  3092. // because if input is an absolute path, base path won't affect it in any way.
  3093. if (input.startsWith('/'))
  3094. return '/' + normalizeSimplePath(input);
  3095. // Since input and base are paths, we need to join them to do any further
  3096. // processing. Paths are joined at the directory level, so we need to remove
  3097. // the base's filename before joining. We also know that input does not have a
  3098. // leading slash, and that the stripped base will have a trailing slash if
  3099. // there are any directories (or it'll be empty).
  3100. const joined = stripPathFilename(base) + input;
  3101. // If base is an absolute path, then input will be relative to it.
  3102. if (base.startsWith('/'))
  3103. return '/' + normalizeSimplePath(joined);
  3104. // We now know both base (if there is one) and input are relative paths.
  3105. const relative = normalizePath$5(joined);
  3106. // If base started with a leading ".", or there is no base and input started
  3107. // with a ".", then we need to ensure that the relative path starts with a
  3108. // ".". We don't know if relative starts with a "..", though, so check before
  3109. // prepending.
  3110. if ((base || input).startsWith('.') && !relative.startsWith('.')) {
  3111. return './' + relative;
  3112. }
  3113. return relative;
  3114. }
  3115. /**
  3116. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  3117. *
  3118. * Licensed under the Apache License, Version 2.0 (the "License");
  3119. * you may not use this file except in compliance with the License.
  3120. * You may obtain a copy of the License at
  3121. *
  3122. * http://www.apache.org/licenses/LICENSE-2.0
  3123. *
  3124. * Unless required by applicable law or agreed to in writing, software
  3125. * distributed under the License is distributed on an "AS IS" BASIS,
  3126. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3127. * See the License for the specific language governing permissions and
  3128. * limitations under the License.
  3129. */
  3130. function resolve$1$1(input, base) {
  3131. // The base is always treated as a directory, if it's not empty.
  3132. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  3133. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  3134. if (base && !base.endsWith('/'))
  3135. base += '/';
  3136. return resolve$3(input, base);
  3137. }
  3138. /**
  3139. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  3140. *
  3141. * Licensed under the Apache License, Version 2.0 (the "License");
  3142. * you may not use this file except in compliance with the License.
  3143. * You may obtain a copy of the License at
  3144. *
  3145. * http://www.apache.org/licenses/LICENSE-2.0
  3146. *
  3147. * Unless required by applicable law or agreed to in writing, software
  3148. * distributed under the License is distributed on an "AS IS" BASIS,
  3149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3150. * See the License for the specific language governing permissions and
  3151. * limitations under the License.
  3152. */
  3153. /**
  3154. * A binary search implementation that returns the index if a match is found,
  3155. * or the negated index of where the `needle` should be inserted.
  3156. *
  3157. * The `comparator` callback receives both the `item` under comparison and the
  3158. * needle we are searching for. It must return `0` if the `item` is a match,
  3159. * any negative number if `item` is too small (and we must search after it), or
  3160. * any positive number if the `item` is too large (and we must search before
  3161. * it).
  3162. *
  3163. * If no match is found, a negated index of where to insert the `needle` is
  3164. * returned. This negated index is guaranteed to be less than 0. To insert an
  3165. * item, negate it (again) and splice:
  3166. *
  3167. * ```js
  3168. * const array = [1, 3];
  3169. * const needle = 2;
  3170. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  3171. *
  3172. * assert.equal(index, -2);
  3173. * assert.equal(~index, 1);
  3174. * array.splice(~index, 0, needle);
  3175. * assert.deepEqual(array, [1, 2, 3]);
  3176. * ```
  3177. */
  3178. function binarySearch$4(haystack, needle, comparator, low, high) {
  3179. low = Math.max(low, 0);
  3180. while (low <= high) {
  3181. const mid = low + ((high - low) >> 1);
  3182. const cmp = comparator(haystack[mid], needle);
  3183. if (cmp === 0) {
  3184. return mid;
  3185. }
  3186. if (cmp < 0) {
  3187. low = mid + 1;
  3188. }
  3189. else {
  3190. high = mid - 1;
  3191. }
  3192. }
  3193. return ~low;
  3194. }
  3195. /**
  3196. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  3197. *
  3198. * Licensed under the Apache License, Version 2.0 (the "License");
  3199. * you may not use this file except in compliance with the License.
  3200. * You may obtain a copy of the License at
  3201. *
  3202. * http://www.apache.org/licenses/LICENSE-2.0
  3203. *
  3204. * Unless required by applicable law or agreed to in writing, software
  3205. * distributed under the License is distributed on an "AS IS" BASIS,
  3206. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3207. * See the License for the specific language governing permissions and
  3208. * limitations under the License.
  3209. */
  3210. /**
  3211. * FastStringArray acts like a `Set` (allowing only one occurrence of a string
  3212. * `key`), but provides the index of the `key` in the backing array.
  3213. *
  3214. * This is designed to allow synchronizing a second array with the contents of
  3215. * the backing array, like how `sourcesContent[i]` is the source content
  3216. * associated with `source[i]`, and there are never duplicates.
  3217. */
  3218. class FastStringArray {
  3219. constructor() {
  3220. this.indexes = Object.create(null);
  3221. this.array = [];
  3222. }
  3223. /**
  3224. * Puts `key` into the backing array, if it is not already present. Returns
  3225. * the index of the `key` in the backing array.
  3226. */
  3227. put(key) {
  3228. const { array, indexes } = this;
  3229. // The key may or may not be present. If it is present, it's a number.
  3230. let index = indexes[key];
  3231. // If it's not yet present, we need to insert it and track the index in the
  3232. // indexes.
  3233. if (index === undefined) {
  3234. index = indexes[key] = array.length;
  3235. array.push(key);
  3236. }
  3237. return index;
  3238. }
  3239. }
  3240. /**
  3241. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  3242. *
  3243. * Licensed under the Apache License, Version 2.0 (the "License");
  3244. * you may not use this file except in compliance with the License.
  3245. * You may obtain a copy of the License at
  3246. *
  3247. * http://www.apache.org/licenses/LICENSE-2.0
  3248. *
  3249. * Unless required by applicable law or agreed to in writing, software
  3250. * distributed under the License is distributed on an "AS IS" BASIS,
  3251. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3252. * See the License for the specific language governing permissions and
  3253. * limitations under the License.
  3254. */
  3255. /**
  3256. * SourceMapTree represents a single sourcemap, with the ability to trace
  3257. * mappings into its child nodes (which may themselves be SourceMapTrees).
  3258. */
  3259. class SourceMapTree {
  3260. constructor(map, sources) {
  3261. this.map = map;
  3262. this.sources = sources;
  3263. this.lastLine = 0;
  3264. this.lastColumn = 0;
  3265. this.lastIndex = 0;
  3266. }
  3267. /**
  3268. * traceMappings is only called on the root level SourceMapTree, and begins
  3269. * the process of resolving each mapping in terms of the original source
  3270. * files.
  3271. */
  3272. traceMappings() {
  3273. const mappings = [];
  3274. const names = new FastStringArray();
  3275. const sources = new FastStringArray();
  3276. const sourcesContent = [];
  3277. const { mappings: rootMappings, names: rootNames } = this.map;
  3278. for (let i = 0; i < rootMappings.length; i++) {
  3279. const segments = rootMappings[i];
  3280. const tracedSegments = [];
  3281. let lastTraced = undefined;
  3282. for (let j = 0; j < segments.length; j++) {
  3283. const segment = segments[j];
  3284. // 1-length segments only move the current generated column, there's no
  3285. // source information to gather from it.
  3286. if (segment.length === 1)
  3287. continue;
  3288. const source = this.sources[segment[1]];
  3289. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
  3290. if (!traced)
  3291. continue;
  3292. // So we traced a segment down into its original source file. Now push a
  3293. // new segment pointing to this location.
  3294. const { column, line, name } = traced;
  3295. const { content, filename } = traced.source;
  3296. // Store the source location, and ensure we keep sourcesContent up to
  3297. // date with the sources array.
  3298. const sourceIndex = sources.put(filename);
  3299. sourcesContent[sourceIndex] = content;
  3300. if (lastTraced &&
  3301. lastTraced[1] === sourceIndex &&
  3302. lastTraced[2] === line &&
  3303. lastTraced[3] === column) {
  3304. // This is a duplicate mapping pointing at the exact same starting point in the source file.
  3305. // It doesn't provide any new information, and only bloats the sourcemap.
  3306. continue;
  3307. }
  3308. // This looks like unnecessary duplication, but it noticeably increases
  3309. // performance. If we were to push the nameIndex onto length-4 array, v8
  3310. // would internally allocate 22 slots! That's 68 wasted bytes! Array
  3311. // literals have the same capacity as their length, saving memory.
  3312. if (name) {
  3313. lastTraced = [segment[0], sourceIndex, line, column, names.put(name)];
  3314. }
  3315. else {
  3316. lastTraced = [segment[0], sourceIndex, line, column];
  3317. }
  3318. tracedSegments.push(lastTraced);
  3319. }
  3320. mappings.push(tracedSegments);
  3321. }
  3322. // TODO: Make all sources relative to the sourceRoot.
  3323. return defaults({
  3324. mappings,
  3325. names: names.array,
  3326. sources: sources.array,
  3327. sourcesContent,
  3328. }, this.map);
  3329. }
  3330. /**
  3331. * traceSegment is only called on children SourceMapTrees. It recurses down
  3332. * into its own child SourceMapTrees, until we find the original source map.
  3333. */
  3334. traceSegment(line, column, name) {
  3335. const { mappings, names } = this.map;
  3336. // It's common for parent sourcemaps to have pointers to lines that have no
  3337. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  3338. if (line >= mappings.length)
  3339. return null;
  3340. const segments = mappings[line];
  3341. if (segments.length === 0)
  3342. return null;
  3343. let low = 0;
  3344. let high = segments.length - 1;
  3345. if (line === this.lastLine) {
  3346. if (column >= this.lastColumn) {
  3347. low = this.lastIndex;
  3348. }
  3349. else {
  3350. high = this.lastIndex;
  3351. }
  3352. }
  3353. let index = binarySearch$4(segments, column, segmentComparator$1, low, high);
  3354. this.lastLine = line;
  3355. this.lastColumn = column;
  3356. if (index === -1) {
  3357. this.lastIndex = index;
  3358. return null; // we come before any mapped segment
  3359. }
  3360. // If we can't find a segment that lines up to this column, we use the
  3361. // segment before.
  3362. if (index < 0) {
  3363. index = ~index - 1;
  3364. }
  3365. this.lastIndex = index;
  3366. const segment = segments[index];
  3367. // 1-length segments only move the current generated column, there's no
  3368. // source information to gather from it.
  3369. if (segment.length === 1)
  3370. return null;
  3371. const source = this.sources[segment[1]];
  3372. // So now we can recurse down, until we hit the original source file.
  3373. return source.traceSegment(segment[2], segment[3],
  3374. // A child map's recorded name for this segment takes precedence over the
  3375. // parent's mapped name. Imagine a mangler changing the name over, etc.
  3376. segment.length === 5 ? names[segment[4]] : name);
  3377. }
  3378. }
  3379. function segmentComparator$1(segment, column) {
  3380. return segment[0] - column;
  3381. }
  3382. /**
  3383. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  3384. *
  3385. * Licensed under the Apache License, Version 2.0 (the "License");
  3386. * you may not use this file except in compliance with the License.
  3387. * You may obtain a copy of the License at
  3388. *
  3389. * http://www.apache.org/licenses/LICENSE-2.0
  3390. *
  3391. * Unless required by applicable law or agreed to in writing, software
  3392. * distributed under the License is distributed on an "AS IS" BASIS,
  3393. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3394. * See the License for the specific language governing permissions and
  3395. * limitations under the License.
  3396. */
  3397. /**
  3398. * Removes the filename from a path.
  3399. */
  3400. function stripFilename(path) {
  3401. if (!path)
  3402. return '';
  3403. const index = path.lastIndexOf('/');
  3404. return path.slice(0, index + 1);
  3405. }
  3406. /**
  3407. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  3408. *
  3409. * Licensed under the Apache License, Version 2.0 (the "License");
  3410. * you may not use this file except in compliance with the License.
  3411. * You may obtain a copy of the License at
  3412. *
  3413. * http://www.apache.org/licenses/LICENSE-2.0
  3414. *
  3415. * Unless required by applicable law or agreed to in writing, software
  3416. * distributed under the License is distributed on an "AS IS" BASIS,
  3417. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3418. * See the License for the specific language governing permissions and
  3419. * limitations under the License.
  3420. */
  3421. function asArray(value) {
  3422. if (Array.isArray(value))
  3423. return value;
  3424. return [value];
  3425. }
  3426. /**
  3427. * Recursively builds a tree structure out of sourcemap files, with each node
  3428. * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
  3429. * `OriginalSource`s and `SourceMapTree`s.
  3430. *
  3431. * Every sourcemap is composed of a collection of source files and mappings
  3432. * into locations of those source files. When we generate a `SourceMapTree` for
  3433. * the sourcemap, we attempt to load each source file's own sourcemap. If it
  3434. * does not have an associated sourcemap, it is considered an original,
  3435. * unmodified source file.
  3436. */
  3437. function buildSourceMapTree(input, loader, relativeRoot) {
  3438. const maps = asArray(input).map(decodeSourceMap);
  3439. const map = maps.pop();
  3440. for (let i = 0; i < maps.length; i++) {
  3441. if (maps[i].sources.length !== 1) {
  3442. throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
  3443. 'Did you specify these with the most recent transformation maps first?');
  3444. }
  3445. }
  3446. const { sourceRoot, sources, sourcesContent } = map;
  3447. const children = sources.map((sourceFile, i) => {
  3448. // Each source file is loaded relative to the sourcemap's own sourceRoot,
  3449. // which is itself relative to the sourcemap's parent.
  3450. const uri = resolve$1$1(sourceFile || '', resolve$1$1(sourceRoot || '', stripFilename(relativeRoot)));
  3451. // Use the provided loader callback to retrieve the file's sourcemap.
  3452. // TODO: We should eventually support async loading of sourcemap files.
  3453. const sourceMap = loader(uri);
  3454. // If there is no sourcemap, then it is an unmodified source file.
  3455. if (!sourceMap) {
  3456. // The source file's actual contents must be included in the sourcemap
  3457. // (done when generating the sourcemap) for it to be included as a
  3458. // sourceContent in the output sourcemap.
  3459. const sourceContent = sourcesContent ? sourcesContent[i] : null;
  3460. return new OriginalSource(uri, sourceContent);
  3461. }
  3462. // Else, it's a real sourcemap, and we need to recurse into it to load its
  3463. // source files.
  3464. return buildSourceMapTree(decodeSourceMap(sourceMap), loader, uri);
  3465. });
  3466. let tree = new SourceMapTree(map, children);
  3467. for (let i = maps.length - 1; i >= 0; i--) {
  3468. tree = new SourceMapTree(maps[i], [tree]);
  3469. }
  3470. return tree;
  3471. }
  3472. /**
  3473. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  3474. *
  3475. * Licensed under the Apache License, Version 2.0 (the "License");
  3476. * you may not use this file except in compliance with the License.
  3477. * You may obtain a copy of the License at
  3478. *
  3479. * http://www.apache.org/licenses/LICENSE-2.0
  3480. *
  3481. * Unless required by applicable law or agreed to in writing, software
  3482. * distributed under the License is distributed on an "AS IS" BASIS,
  3483. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3484. * See the License for the specific language governing permissions and
  3485. * limitations under the License.
  3486. */
  3487. /**
  3488. * A SourceMap v3 compatible sourcemap, which only includes fields that were
  3489. * provided to it.
  3490. */
  3491. class SourceMap$1 {
  3492. constructor(map, options) {
  3493. this.version = 3; // SourceMap spec says this should be first.
  3494. if ('file' in map)
  3495. this.file = map.file;
  3496. this.mappings = options.decodedMappings ? map.mappings : encode$1(map.mappings);
  3497. this.names = map.names;
  3498. // TODO: We first need to make all source URIs relative to the sourceRoot
  3499. // before we can support a sourceRoot.
  3500. // if ('sourceRoot' in map) this.sourceRoot = map.sourceRoot;
  3501. this.sources = map.sources;
  3502. if (!options.excludeContent && 'sourcesContent' in map) {
  3503. this.sourcesContent = map.sourcesContent;
  3504. }
  3505. }
  3506. toString() {
  3507. return JSON.stringify(this);
  3508. }
  3509. }
  3510. /**
  3511. * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
  3512. *
  3513. * Licensed under the Apache License, Version 2.0 (the "License");
  3514. * you may not use this file except in compliance with the License.
  3515. * You may obtain a copy of the License at
  3516. *
  3517. * http://www.apache.org/licenses/LICENSE-2.0
  3518. *
  3519. * Unless required by applicable law or agreed to in writing, software
  3520. * distributed under the License is distributed on an "AS IS" BASIS,
  3521. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3522. * See the License for the specific language governing permissions and
  3523. * limitations under the License.
  3524. */
  3525. /**
  3526. * Traces through all the mappings in the root sourcemap, through the sources
  3527. * (and their sourcemaps), all the way back to the original source location.
  3528. *
  3529. * `loader` will be called every time we encounter a source file. If it returns
  3530. * a sourcemap, we will recurse into that sourcemap to continue the trace. If
  3531. * it returns a falsey value, that source file is treated as an original,
  3532. * unmodified source file.
  3533. *
  3534. * Pass `excludeContent` to exclude any self-containing source file content
  3535. * from the output sourcemap.
  3536. *
  3537. * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
  3538. * VLQ encoded) mappings.
  3539. */
  3540. function remapping(input, loader, options) {
  3541. const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
  3542. const graph = buildSourceMapTree(input, loader);
  3543. return new SourceMap$1(graph.traceMappings(), opts);
  3544. }
  3545. function slash$3(p) {
  3546. return p.replace(/\\/g, '/');
  3547. }
  3548. // Strip valid id prefix. This is prepended to resolved Ids that are
  3549. // not valid browser import specifiers by the importAnalysis plugin.
  3550. function unwrapId$1(id) {
  3551. return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id;
  3552. }
  3553. const flattenId = (id) => id.replace(/(\s*>\s*)/g, '__').replace(/[\/\.]/g, '_');
  3554. const normalizeId$1 = (id) => id.replace(/(\s*>\s*)/g, ' > ');
  3555. function isBuiltin(id) {
  3556. return builtinModules_1.includes(id);
  3557. }
  3558. const bareImportRE = /^[\w@](?!.*:\/\/)/;
  3559. const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
  3560. let isRunningWithYarnPnp;
  3561. try {
  3562. isRunningWithYarnPnp = Boolean(require('pnpapi'));
  3563. }
  3564. catch { }
  3565. const ssrExtensions = ['.js', '.cjs', '.json', '.node'];
  3566. function resolveFrom$3(id, basedir, ssr = false) {
  3567. return resolve__default.sync(id, {
  3568. basedir,
  3569. extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS,
  3570. // necessary to work with pnpm
  3571. preserveSymlinks: isRunningWithYarnPnp || false
  3572. });
  3573. }
  3574. /**
  3575. * like `resolveFrom` but supports resolving `>` path in `id`,
  3576. * for example: `foo > bar > baz`
  3577. */
  3578. function nestedResolveFrom(id, basedir) {
  3579. const pkgs = id.split('>').map((pkg) => pkg.trim());
  3580. try {
  3581. for (const pkg of pkgs) {
  3582. basedir = resolveFrom$3(pkg, basedir);
  3583. }
  3584. }
  3585. catch { }
  3586. return basedir;
  3587. }
  3588. // set in bin/vite.js
  3589. const filter$1 = process.env.VITE_DEBUG_FILTER;
  3590. const DEBUG$1 = process.env.DEBUG;
  3591. function createDebugger(namespace, options = {}) {
  3592. const log = debug$d(namespace);
  3593. const { onlyWhenFocused } = options;
  3594. const focus = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace;
  3595. return (msg, ...args) => {
  3596. if (filter$1 && !msg.includes(filter$1)) {
  3597. return;
  3598. }
  3599. if (onlyWhenFocused && !(DEBUG$1 === null || DEBUG$1 === void 0 ? void 0 : DEBUG$1.includes(focus))) {
  3600. return;
  3601. }
  3602. log(msg, ...args);
  3603. };
  3604. }
  3605. const isWindows$4 = require$$0__default$1.platform() === 'win32';
  3606. const VOLUME_RE = /^[A-Z]:/i;
  3607. function normalizePath$4(id) {
  3608. return path__default.posix.normalize(isWindows$4 ? slash$3(id) : id);
  3609. }
  3610. function fsPathFromId(id) {
  3611. const fsPath = normalizePath$4(id.slice(FS_PREFIX.length));
  3612. return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
  3613. ? fsPath
  3614. : `/${fsPath}`;
  3615. }
  3616. function ensureVolumeInPath(file) {
  3617. return isWindows$4 ? path__default.resolve(file) : file;
  3618. }
  3619. const queryRE = /\?.*$/s;
  3620. const hashRE = /#.*$/s;
  3621. const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, '');
  3622. const externalRE = /^(https?:)?\/\//;
  3623. const isExternalUrl = (url) => externalRE.test(url);
  3624. const dataUrlRE = /^\s*data:/i;
  3625. const isDataUrl = (url) => dataUrlRE.test(url);
  3626. const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte)($|\?)/;
  3627. const isJSRequest = (url) => {
  3628. url = cleanUrl(url);
  3629. if (knownJsSrcRE.test(url)) {
  3630. return true;
  3631. }
  3632. if (!path__default.extname(url) && !url.endsWith('/')) {
  3633. return true;
  3634. }
  3635. return false;
  3636. };
  3637. const importQueryRE = /(\?|&)import=?(?:&|$)/;
  3638. const internalPrefixes = [
  3639. FS_PREFIX,
  3640. VALID_ID_PREFIX,
  3641. CLIENT_PUBLIC_PATH,
  3642. ENV_PUBLIC_PATH
  3643. ];
  3644. const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`);
  3645. const trailingSeparatorRE = /[\?&]$/;
  3646. const isImportRequest = (url) => importQueryRE.test(url);
  3647. const isInternalRequest = (url) => InternalPrefixRE.test(url);
  3648. function removeImportQuery(url) {
  3649. return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, '');
  3650. }
  3651. function injectQuery(url, queryToInject) {
  3652. // encode percents for consistent behavior with pathToFileURL
  3653. // see #2614 for details
  3654. let resolvedUrl = new require$$0$a.URL(url.replace(/%/g, '%25'), 'relative:///');
  3655. if (resolvedUrl.protocol !== 'relative:') {
  3656. resolvedUrl = require$$0$a.pathToFileURL(url);
  3657. }
  3658. let { protocol, pathname, search, hash } = resolvedUrl;
  3659. if (protocol === 'file:') {
  3660. pathname = pathname.slice(1);
  3661. }
  3662. pathname = decodeURIComponent(pathname);
  3663. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`;
  3664. }
  3665. const timestampRE = /\bt=\d{13}&?\b/;
  3666. function removeTimestampQuery(url) {
  3667. return url.replace(timestampRE, '').replace(trailingSeparatorRE, '');
  3668. }
  3669. async function asyncReplace(input, re, replacer) {
  3670. let match;
  3671. let remaining = input;
  3672. let rewritten = '';
  3673. while ((match = re.exec(remaining))) {
  3674. rewritten += remaining.slice(0, match.index);
  3675. rewritten += await replacer(match);
  3676. remaining = remaining.slice(match.index + match[0].length);
  3677. }
  3678. rewritten += remaining;
  3679. return rewritten;
  3680. }
  3681. function timeFrom(start, subtract = 0) {
  3682. const time = Date.now() - start - subtract;
  3683. const timeString = (time + `ms`).padEnd(5, ' ');
  3684. if (time < 10) {
  3685. return source.green(timeString);
  3686. }
  3687. else if (time < 50) {
  3688. return source.yellow(timeString);
  3689. }
  3690. else {
  3691. return source.red(timeString);
  3692. }
  3693. }
  3694. /**
  3695. * pretty url for logging.
  3696. */
  3697. function prettifyUrl(url, root) {
  3698. url = removeTimestampQuery(url);
  3699. const isAbsoluteFile = url.startsWith(root);
  3700. if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
  3701. let file = path__default.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
  3702. const seg = file.split('/');
  3703. const npmIndex = seg.indexOf(`node_modules`);
  3704. const isSourceMap = file.endsWith('.map');
  3705. if (npmIndex > 0) {
  3706. file = seg[npmIndex + 1];
  3707. if (file.startsWith('@')) {
  3708. file = `${file}/${seg[npmIndex + 2]}`;
  3709. }
  3710. file = `npm: ${source.dim(file)}${isSourceMap ? ` (source map)` : ``}`;
  3711. }
  3712. return source.dim(file);
  3713. }
  3714. else {
  3715. return source.dim(url);
  3716. }
  3717. }
  3718. function isObject$3(value) {
  3719. return Object.prototype.toString.call(value) === '[object Object]';
  3720. }
  3721. function isDefined(value) {
  3722. return value != null;
  3723. }
  3724. function lookupFile(dir, formats, pathOnly = false) {
  3725. for (const format of formats) {
  3726. const fullPath = path__default.join(dir, format);
  3727. if (fs__default.existsSync(fullPath) && fs__default.statSync(fullPath).isFile()) {
  3728. return pathOnly ? fullPath : fs__default.readFileSync(fullPath, 'utf-8');
  3729. }
  3730. }
  3731. const parentDir = path__default.dirname(dir);
  3732. if (parentDir !== dir) {
  3733. return lookupFile(parentDir, formats, pathOnly);
  3734. }
  3735. }
  3736. const splitRE = /\r?\n/;
  3737. const range$1 = 2;
  3738. function pad$1(source, n = 2) {
  3739. const lines = source.split(splitRE);
  3740. return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
  3741. }
  3742. function posToNumber(source, pos) {
  3743. if (typeof pos === 'number')
  3744. return pos;
  3745. const lines = source.split(splitRE);
  3746. const { line, column } = pos;
  3747. let start = 0;
  3748. for (let i = 0; i < line - 1; i++) {
  3749. start += lines[i].length + 1;
  3750. }
  3751. return start + column;
  3752. }
  3753. function numberToPos(source, offset) {
  3754. if (typeof offset !== 'number')
  3755. return offset;
  3756. if (offset > source.length) {
  3757. throw new Error('offset is longer than source length!');
  3758. }
  3759. const lines = source.split(splitRE);
  3760. let counted = 0;
  3761. let line = 0;
  3762. let column = 0;
  3763. for (; line < lines.length; line++) {
  3764. const lineLength = lines[line].length + 1;
  3765. if (counted + lineLength >= offset) {
  3766. column = offset - counted + 1;
  3767. break;
  3768. }
  3769. counted += lineLength;
  3770. }
  3771. return { line: line + 1, column };
  3772. }
  3773. function generateCodeFrame(source, start = 0, end) {
  3774. start = posToNumber(source, start);
  3775. end = end || start;
  3776. const lines = source.split(splitRE);
  3777. let count = 0;
  3778. const res = [];
  3779. for (let i = 0; i < lines.length; i++) {
  3780. count += lines[i].length + 1;
  3781. if (count >= start) {
  3782. for (let j = i - range$1; j <= i + range$1 || end > count; j++) {
  3783. if (j < 0 || j >= lines.length)
  3784. continue;
  3785. const line = j + 1;
  3786. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  3787. const lineLength = lines[j].length;
  3788. if (j === i) {
  3789. // push underline
  3790. const pad = start - (count - lineLength) + 1;
  3791. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  3792. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  3793. }
  3794. else if (j > i) {
  3795. if (end > count) {
  3796. const length = Math.max(Math.min(end - count, lineLength), 1);
  3797. res.push(` | ` + '^'.repeat(length));
  3798. }
  3799. count += lineLength + 1;
  3800. }
  3801. }
  3802. break;
  3803. }
  3804. }
  3805. return res.join('\n');
  3806. }
  3807. function writeFile(filename, content) {
  3808. const dir = path__default.dirname(filename);
  3809. if (!fs__default.existsSync(dir)) {
  3810. fs__default.mkdirSync(dir, { recursive: true });
  3811. }
  3812. fs__default.writeFileSync(filename, content);
  3813. }
  3814. /**
  3815. * Delete every file and subdirectory. **The given directory must exist.**
  3816. * Pass an optional `skip` array to preserve files in the root directory.
  3817. */
  3818. function emptyDir(dir, skip) {
  3819. for (const file of fs__default.readdirSync(dir)) {
  3820. if (skip === null || skip === void 0 ? void 0 : skip.includes(file)) {
  3821. continue;
  3822. }
  3823. const abs = path__default.resolve(dir, file);
  3824. // baseline is Node 12 so can't use rmSync :(
  3825. if (fs__default.lstatSync(abs).isDirectory()) {
  3826. emptyDir(abs);
  3827. fs__default.rmdirSync(abs);
  3828. }
  3829. else {
  3830. fs__default.unlinkSync(abs);
  3831. }
  3832. }
  3833. }
  3834. function copyDir(srcDir, destDir) {
  3835. fs__default.mkdirSync(destDir, { recursive: true });
  3836. for (const file of fs__default.readdirSync(srcDir)) {
  3837. const srcFile = path__default.resolve(srcDir, file);
  3838. if (srcFile === destDir) {
  3839. continue;
  3840. }
  3841. const destFile = path__default.resolve(destDir, file);
  3842. const stat = fs__default.statSync(srcFile);
  3843. if (stat.isDirectory()) {
  3844. copyDir(srcFile, destFile);
  3845. }
  3846. else {
  3847. fs__default.copyFileSync(srcFile, destFile);
  3848. }
  3849. }
  3850. }
  3851. function ensureLeadingSlash(path) {
  3852. return !path.startsWith('/') ? '/' + path : path;
  3853. }
  3854. function ensureWatchedFile(watcher, file, root) {
  3855. if (file &&
  3856. // only need to watch if out of root
  3857. !file.startsWith(root + '/') &&
  3858. // some rollup plugins use null bytes for private resolved Ids
  3859. !file.includes('\0') &&
  3860. fs__default.existsSync(file)) {
  3861. // resolve file to normalized system path
  3862. watcher.add(path__default.resolve(file));
  3863. }
  3864. }
  3865. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  3866. async function processSrcSet(srcs, replacer) {
  3867. const imageCandidates = srcs
  3868. .split(',')
  3869. .map((s) => {
  3870. const [url, descriptor] = s
  3871. .replace(escapedSpaceCharacters, ' ')
  3872. .trim()
  3873. .split(' ', 2);
  3874. return { url, descriptor };
  3875. })
  3876. .filter(({ url }) => !!url);
  3877. const ret = await Promise.all(imageCandidates.map(async ({ url, descriptor }) => {
  3878. return {
  3879. url: await replacer({ url, descriptor }),
  3880. descriptor
  3881. };
  3882. }));
  3883. const url = ret.reduce((prev, { url, descriptor }, index) => {
  3884. descriptor = descriptor || '';
  3885. return (prev +=
  3886. url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`);
  3887. }, '');
  3888. return url;
  3889. }
  3890. // based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221
  3891. const nullSourceMap = {
  3892. names: [],
  3893. sources: [],
  3894. mappings: '',
  3895. version: 3
  3896. };
  3897. function combineSourcemaps(filename, sourcemapList) {
  3898. if (sourcemapList.length === 0 ||
  3899. sourcemapList.every((m) => m.sources.length === 0)) {
  3900. return { ...nullSourceMap };
  3901. }
  3902. // We don't declare type here so we can convert/fake/map as RawSourceMap
  3903. let map; //: SourceMap
  3904. let mapIndex = 1;
  3905. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined;
  3906. if (useArrayInterface) {
  3907. map = remapping(sourcemapList, () => null, true);
  3908. }
  3909. else {
  3910. map = remapping(sourcemapList[0], function loader(sourcefile) {
  3911. if (sourcefile === filename && sourcemapList[mapIndex]) {
  3912. return sourcemapList[mapIndex++];
  3913. }
  3914. else {
  3915. return { ...nullSourceMap };
  3916. }
  3917. }, true);
  3918. }
  3919. if (!map.file) {
  3920. delete map.file;
  3921. }
  3922. return map;
  3923. }
  3924. function unique(arr) {
  3925. return Array.from(new Set(arr));
  3926. }
  3927. function resolveHostname(optionsHost) {
  3928. let host;
  3929. if (optionsHost === undefined ||
  3930. optionsHost === false ||
  3931. optionsHost === 'localhost') {
  3932. // Use a secure default
  3933. host = '127.0.0.1';
  3934. }
  3935. else if (optionsHost === true) {
  3936. // If passed --host in the CLI without arguments
  3937. host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
  3938. }
  3939. else {
  3940. host = optionsHost;
  3941. }
  3942. // Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1'
  3943. const name = (optionsHost !== '127.0.0.1' && host === '127.0.0.1') ||
  3944. host === '0.0.0.0' ||
  3945. host === '::' ||
  3946. host === undefined
  3947. ? 'localhost'
  3948. : host;
  3949. return { host, name };
  3950. }
  3951. function arraify(target) {
  3952. return Array.isArray(target) ? target : [target];
  3953. }
  3954. const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm;
  3955. const singlelineCommentsRE = /\/\/.*/g;
  3956. /* eslint no-console: 0 */
  3957. const LogLevels = {
  3958. silent: 0,
  3959. error: 1,
  3960. warn: 2,
  3961. info: 3
  3962. };
  3963. let lastType;
  3964. let lastMsg;
  3965. let sameCount = 0;
  3966. function clearScreen() {
  3967. const repeatCount = process.stdout.rows - 2;
  3968. const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : '';
  3969. console.log(blank);
  3970. readline__default.cursorTo(process.stdout, 0, 0);
  3971. readline__default.clearScreenDown(process.stdout);
  3972. }
  3973. function createLogger(level = 'info', options = {}) {
  3974. if (options.customLogger) {
  3975. return options.customLogger;
  3976. }
  3977. const loggedErrors = new WeakSet();
  3978. const { prefix = '[vite]', allowClearScreen = true } = options;
  3979. const thresh = LogLevels[level];
  3980. const clear = allowClearScreen && process.stdout.isTTY && !process.env.CI
  3981. ? clearScreen
  3982. : () => { };
  3983. function output(type, msg, options = {}) {
  3984. if (thresh >= LogLevels[type]) {
  3985. const method = type === 'info' ? 'log' : type;
  3986. const format = () => {
  3987. if (options.timestamp) {
  3988. const tag = type === 'info'
  3989. ? source.cyan.bold(prefix)
  3990. : type === 'warn'
  3991. ? source.yellow.bold(prefix)
  3992. : source.red.bold(prefix);
  3993. return `${source.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`;
  3994. }
  3995. else {
  3996. return msg;
  3997. }
  3998. };
  3999. if (options.error) {
  4000. loggedErrors.add(options.error);
  4001. }
  4002. if (type === lastType && msg === lastMsg) {
  4003. sameCount++;
  4004. clear();
  4005. console[method](format(), source.yellow(`(x${sameCount + 1})`));
  4006. }
  4007. else {
  4008. sameCount = 0;
  4009. lastMsg = msg;
  4010. lastType = type;
  4011. if (options.clear) {
  4012. clear();
  4013. }
  4014. console[method](format());
  4015. }
  4016. }
  4017. }
  4018. const warnedMessages = new Set();
  4019. const logger = {
  4020. hasWarned: false,
  4021. info(msg, opts) {
  4022. output('info', msg, opts);
  4023. },
  4024. warn(msg, opts) {
  4025. logger.hasWarned = true;
  4026. output('warn', msg, opts);
  4027. },
  4028. warnOnce(msg, opts) {
  4029. if (warnedMessages.has(msg))
  4030. return;
  4031. logger.hasWarned = true;
  4032. output('warn', msg, opts);
  4033. warnedMessages.add(msg);
  4034. },
  4035. error(msg, opts) {
  4036. logger.hasWarned = true;
  4037. output('error', msg, opts);
  4038. },
  4039. clearScreen(type) {
  4040. if (thresh >= LogLevels[type]) {
  4041. clear();
  4042. }
  4043. },
  4044. hasErrorLogged(error) {
  4045. return loggedErrors.has(error);
  4046. }
  4047. };
  4048. return logger;
  4049. }
  4050. function printServerUrls(hostname, protocol, port, base, info) {
  4051. if (hostname.host === '127.0.0.1') {
  4052. const url = `${protocol}://${hostname.name}:${source.bold(port)}${base}`;
  4053. info(` > Local: ${source.cyan(url)}`);
  4054. if (hostname.name !== '127.0.0.1') {
  4055. info(` > Network: ${source.dim('use `--host` to expose')}`);
  4056. }
  4057. }
  4058. else {
  4059. Object.values(require$$0__default$1.networkInterfaces())
  4060. .flatMap((nInterface) => nInterface !== null && nInterface !== void 0 ? nInterface : [])
  4061. .filter((detail) => detail.family === 'IPv4')
  4062. .map((detail) => {
  4063. const type = detail.address.includes('127.0.0.1')
  4064. ? 'Local: '
  4065. : 'Network: ';
  4066. const host = detail.address.replace('127.0.0.1', hostname.name);
  4067. const url = `${protocol}://${host}:${source.bold(port)}${base}`;
  4068. return ` > ${type} ${source.cyan(url)}`;
  4069. })
  4070. .forEach((msg) => info(msg));
  4071. }
  4072. }
  4073. const writeColors = {
  4074. [0 /* JS */]: source.cyan,
  4075. [1 /* CSS */]: source.magenta,
  4076. [2 /* ASSET */]: source.green,
  4077. [3 /* HTML */]: source.blue,
  4078. [4 /* SOURCE_MAP */]: source.gray
  4079. };
  4080. function buildReporterPlugin(config) {
  4081. const chunkLimit = config.build.chunkSizeWarningLimit;
  4082. function isLarge(code) {
  4083. // bail out on particularly large chunks
  4084. return code.length / 1024 > chunkLimit;
  4085. }
  4086. async function getCompressedSize(code) {
  4087. if (config.build.ssr || !config.build.brotliSize) {
  4088. return '';
  4089. }
  4090. if (isLarge(code)) {
  4091. return ' / brotli: skipped (large chunk)';
  4092. }
  4093. return ` / brotli: ${((await _default(typeof code === 'string' ? code : Buffer.from(code))) / 1024).toFixed(2)} KiB`;
  4094. }
  4095. function printFileInfo(filePath, content, type, maxLength, compressedSize = '') {
  4096. const outDir = normalizePath$4(path__default.relative(config.root, path__default.resolve(config.root, config.build.outDir))) + '/';
  4097. const kibs = content.length / 1024;
  4098. const sizeColor = kibs > chunkLimit ? source.yellow : source.dim;
  4099. config.logger.info(`${source.gray(source.white.dim(outDir))}${writeColors[type](filePath.padEnd(maxLength + 2))} ${sizeColor(`${kibs.toFixed(2)} KiB${compressedSize}`)}`);
  4100. }
  4101. const tty = process.stdout.isTTY && !process.env.CI;
  4102. const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info;
  4103. let hasTransformed = false;
  4104. let hasRenderedChunk = false;
  4105. let transformedCount = 0;
  4106. let chunkCount = 0;
  4107. const logTransform = throttle((id) => {
  4108. writeLine(`transforming (${transformedCount}) ${source.dim(path__default.relative(config.root, id))}`);
  4109. });
  4110. return {
  4111. name: 'vite:reporter',
  4112. transform(_, id) {
  4113. transformedCount++;
  4114. if (shouldLogInfo) {
  4115. if (!tty) {
  4116. if (!hasTransformed) {
  4117. config.logger.info(`transforming...`);
  4118. }
  4119. }
  4120. else {
  4121. if (id.includes(`?`))
  4122. return;
  4123. logTransform(id);
  4124. }
  4125. hasTransformed = true;
  4126. }
  4127. return null;
  4128. },
  4129. buildEnd() {
  4130. if (shouldLogInfo) {
  4131. if (tty) {
  4132. process.stdout.clearLine(0);
  4133. process.stdout.cursorTo(0);
  4134. }
  4135. config.logger.info(`${source.green(`✓`)} ${transformedCount} modules transformed.`);
  4136. }
  4137. },
  4138. renderStart() {
  4139. chunkCount = 0;
  4140. },
  4141. renderChunk() {
  4142. chunkCount++;
  4143. if (shouldLogInfo) {
  4144. if (!tty) {
  4145. if (!hasRenderedChunk) {
  4146. config.logger.info('rendering chunks...');
  4147. }
  4148. }
  4149. else {
  4150. writeLine(`rendering chunks (${chunkCount})...`);
  4151. }
  4152. hasRenderedChunk = true;
  4153. }
  4154. return null;
  4155. },
  4156. generateBundle() {
  4157. if (shouldLogInfo && tty) {
  4158. process.stdout.clearLine(0);
  4159. process.stdout.cursorTo(0);
  4160. }
  4161. },
  4162. async writeBundle(_, output) {
  4163. let hasLargeChunks = false;
  4164. if (shouldLogInfo) {
  4165. let longest = 0;
  4166. for (const file in output) {
  4167. const l = output[file].fileName.length;
  4168. if (l > longest)
  4169. longest = l;
  4170. }
  4171. // large chunks are deferred to be logged at the end so they are more
  4172. // visible.
  4173. const deferredLogs = [];
  4174. await Promise.all(Object.keys(output).map(async (file) => {
  4175. const chunk = output[file];
  4176. if (chunk.type === 'chunk') {
  4177. const log = async () => {
  4178. printFileInfo(chunk.fileName, chunk.code, 0 /* JS */, longest, await getCompressedSize(chunk.code));
  4179. if (chunk.map) {
  4180. printFileInfo(chunk.fileName + '.map', chunk.map.toString(), 4 /* SOURCE_MAP */, longest);
  4181. }
  4182. };
  4183. if (isLarge(chunk.code)) {
  4184. hasLargeChunks = true;
  4185. deferredLogs.push(log);
  4186. }
  4187. else {
  4188. await log();
  4189. }
  4190. }
  4191. else if (chunk.source) {
  4192. const isCSS = chunk.fileName.endsWith('.css');
  4193. printFileInfo(chunk.fileName, chunk.source, isCSS ? 1 /* CSS */ : 2 /* ASSET */, longest, isCSS ? await getCompressedSize(chunk.source) : undefined);
  4194. }
  4195. }));
  4196. await Promise.all(deferredLogs.map((l) => l()));
  4197. }
  4198. else {
  4199. hasLargeChunks = Object.keys(output).some((file) => {
  4200. const chunk = output[file];
  4201. return chunk.type === 'chunk' && chunk.code.length / 1024 > chunkLimit;
  4202. });
  4203. }
  4204. if (hasLargeChunks &&
  4205. config.build.minify &&
  4206. !config.build.lib &&
  4207. !config.build.ssr) {
  4208. config.logger.warn(source.yellow(`\n(!) Some chunks are larger than ${chunkLimit} KiB after minification. Consider:\n` +
  4209. `- Using dynamic import() to code-split the application\n` +
  4210. `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n` +
  4211. `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`));
  4212. }
  4213. }
  4214. };
  4215. }
  4216. function writeLine(output) {
  4217. process.stdout.clearLine(0);
  4218. process.stdout.cursorTo(0);
  4219. if (output.length < process.stdout.columns) {
  4220. process.stdout.write(output);
  4221. }
  4222. else {
  4223. process.stdout.write(output.substring(0, process.stdout.columns - 1));
  4224. }
  4225. }
  4226. function throttle(fn) {
  4227. let timerHandle = null;
  4228. return (...args) => {
  4229. if (timerHandle)
  4230. return;
  4231. fn(...args);
  4232. timerHandle = setTimeout(() => {
  4233. timerHandle = null;
  4234. }, 100);
  4235. };
  4236. }
  4237. var charToInteger = {};
  4238. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  4239. for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
  4240. charToInteger[chars$1.charCodeAt(i$1)] = i$1;
  4241. }
  4242. function encode(decoded) {
  4243. var sourceFileIndex = 0; // second field
  4244. var sourceCodeLine = 0; // third field
  4245. var sourceCodeColumn = 0; // fourth field
  4246. var nameIndex = 0; // fifth field
  4247. var mappings = '';
  4248. for (var i = 0; i < decoded.length; i++) {
  4249. var line = decoded[i];
  4250. if (i > 0)
  4251. mappings += ';';
  4252. if (line.length === 0)
  4253. continue;
  4254. var generatedCodeColumn = 0; // first field
  4255. var lineMappings = [];
  4256. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  4257. var segment = line_1[_i];
  4258. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  4259. generatedCodeColumn = segment[0];
  4260. if (segment.length > 1) {
  4261. segmentMappings +=
  4262. encodeInteger(segment[1] - sourceFileIndex) +
  4263. encodeInteger(segment[2] - sourceCodeLine) +
  4264. encodeInteger(segment[3] - sourceCodeColumn);
  4265. sourceFileIndex = segment[1];
  4266. sourceCodeLine = segment[2];
  4267. sourceCodeColumn = segment[3];
  4268. }
  4269. if (segment.length === 5) {
  4270. segmentMappings += encodeInteger(segment[4] - nameIndex);
  4271. nameIndex = segment[4];
  4272. }
  4273. lineMappings.push(segmentMappings);
  4274. }
  4275. mappings += lineMappings.join(',');
  4276. }
  4277. return mappings;
  4278. }
  4279. function encodeInteger(num) {
  4280. var result = '';
  4281. num = num < 0 ? (-num << 1) | 1 : num << 1;
  4282. do {
  4283. var clamped = num & 31;
  4284. num >>>= 5;
  4285. if (num > 0) {
  4286. clamped |= 32;
  4287. }
  4288. result += chars$1[clamped];
  4289. } while (num > 0);
  4290. return result;
  4291. }
  4292. var BitSet = function BitSet(arg) {
  4293. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  4294. };
  4295. BitSet.prototype.add = function add (n) {
  4296. this.bits[n >> 5] |= 1 << (n & 31);
  4297. };
  4298. BitSet.prototype.has = function has (n) {
  4299. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  4300. };
  4301. var Chunk = function Chunk(start, end, content) {
  4302. this.start = start;
  4303. this.end = end;
  4304. this.original = content;
  4305. this.intro = '';
  4306. this.outro = '';
  4307. this.content = content;
  4308. this.storeName = false;
  4309. this.edited = false;
  4310. // we make these non-enumerable, for sanity while debugging
  4311. Object.defineProperties(this, {
  4312. previous: { writable: true, value: null },
  4313. next: { writable: true, value: null }
  4314. });
  4315. };
  4316. Chunk.prototype.appendLeft = function appendLeft (content) {
  4317. this.outro += content;
  4318. };
  4319. Chunk.prototype.appendRight = function appendRight (content) {
  4320. this.intro = this.intro + content;
  4321. };
  4322. Chunk.prototype.clone = function clone () {
  4323. var chunk = new Chunk(this.start, this.end, this.original);
  4324. chunk.intro = this.intro;
  4325. chunk.outro = this.outro;
  4326. chunk.content = this.content;
  4327. chunk.storeName = this.storeName;
  4328. chunk.edited = this.edited;
  4329. return chunk;
  4330. };
  4331. Chunk.prototype.contains = function contains (index) {
  4332. return this.start < index && index < this.end;
  4333. };
  4334. Chunk.prototype.eachNext = function eachNext (fn) {
  4335. var chunk = this;
  4336. while (chunk) {
  4337. fn(chunk);
  4338. chunk = chunk.next;
  4339. }
  4340. };
  4341. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  4342. var chunk = this;
  4343. while (chunk) {
  4344. fn(chunk);
  4345. chunk = chunk.previous;
  4346. }
  4347. };
  4348. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  4349. this.content = content;
  4350. if (!contentOnly) {
  4351. this.intro = '';
  4352. this.outro = '';
  4353. }
  4354. this.storeName = storeName;
  4355. this.edited = true;
  4356. return this;
  4357. };
  4358. Chunk.prototype.prependLeft = function prependLeft (content) {
  4359. this.outro = content + this.outro;
  4360. };
  4361. Chunk.prototype.prependRight = function prependRight (content) {
  4362. this.intro = content + this.intro;
  4363. };
  4364. Chunk.prototype.split = function split (index) {
  4365. var sliceIndex = index - this.start;
  4366. var originalBefore = this.original.slice(0, sliceIndex);
  4367. var originalAfter = this.original.slice(sliceIndex);
  4368. this.original = originalBefore;
  4369. var newChunk = new Chunk(index, this.end, originalAfter);
  4370. newChunk.outro = this.outro;
  4371. this.outro = '';
  4372. this.end = index;
  4373. if (this.edited) {
  4374. // TODO is this block necessary?...
  4375. newChunk.edit('', false);
  4376. this.content = '';
  4377. } else {
  4378. this.content = originalBefore;
  4379. }
  4380. newChunk.next = this.next;
  4381. if (newChunk.next) { newChunk.next.previous = newChunk; }
  4382. newChunk.previous = this;
  4383. this.next = newChunk;
  4384. return newChunk;
  4385. };
  4386. Chunk.prototype.toString = function toString () {
  4387. return this.intro + this.content + this.outro;
  4388. };
  4389. Chunk.prototype.trimEnd = function trimEnd (rx) {
  4390. this.outro = this.outro.replace(rx, '');
  4391. if (this.outro.length) { return true; }
  4392. var trimmed = this.content.replace(rx, '');
  4393. if (trimmed.length) {
  4394. if (trimmed !== this.content) {
  4395. this.split(this.start + trimmed.length).edit('', undefined, true);
  4396. }
  4397. return true;
  4398. } else {
  4399. this.edit('', undefined, true);
  4400. this.intro = this.intro.replace(rx, '');
  4401. if (this.intro.length) { return true; }
  4402. }
  4403. };
  4404. Chunk.prototype.trimStart = function trimStart (rx) {
  4405. this.intro = this.intro.replace(rx, '');
  4406. if (this.intro.length) { return true; }
  4407. var trimmed = this.content.replace(rx, '');
  4408. if (trimmed.length) {
  4409. if (trimmed !== this.content) {
  4410. this.split(this.end - trimmed.length);
  4411. this.edit('', undefined, true);
  4412. }
  4413. return true;
  4414. } else {
  4415. this.edit('', undefined, true);
  4416. this.outro = this.outro.replace(rx, '');
  4417. if (this.outro.length) { return true; }
  4418. }
  4419. };
  4420. var btoa$1 = function () {
  4421. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  4422. };
  4423. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  4424. btoa$1 = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  4425. } else if (typeof Buffer === 'function') {
  4426. btoa$1 = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  4427. }
  4428. var SourceMap = function SourceMap(properties) {
  4429. this.version = 3;
  4430. this.file = properties.file;
  4431. this.sources = properties.sources;
  4432. this.sourcesContent = properties.sourcesContent;
  4433. this.names = properties.names;
  4434. this.mappings = encode(properties.mappings);
  4435. };
  4436. SourceMap.prototype.toString = function toString () {
  4437. return JSON.stringify(this);
  4438. };
  4439. SourceMap.prototype.toUrl = function toUrl () {
  4440. return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
  4441. };
  4442. function guessIndent(code) {
  4443. var lines = code.split('\n');
  4444. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  4445. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  4446. if (tabbed.length === 0 && spaced.length === 0) {
  4447. return null;
  4448. }
  4449. // More lines tabbed than spaced? Assume tabs, and
  4450. // default to tabs in the case of a tie (or nothing
  4451. // to go on)
  4452. if (tabbed.length >= spaced.length) {
  4453. return '\t';
  4454. }
  4455. // Otherwise, we need to guess the multiple
  4456. var min = spaced.reduce(function (previous, current) {
  4457. var numSpaces = /^ +/.exec(current)[0].length;
  4458. return Math.min(numSpaces, previous);
  4459. }, Infinity);
  4460. return new Array(min + 1).join(' ');
  4461. }
  4462. function getRelativePath(from, to) {
  4463. var fromParts = from.split(/[/\\]/);
  4464. var toParts = to.split(/[/\\]/);
  4465. fromParts.pop(); // get dirname
  4466. while (fromParts[0] === toParts[0]) {
  4467. fromParts.shift();
  4468. toParts.shift();
  4469. }
  4470. if (fromParts.length) {
  4471. var i = fromParts.length;
  4472. while (i--) { fromParts[i] = '..'; }
  4473. }
  4474. return fromParts.concat(toParts).join('/');
  4475. }
  4476. var toString$2 = Object.prototype.toString;
  4477. function isObject$2(thing) {
  4478. return toString$2.call(thing) === '[object Object]';
  4479. }
  4480. function getLocator(source) {
  4481. var originalLines = source.split('\n');
  4482. var lineOffsets = [];
  4483. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  4484. lineOffsets.push(pos);
  4485. pos += originalLines[i].length + 1;
  4486. }
  4487. return function locate(index) {
  4488. var i = 0;
  4489. var j = lineOffsets.length;
  4490. while (i < j) {
  4491. var m = (i + j) >> 1;
  4492. if (index < lineOffsets[m]) {
  4493. j = m;
  4494. } else {
  4495. i = m + 1;
  4496. }
  4497. }
  4498. var line = i - 1;
  4499. var column = index - lineOffsets[line];
  4500. return { line: line, column: column };
  4501. };
  4502. }
  4503. var Mappings = function Mappings(hires) {
  4504. this.hires = hires;
  4505. this.generatedCodeLine = 0;
  4506. this.generatedCodeColumn = 0;
  4507. this.raw = [];
  4508. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  4509. this.pending = null;
  4510. };
  4511. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  4512. if (content.length) {
  4513. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  4514. if (nameIndex >= 0) {
  4515. segment.push(nameIndex);
  4516. }
  4517. this.rawSegments.push(segment);
  4518. } else if (this.pending) {
  4519. this.rawSegments.push(this.pending);
  4520. }
  4521. this.advance(content);
  4522. this.pending = null;
  4523. };
  4524. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  4525. var originalCharIndex = chunk.start;
  4526. var first = true;
  4527. while (originalCharIndex < chunk.end) {
  4528. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  4529. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  4530. }
  4531. if (original[originalCharIndex] === '\n') {
  4532. loc.line += 1;
  4533. loc.column = 0;
  4534. this.generatedCodeLine += 1;
  4535. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4536. this.generatedCodeColumn = 0;
  4537. first = true;
  4538. } else {
  4539. loc.column += 1;
  4540. this.generatedCodeColumn += 1;
  4541. first = false;
  4542. }
  4543. originalCharIndex += 1;
  4544. }
  4545. this.pending = null;
  4546. };
  4547. Mappings.prototype.advance = function advance (str) {
  4548. if (!str) { return; }
  4549. var lines = str.split('\n');
  4550. if (lines.length > 1) {
  4551. for (var i = 0; i < lines.length - 1; i++) {
  4552. this.generatedCodeLine++;
  4553. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4554. }
  4555. this.generatedCodeColumn = 0;
  4556. }
  4557. this.generatedCodeColumn += lines[lines.length - 1].length;
  4558. };
  4559. var n = '\n';
  4560. var warned$1 = {
  4561. insertLeft: false,
  4562. insertRight: false,
  4563. storeName: false
  4564. };
  4565. var MagicString = function MagicString(string, options) {
  4566. if ( options === void 0 ) options = {};
  4567. var chunk = new Chunk(0, string.length, string);
  4568. Object.defineProperties(this, {
  4569. original: { writable: true, value: string },
  4570. outro: { writable: true, value: '' },
  4571. intro: { writable: true, value: '' },
  4572. firstChunk: { writable: true, value: chunk },
  4573. lastChunk: { writable: true, value: chunk },
  4574. lastSearchedChunk: { writable: true, value: chunk },
  4575. byStart: { writable: true, value: {} },
  4576. byEnd: { writable: true, value: {} },
  4577. filename: { writable: true, value: options.filename },
  4578. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  4579. sourcemapLocations: { writable: true, value: new BitSet() },
  4580. storedNames: { writable: true, value: {} },
  4581. indentStr: { writable: true, value: guessIndent(string) }
  4582. });
  4583. this.byStart[0] = chunk;
  4584. this.byEnd[string.length] = chunk;
  4585. };
  4586. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  4587. this.sourcemapLocations.add(char);
  4588. };
  4589. MagicString.prototype.append = function append (content) {
  4590. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  4591. this.outro += content;
  4592. return this;
  4593. };
  4594. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  4595. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  4596. this._split(index);
  4597. var chunk = this.byEnd[index];
  4598. if (chunk) {
  4599. chunk.appendLeft(content);
  4600. } else {
  4601. this.intro += content;
  4602. }
  4603. return this;
  4604. };
  4605. MagicString.prototype.appendRight = function appendRight (index, content) {
  4606. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  4607. this._split(index);
  4608. var chunk = this.byStart[index];
  4609. if (chunk) {
  4610. chunk.appendRight(content);
  4611. } else {
  4612. this.outro += content;
  4613. }
  4614. return this;
  4615. };
  4616. MagicString.prototype.clone = function clone () {
  4617. var cloned = new MagicString(this.original, { filename: this.filename });
  4618. var originalChunk = this.firstChunk;
  4619. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  4620. while (originalChunk) {
  4621. cloned.byStart[clonedChunk.start] = clonedChunk;
  4622. cloned.byEnd[clonedChunk.end] = clonedChunk;
  4623. var nextOriginalChunk = originalChunk.next;
  4624. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  4625. if (nextClonedChunk) {
  4626. clonedChunk.next = nextClonedChunk;
  4627. nextClonedChunk.previous = clonedChunk;
  4628. clonedChunk = nextClonedChunk;
  4629. }
  4630. originalChunk = nextOriginalChunk;
  4631. }
  4632. cloned.lastChunk = clonedChunk;
  4633. if (this.indentExclusionRanges) {
  4634. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  4635. }
  4636. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  4637. cloned.intro = this.intro;
  4638. cloned.outro = this.outro;
  4639. return cloned;
  4640. };
  4641. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  4642. var this$1$1 = this;
  4643. options = options || {};
  4644. var sourceIndex = 0;
  4645. var names = Object.keys(this.storedNames);
  4646. var mappings = new Mappings(options.hires);
  4647. var locate = getLocator(this.original);
  4648. if (this.intro) {
  4649. mappings.advance(this.intro);
  4650. }
  4651. this.firstChunk.eachNext(function (chunk) {
  4652. var loc = locate(chunk.start);
  4653. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  4654. if (chunk.edited) {
  4655. mappings.addEdit(
  4656. sourceIndex,
  4657. chunk.content,
  4658. loc,
  4659. chunk.storeName ? names.indexOf(chunk.original) : -1
  4660. );
  4661. } else {
  4662. mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
  4663. }
  4664. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  4665. });
  4666. return {
  4667. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  4668. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  4669. sourcesContent: options.includeContent ? [this.original] : [null],
  4670. names: names,
  4671. mappings: mappings.raw
  4672. };
  4673. };
  4674. MagicString.prototype.generateMap = function generateMap (options) {
  4675. return new SourceMap(this.generateDecodedMap(options));
  4676. };
  4677. MagicString.prototype.getIndentString = function getIndentString () {
  4678. return this.indentStr === null ? '\t' : this.indentStr;
  4679. };
  4680. MagicString.prototype.indent = function indent (indentStr, options) {
  4681. var pattern = /^[^\r\n]/gm;
  4682. if (isObject$2(indentStr)) {
  4683. options = indentStr;
  4684. indentStr = undefined;
  4685. }
  4686. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  4687. if (indentStr === '') { return this; } // noop
  4688. options = options || {};
  4689. // Process exclusion ranges
  4690. var isExcluded = {};
  4691. if (options.exclude) {
  4692. var exclusions =
  4693. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  4694. exclusions.forEach(function (exclusion) {
  4695. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  4696. isExcluded[i] = true;
  4697. }
  4698. });
  4699. }
  4700. var shouldIndentNextCharacter = options.indentStart !== false;
  4701. var replacer = function (match) {
  4702. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  4703. shouldIndentNextCharacter = true;
  4704. return match;
  4705. };
  4706. this.intro = this.intro.replace(pattern, replacer);
  4707. var charIndex = 0;
  4708. var chunk = this.firstChunk;
  4709. while (chunk) {
  4710. var end = chunk.end;
  4711. if (chunk.edited) {
  4712. if (!isExcluded[charIndex]) {
  4713. chunk.content = chunk.content.replace(pattern, replacer);
  4714. if (chunk.content.length) {
  4715. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  4716. }
  4717. }
  4718. } else {
  4719. charIndex = chunk.start;
  4720. while (charIndex < end) {
  4721. if (!isExcluded[charIndex]) {
  4722. var char = this.original[charIndex];
  4723. if (char === '\n') {
  4724. shouldIndentNextCharacter = true;
  4725. } else if (char !== '\r' && shouldIndentNextCharacter) {
  4726. shouldIndentNextCharacter = false;
  4727. if (charIndex === chunk.start) {
  4728. chunk.prependRight(indentStr);
  4729. } else {
  4730. this._splitChunk(chunk, charIndex);
  4731. chunk = chunk.next;
  4732. chunk.prependRight(indentStr);
  4733. }
  4734. }
  4735. }
  4736. charIndex += 1;
  4737. }
  4738. }
  4739. charIndex = chunk.end;
  4740. chunk = chunk.next;
  4741. }
  4742. this.outro = this.outro.replace(pattern, replacer);
  4743. return this;
  4744. };
  4745. MagicString.prototype.insert = function insert () {
  4746. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  4747. };
  4748. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  4749. if (!warned$1.insertLeft) {
  4750. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  4751. warned$1.insertLeft = true;
  4752. }
  4753. return this.appendLeft(index, content);
  4754. };
  4755. MagicString.prototype.insertRight = function insertRight (index, content) {
  4756. if (!warned$1.insertRight) {
  4757. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  4758. warned$1.insertRight = true;
  4759. }
  4760. return this.prependRight(index, content);
  4761. };
  4762. MagicString.prototype.move = function move (start, end, index) {
  4763. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  4764. this._split(start);
  4765. this._split(end);
  4766. this._split(index);
  4767. var first = this.byStart[start];
  4768. var last = this.byEnd[end];
  4769. var oldLeft = first.previous;
  4770. var oldRight = last.next;
  4771. var newRight = this.byStart[index];
  4772. if (!newRight && last === this.lastChunk) { return this; }
  4773. var newLeft = newRight ? newRight.previous : this.lastChunk;
  4774. if (oldLeft) { oldLeft.next = oldRight; }
  4775. if (oldRight) { oldRight.previous = oldLeft; }
  4776. if (newLeft) { newLeft.next = first; }
  4777. if (newRight) { newRight.previous = last; }
  4778. if (!first.previous) { this.firstChunk = last.next; }
  4779. if (!last.next) {
  4780. this.lastChunk = first.previous;
  4781. this.lastChunk.next = null;
  4782. }
  4783. first.previous = newLeft;
  4784. last.next = newRight || null;
  4785. if (!newLeft) { this.firstChunk = first; }
  4786. if (!newRight) { this.lastChunk = last; }
  4787. return this;
  4788. };
  4789. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  4790. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  4791. while (start < 0) { start += this.original.length; }
  4792. while (end < 0) { end += this.original.length; }
  4793. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  4794. if (start === end)
  4795. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  4796. this._split(start);
  4797. this._split(end);
  4798. if (options === true) {
  4799. if (!warned$1.storeName) {
  4800. console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
  4801. warned$1.storeName = true;
  4802. }
  4803. options = { storeName: true };
  4804. }
  4805. var storeName = options !== undefined ? options.storeName : false;
  4806. var contentOnly = options !== undefined ? options.contentOnly : false;
  4807. if (storeName) {
  4808. var original = this.original.slice(start, end);
  4809. this.storedNames[original] = true;
  4810. }
  4811. var first = this.byStart[start];
  4812. var last = this.byEnd[end];
  4813. if (first) {
  4814. if (end > first.end && first.next !== this.byStart[first.end]) {
  4815. throw new Error('Cannot overwrite across a split point');
  4816. }
  4817. first.edit(content, storeName, contentOnly);
  4818. if (first !== last) {
  4819. var chunk = first.next;
  4820. while (chunk !== last) {
  4821. chunk.edit('', false);
  4822. chunk = chunk.next;
  4823. }
  4824. chunk.edit('', false);
  4825. }
  4826. } else {
  4827. // must be inserting at the end
  4828. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  4829. // TODO last chunk in the array may not be the last chunk, if it's moved...
  4830. last.next = newChunk;
  4831. newChunk.previous = last;
  4832. }
  4833. return this;
  4834. };
  4835. MagicString.prototype.prepend = function prepend (content) {
  4836. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  4837. this.intro = content + this.intro;
  4838. return this;
  4839. };
  4840. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  4841. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  4842. this._split(index);
  4843. var chunk = this.byEnd[index];
  4844. if (chunk) {
  4845. chunk.prependLeft(content);
  4846. } else {
  4847. this.intro = content + this.intro;
  4848. }
  4849. return this;
  4850. };
  4851. MagicString.prototype.prependRight = function prependRight (index, content) {
  4852. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  4853. this._split(index);
  4854. var chunk = this.byStart[index];
  4855. if (chunk) {
  4856. chunk.prependRight(content);
  4857. } else {
  4858. this.outro = content + this.outro;
  4859. }
  4860. return this;
  4861. };
  4862. MagicString.prototype.remove = function remove (start, end) {
  4863. while (start < 0) { start += this.original.length; }
  4864. while (end < 0) { end += this.original.length; }
  4865. if (start === end) { return this; }
  4866. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  4867. if (start > end) { throw new Error('end must be greater than start'); }
  4868. this._split(start);
  4869. this._split(end);
  4870. var chunk = this.byStart[start];
  4871. while (chunk) {
  4872. chunk.intro = '';
  4873. chunk.outro = '';
  4874. chunk.edit('');
  4875. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4876. }
  4877. return this;
  4878. };
  4879. MagicString.prototype.lastChar = function lastChar () {
  4880. if (this.outro.length)
  4881. { return this.outro[this.outro.length - 1]; }
  4882. var chunk = this.lastChunk;
  4883. do {
  4884. if (chunk.outro.length)
  4885. { return chunk.outro[chunk.outro.length - 1]; }
  4886. if (chunk.content.length)
  4887. { return chunk.content[chunk.content.length - 1]; }
  4888. if (chunk.intro.length)
  4889. { return chunk.intro[chunk.intro.length - 1]; }
  4890. } while (chunk = chunk.previous);
  4891. if (this.intro.length)
  4892. { return this.intro[this.intro.length - 1]; }
  4893. return '';
  4894. };
  4895. MagicString.prototype.lastLine = function lastLine () {
  4896. var lineIndex = this.outro.lastIndexOf(n);
  4897. if (lineIndex !== -1)
  4898. { return this.outro.substr(lineIndex + 1); }
  4899. var lineStr = this.outro;
  4900. var chunk = this.lastChunk;
  4901. do {
  4902. if (chunk.outro.length > 0) {
  4903. lineIndex = chunk.outro.lastIndexOf(n);
  4904. if (lineIndex !== -1)
  4905. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  4906. lineStr = chunk.outro + lineStr;
  4907. }
  4908. if (chunk.content.length > 0) {
  4909. lineIndex = chunk.content.lastIndexOf(n);
  4910. if (lineIndex !== -1)
  4911. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  4912. lineStr = chunk.content + lineStr;
  4913. }
  4914. if (chunk.intro.length > 0) {
  4915. lineIndex = chunk.intro.lastIndexOf(n);
  4916. if (lineIndex !== -1)
  4917. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  4918. lineStr = chunk.intro + lineStr;
  4919. }
  4920. } while (chunk = chunk.previous);
  4921. lineIndex = this.intro.lastIndexOf(n);
  4922. if (lineIndex !== -1)
  4923. { return this.intro.substr(lineIndex + 1) + lineStr; }
  4924. return this.intro + lineStr;
  4925. };
  4926. MagicString.prototype.slice = function slice (start, end) {
  4927. if ( start === void 0 ) start = 0;
  4928. if ( end === void 0 ) end = this.original.length;
  4929. while (start < 0) { start += this.original.length; }
  4930. while (end < 0) { end += this.original.length; }
  4931. var result = '';
  4932. // find start chunk
  4933. var chunk = this.firstChunk;
  4934. while (chunk && (chunk.start > start || chunk.end <= start)) {
  4935. // found end chunk before start
  4936. if (chunk.start < end && chunk.end >= end) {
  4937. return result;
  4938. }
  4939. chunk = chunk.next;
  4940. }
  4941. if (chunk && chunk.edited && chunk.start !== start)
  4942. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  4943. var startChunk = chunk;
  4944. while (chunk) {
  4945. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  4946. result += chunk.intro;
  4947. }
  4948. var containsEnd = chunk.start < end && chunk.end >= end;
  4949. if (containsEnd && chunk.edited && chunk.end !== end)
  4950. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  4951. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  4952. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  4953. result += chunk.content.slice(sliceStart, sliceEnd);
  4954. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  4955. result += chunk.outro;
  4956. }
  4957. if (containsEnd) {
  4958. break;
  4959. }
  4960. chunk = chunk.next;
  4961. }
  4962. return result;
  4963. };
  4964. // TODO deprecate this? not really very useful
  4965. MagicString.prototype.snip = function snip (start, end) {
  4966. var clone = this.clone();
  4967. clone.remove(0, start);
  4968. clone.remove(end, clone.original.length);
  4969. return clone;
  4970. };
  4971. MagicString.prototype._split = function _split (index) {
  4972. if (this.byStart[index] || this.byEnd[index]) { return; }
  4973. var chunk = this.lastSearchedChunk;
  4974. var searchForward = index > chunk.end;
  4975. while (chunk) {
  4976. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  4977. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  4978. }
  4979. };
  4980. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  4981. if (chunk.edited && chunk.content.length) {
  4982. // zero-length edited chunks are a special case (overlapping replacements)
  4983. var loc = getLocator(this.original)(index);
  4984. throw new Error(
  4985. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  4986. );
  4987. }
  4988. var newChunk = chunk.split(index);
  4989. this.byEnd[index] = chunk;
  4990. this.byStart[index] = newChunk;
  4991. this.byEnd[newChunk.end] = newChunk;
  4992. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  4993. this.lastSearchedChunk = chunk;
  4994. return true;
  4995. };
  4996. MagicString.prototype.toString = function toString () {
  4997. var str = this.intro;
  4998. var chunk = this.firstChunk;
  4999. while (chunk) {
  5000. str += chunk.toString();
  5001. chunk = chunk.next;
  5002. }
  5003. return str + this.outro;
  5004. };
  5005. MagicString.prototype.isEmpty = function isEmpty () {
  5006. var chunk = this.firstChunk;
  5007. do {
  5008. if (chunk.intro.length && chunk.intro.trim() ||
  5009. chunk.content.length && chunk.content.trim() ||
  5010. chunk.outro.length && chunk.outro.trim())
  5011. { return false; }
  5012. } while (chunk = chunk.next);
  5013. return true;
  5014. };
  5015. MagicString.prototype.length = function length () {
  5016. var chunk = this.firstChunk;
  5017. var length = 0;
  5018. do {
  5019. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  5020. } while (chunk = chunk.next);
  5021. return length;
  5022. };
  5023. MagicString.prototype.trimLines = function trimLines () {
  5024. return this.trim('[\\r\\n]');
  5025. };
  5026. MagicString.prototype.trim = function trim (charType) {
  5027. return this.trimStart(charType).trimEnd(charType);
  5028. };
  5029. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  5030. var rx = new RegExp((charType || '\\s') + '+$');
  5031. this.outro = this.outro.replace(rx, '');
  5032. if (this.outro.length) { return true; }
  5033. var chunk = this.lastChunk;
  5034. do {
  5035. var end = chunk.end;
  5036. var aborted = chunk.trimEnd(rx);
  5037. // if chunk was trimmed, we have a new lastChunk
  5038. if (chunk.end !== end) {
  5039. if (this.lastChunk === chunk) {
  5040. this.lastChunk = chunk.next;
  5041. }
  5042. this.byEnd[chunk.end] = chunk;
  5043. this.byStart[chunk.next.start] = chunk.next;
  5044. this.byEnd[chunk.next.end] = chunk.next;
  5045. }
  5046. if (aborted) { return true; }
  5047. chunk = chunk.previous;
  5048. } while (chunk);
  5049. return false;
  5050. };
  5051. MagicString.prototype.trimEnd = function trimEnd (charType) {
  5052. this.trimEndAborted(charType);
  5053. return this;
  5054. };
  5055. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  5056. var rx = new RegExp('^' + (charType || '\\s') + '+');
  5057. this.intro = this.intro.replace(rx, '');
  5058. if (this.intro.length) { return true; }
  5059. var chunk = this.firstChunk;
  5060. do {
  5061. var end = chunk.end;
  5062. var aborted = chunk.trimStart(rx);
  5063. if (chunk.end !== end) {
  5064. // special case...
  5065. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  5066. this.byEnd[chunk.end] = chunk;
  5067. this.byStart[chunk.next.start] = chunk.next;
  5068. this.byEnd[chunk.next.end] = chunk.next;
  5069. }
  5070. if (aborted) { return true; }
  5071. chunk = chunk.next;
  5072. } while (chunk);
  5073. return false;
  5074. };
  5075. MagicString.prototype.trimStart = function trimStart (charType) {
  5076. this.trimStartAborted(charType);
  5077. return this;
  5078. };
  5079. /**
  5080. * @param typeMap [Object] Map of MIME type -> Array[extensions]
  5081. * @param ...
  5082. */
  5083. function Mime$1() {
  5084. this._types = Object.create(null);
  5085. this._extensions = Object.create(null);
  5086. for (let i = 0; i < arguments.length; i++) {
  5087. this.define(arguments[i]);
  5088. }
  5089. this.define = this.define.bind(this);
  5090. this.getType = this.getType.bind(this);
  5091. this.getExtension = this.getExtension.bind(this);
  5092. }
  5093. /**
  5094. * Define mimetype -> extension mappings. Each key is a mime-type that maps
  5095. * to an array of extensions associated with the type. The first extension is
  5096. * used as the default extension for the type.
  5097. *
  5098. * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
  5099. *
  5100. * If a type declares an extension that has already been defined, an error will
  5101. * be thrown. To suppress this error and force the extension to be associated
  5102. * with the new type, pass `force`=true. Alternatively, you may prefix the
  5103. * extension with "*" to map the type to extension, without mapping the
  5104. * extension to the type.
  5105. *
  5106. * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
  5107. *
  5108. *
  5109. * @param map (Object) type definitions
  5110. * @param force (Boolean) if true, force overriding of existing definitions
  5111. */
  5112. Mime$1.prototype.define = function(typeMap, force) {
  5113. for (let type in typeMap) {
  5114. let extensions = typeMap[type].map(function(t) {
  5115. return t.toLowerCase();
  5116. });
  5117. type = type.toLowerCase();
  5118. for (let i = 0; i < extensions.length; i++) {
  5119. const ext = extensions[i];
  5120. // '*' prefix = not the preferred type for this extension. So fixup the
  5121. // extension, and skip it.
  5122. if (ext[0] === '*') {
  5123. continue;
  5124. }
  5125. if (!force && (ext in this._types)) {
  5126. throw new Error(
  5127. 'Attempt to change mapping for "' + ext +
  5128. '" extension from "' + this._types[ext] + '" to "' + type +
  5129. '". Pass `force=true` to allow this, otherwise remove "' + ext +
  5130. '" from the list of extensions for "' + type + '".'
  5131. );
  5132. }
  5133. this._types[ext] = type;
  5134. }
  5135. // Use first extension as default
  5136. if (force || !this._extensions[type]) {
  5137. const ext = extensions[0];
  5138. this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);
  5139. }
  5140. }
  5141. };
  5142. /**
  5143. * Lookup a mime type based on extension
  5144. */
  5145. Mime$1.prototype.getType = function(path) {
  5146. path = String(path);
  5147. let last = path.replace(/^.*[/\\]/, '').toLowerCase();
  5148. let ext = last.replace(/^.*\./, '').toLowerCase();
  5149. let hasPath = last.length < path.length;
  5150. let hasDot = ext.length < last.length - 1;
  5151. return (hasDot || !hasPath) && this._types[ext] || null;
  5152. };
  5153. /**
  5154. * Return file extension associated with a mime type
  5155. */
  5156. Mime$1.prototype.getExtension = function(type) {
  5157. type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
  5158. return type && this._extensions[type.toLowerCase()] || null;
  5159. };
  5160. var Mime_1 = Mime$1;
  5161. var standard = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma","es"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/mrb-consumer+xml":["*xdf"],"application/mrb-publish+xml":["*xdf"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["*xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-error+xml":["xer"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};
  5162. let Mime = Mime_1;
  5163. var lite = new Mime(standard);
  5164. const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g;
  5165. // urls in JS must be quoted as strings, so when replacing them we need
  5166. // a different regex
  5167. const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g;
  5168. const rawRE = /(\?|&)raw(?:&|$)/;
  5169. const urlRE = /(\?|&)url(?:&|$)/;
  5170. const chunkToEmittedAssetsMap = new WeakMap();
  5171. const assetCache = new WeakMap();
  5172. const assetHashToFilenameMap = new WeakMap();
  5173. // save hashes of the files that has been emitted in build watch
  5174. const emittedHashMap = new WeakMap();
  5175. /**
  5176. * Also supports loading plain strings with import text from './foo.txt?raw'
  5177. */
  5178. function assetPlugin(config) {
  5179. // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined
  5180. assetHashToFilenameMap.set(config, new Map());
  5181. return {
  5182. name: 'vite:asset',
  5183. buildStart() {
  5184. assetCache.set(config, new Map());
  5185. emittedHashMap.set(config, new Set());
  5186. },
  5187. resolveId(id) {
  5188. if (!config.assetsInclude(cleanUrl(id))) {
  5189. return;
  5190. }
  5191. // imports to absolute urls pointing to files in /public
  5192. // will fail to resolve in the main resolver. handle them here.
  5193. const publicFile = checkPublicFile(id, config);
  5194. if (publicFile) {
  5195. return id;
  5196. }
  5197. },
  5198. async load(id) {
  5199. if (id.startsWith('\0')) {
  5200. // Rollup convention, this id should be handled by the
  5201. // plugin that marked it with \0
  5202. return;
  5203. }
  5204. // raw requests, read from disk
  5205. if (rawRE.test(id)) {
  5206. const file = checkPublicFile(id, config) || cleanUrl(id);
  5207. // raw query, read file and return as string
  5208. return `export default ${JSON.stringify(await fs$v.promises.readFile(file, 'utf-8'))}`;
  5209. }
  5210. if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) {
  5211. return;
  5212. }
  5213. id = id.replace(urlRE, '$1').replace(/[\?&]$/, '');
  5214. const url = await fileToUrl(id, config, this);
  5215. return `export default ${JSON.stringify(url)}`;
  5216. },
  5217. renderChunk(code, chunk) {
  5218. let match;
  5219. let s;
  5220. while ((match = assetUrlQuotedRE.exec(code))) {
  5221. s = s || (s = new MagicString(code));
  5222. const [full, hash, postfix = ''] = match;
  5223. // some internal plugins may still need to emit chunks (e.g. worker) so
  5224. // fallback to this.getFileName for that.
  5225. const file = getAssetFilename(hash, config) || this.getFileName(hash);
  5226. registerAssetToChunk(chunk, file);
  5227. const outputFilepath = config.base + file + postfix;
  5228. s.overwrite(match.index, match.index + full.length, JSON.stringify(outputFilepath));
  5229. }
  5230. if (s) {
  5231. return {
  5232. code: s.toString(),
  5233. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
  5234. };
  5235. }
  5236. else {
  5237. return null;
  5238. }
  5239. },
  5240. generateBundle(_, bundle) {
  5241. // do not emit assets for SSR build
  5242. if (config.command === 'build' && config.build.ssr) {
  5243. for (const file in bundle) {
  5244. if (bundle[file].type === 'asset' &&
  5245. !file.includes('ssr-manifest.json')) {
  5246. delete bundle[file];
  5247. }
  5248. }
  5249. }
  5250. }
  5251. };
  5252. }
  5253. function registerAssetToChunk(chunk, file) {
  5254. let emitted = chunkToEmittedAssetsMap.get(chunk);
  5255. if (!emitted) {
  5256. emitted = new Set();
  5257. chunkToEmittedAssetsMap.set(chunk, emitted);
  5258. }
  5259. emitted.add(cleanUrl(file));
  5260. }
  5261. function checkPublicFile(url, { publicDir }) {
  5262. // note if the file is in /public, the resolver would have returned it
  5263. // as-is so it's not going to be a fully resolved path.
  5264. if (!publicDir || !url.startsWith('/')) {
  5265. return;
  5266. }
  5267. const publicFile = path__default.join(publicDir, cleanUrl(url));
  5268. if (fs__default.existsSync(publicFile)) {
  5269. return publicFile;
  5270. }
  5271. else {
  5272. return;
  5273. }
  5274. }
  5275. function fileToUrl(id, config, ctx) {
  5276. if (config.command === 'serve') {
  5277. return fileToDevUrl(id, config);
  5278. }
  5279. else {
  5280. return fileToBuiltUrl(id, config, ctx);
  5281. }
  5282. }
  5283. function fileToDevUrl(id, config) {
  5284. let rtn;
  5285. if (checkPublicFile(id, config)) {
  5286. // in public dir, keep the url as-is
  5287. rtn = id;
  5288. }
  5289. else if (id.startsWith(config.root)) {
  5290. // in project root, infer short public path
  5291. rtn = '/' + path__default.posix.relative(config.root, id);
  5292. }
  5293. else {
  5294. // outside of project root, use absolute fs path
  5295. // (this is special handled by the serve static middleware
  5296. rtn = path__default.posix.join(FS_PREFIX + id);
  5297. }
  5298. return config.base + rtn.replace(/^\//, '');
  5299. }
  5300. function getAssetFilename(hash, config) {
  5301. var _a;
  5302. return (_a = assetHashToFilenameMap.get(config)) === null || _a === void 0 ? void 0 : _a.get(hash);
  5303. }
  5304. /**
  5305. * converts the source filepath of the asset to the output filename based on the assetFileNames option. \
  5306. * this function imitates the behavior of rollup.js. \
  5307. * https://rollupjs.org/guide/en/#outputassetfilenames
  5308. *
  5309. * @example
  5310. * ```ts
  5311. * const content = Buffer.from('text');
  5312. * const fileName = assetFileNamesToFileName(
  5313. * 'assets/[name].[hash][extname]',
  5314. * '/path/to/file.txt',
  5315. * getAssetHash(content),
  5316. * content
  5317. * )
  5318. * // fileName: 'assets/file.982d9e3e.txt'
  5319. * ```
  5320. *
  5321. * @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
  5322. * @param file filepath of the asset
  5323. * @param contentHash hash of the asset. used for `'[hash]'` placeholder
  5324. * @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
  5325. * @returns output filename
  5326. */
  5327. function assetFileNamesToFileName(assetFileNames, file, contentHash, content) {
  5328. const basename = path__default.basename(file);
  5329. // placeholders for `assetFileNames`
  5330. // `hash` is slightly different from the rollup's one
  5331. const extname = path__default.extname(basename);
  5332. const ext = extname.substr(1);
  5333. const name = basename.slice(0, -extname.length);
  5334. const hash = contentHash;
  5335. if (typeof assetFileNames === 'function') {
  5336. assetFileNames = assetFileNames({
  5337. name: file,
  5338. source: content,
  5339. type: 'asset'
  5340. });
  5341. if (typeof assetFileNames !== 'string') {
  5342. throw new TypeError('assetFileNames must return a string');
  5343. }
  5344. }
  5345. else if (typeof assetFileNames !== 'string') {
  5346. throw new TypeError('assetFileNames must be a string or a function');
  5347. }
  5348. const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => {
  5349. switch (placeholder) {
  5350. case '[ext]':
  5351. return ext;
  5352. case '[extname]':
  5353. return extname;
  5354. case '[hash]':
  5355. return hash;
  5356. case '[name]':
  5357. return name;
  5358. }
  5359. throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`);
  5360. });
  5361. return fileName;
  5362. }
  5363. /**
  5364. * Register an asset to be emitted as part of the bundle (if necessary)
  5365. * and returns the resolved public URL
  5366. */
  5367. async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) {
  5368. var _a, _b, _c;
  5369. if (!skipPublicCheck && checkPublicFile(id, config)) {
  5370. return config.base + id.slice(1);
  5371. }
  5372. const cache = assetCache.get(config);
  5373. const cached = cache.get(id);
  5374. if (cached) {
  5375. return cached;
  5376. }
  5377. const file = cleanUrl(id);
  5378. const content = await fs$v.promises.readFile(file);
  5379. let url;
  5380. if (config.build.lib ||
  5381. (!file.endsWith('.svg') &&
  5382. content.length < Number(config.build.assetsInlineLimit))) {
  5383. // base64 inlined as a string
  5384. url = `data:${lite.getType(file)};base64,${content.toString('base64')}`;
  5385. }
  5386. else {
  5387. // emit as asset
  5388. // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code
  5389. // that uses runtime url sniffing and it can be verbose when targeting
  5390. // non-module format. It also fails to cascade the asset content change
  5391. // into the chunk's hash, so we have to do our own content hashing here.
  5392. // https://bundlers.tooling.report/hashing/asset-cascade/
  5393. // https://github.com/rollup/rollup/issues/3415
  5394. const map = assetHashToFilenameMap.get(config);
  5395. const contentHash = getAssetHash(content);
  5396. const { search, hash } = require$$0$a.parse(id);
  5397. const postfix = (search || '') + (hash || '');
  5398. const output = (_b = (_a = config.build) === null || _a === void 0 ? void 0 : _a.rollupOptions) === null || _b === void 0 ? void 0 : _b.output;
  5399. const assetFileNames = (_c = (output && !Array.isArray(output) ? output.assetFileNames : undefined)) !== null && _c !== void 0 ? _c :
  5400. // defaults to '<assetsDir>/[name].[hash][extname]'
  5401. // slightly different from rollup's one ('assets/[name]-[hash][extname]')
  5402. path__default.posix.join(config.build.assetsDir, '[name].[hash][extname]');
  5403. const fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content);
  5404. if (!map.has(contentHash)) {
  5405. map.set(contentHash, fileName);
  5406. }
  5407. const emittedSet = emittedHashMap.get(config);
  5408. if (!emittedSet.has(contentHash)) {
  5409. const name = normalizePath$4(path__default.relative(config.root, file));
  5410. pluginContext.emitFile({
  5411. name,
  5412. fileName,
  5413. type: 'asset',
  5414. source: content
  5415. });
  5416. emittedSet.add(contentHash);
  5417. }
  5418. url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`;
  5419. }
  5420. cache.set(id, url);
  5421. return url;
  5422. }
  5423. function getAssetHash(content) {
  5424. return require$$1$1.createHash('sha256').update(content).digest('hex').slice(0, 8);
  5425. }
  5426. async function urlToBuiltUrl(url, importer, config, pluginContext) {
  5427. if (checkPublicFile(url, config)) {
  5428. return config.base + url.slice(1);
  5429. }
  5430. const file = url.startsWith('/')
  5431. ? path__default.join(config.root, url)
  5432. : path__default.join(path__default.dirname(importer), url);
  5433. return fileToBuiltUrl(file, config, pluginContext,
  5434. // skip public check since we just did it above
  5435. true);
  5436. }
  5437. var tasks = {};
  5438. var utils$k = {};
  5439. var array$1 = {};
  5440. Object.defineProperty(array$1, "__esModule", { value: true });
  5441. array$1.splitWhen = array$1.flatten = void 0;
  5442. function flatten$1(items) {
  5443. return items.reduce((collection, item) => [].concat(collection, item), []);
  5444. }
  5445. array$1.flatten = flatten$1;
  5446. function splitWhen(items, predicate) {
  5447. const result = [[]];
  5448. let groupIndex = 0;
  5449. for (const item of items) {
  5450. if (predicate(item)) {
  5451. groupIndex++;
  5452. result[groupIndex] = [];
  5453. }
  5454. else {
  5455. result[groupIndex].push(item);
  5456. }
  5457. }
  5458. return result;
  5459. }
  5460. array$1.splitWhen = splitWhen;
  5461. var errno$1 = {};
  5462. Object.defineProperty(errno$1, "__esModule", { value: true });
  5463. errno$1.isEnoentCodeError = void 0;
  5464. function isEnoentCodeError(error) {
  5465. return error.code === 'ENOENT';
  5466. }
  5467. errno$1.isEnoentCodeError = isEnoentCodeError;
  5468. var fs$u = {};
  5469. Object.defineProperty(fs$u, "__esModule", { value: true });
  5470. fs$u.createDirentFromStats = void 0;
  5471. class DirentFromStats$1 {
  5472. constructor(name, stats) {
  5473. this.name = name;
  5474. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  5475. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  5476. this.isDirectory = stats.isDirectory.bind(stats);
  5477. this.isFIFO = stats.isFIFO.bind(stats);
  5478. this.isFile = stats.isFile.bind(stats);
  5479. this.isSocket = stats.isSocket.bind(stats);
  5480. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  5481. }
  5482. }
  5483. function createDirentFromStats$1(name, stats) {
  5484. return new DirentFromStats$1(name, stats);
  5485. }
  5486. fs$u.createDirentFromStats = createDirentFromStats$1;
  5487. var path$v = {};
  5488. Object.defineProperty(path$v, "__esModule", { value: true });
  5489. path$v.removeLeadingDotSegment = path$v.escape = path$v.makeAbsolute = path$v.unixify = void 0;
  5490. const path$u = path__default;
  5491. const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
  5492. const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
  5493. /**
  5494. * Designed to work only with simple paths: `dir\\file`.
  5495. */
  5496. function unixify(filepath) {
  5497. return filepath.replace(/\\/g, '/');
  5498. }
  5499. path$v.unixify = unixify;
  5500. function makeAbsolute(cwd, filepath) {
  5501. return path$u.resolve(cwd, filepath);
  5502. }
  5503. path$v.makeAbsolute = makeAbsolute;
  5504. function escape$1(pattern) {
  5505. return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
  5506. }
  5507. path$v.escape = escape$1;
  5508. function removeLeadingDotSegment(entry) {
  5509. // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
  5510. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  5511. if (entry.charAt(0) === '.') {
  5512. const secondCharactery = entry.charAt(1);
  5513. if (secondCharactery === '/' || secondCharactery === '\\') {
  5514. return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
  5515. }
  5516. }
  5517. return entry;
  5518. }
  5519. path$v.removeLeadingDotSegment = removeLeadingDotSegment;
  5520. var pattern$1 = {};
  5521. /*!
  5522. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  5523. *
  5524. * Copyright (c) 2014-2016, Jon Schlinkert.
  5525. * Licensed under the MIT License.
  5526. */
  5527. var isExtglob$1 = function isExtglob(str) {
  5528. if (typeof str !== 'string' || str === '') {
  5529. return false;
  5530. }
  5531. var match;
  5532. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  5533. if (match[2]) return true;
  5534. str = str.slice(match.index + match[0].length);
  5535. }
  5536. return false;
  5537. };
  5538. /*!
  5539. * is-glob <https://github.com/jonschlinkert/is-glob>
  5540. *
  5541. * Copyright (c) 2014-2017, Jon Schlinkert.
  5542. * Released under the MIT License.
  5543. */
  5544. var isExtglob = isExtglob$1;
  5545. var chars = { '{': '}', '(': ')', '[': ']'};
  5546. var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
  5547. var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
  5548. var isGlob$2 = function isGlob(str, options) {
  5549. if (typeof str !== 'string' || str === '') {
  5550. return false;
  5551. }
  5552. if (isExtglob(str)) {
  5553. return true;
  5554. }
  5555. var regex = strictRegex;
  5556. var match;
  5557. // optionally relax regex
  5558. if (options && options.strict === false) {
  5559. regex = relaxedRegex;
  5560. }
  5561. while ((match = regex.exec(str))) {
  5562. if (match[2]) return true;
  5563. var idx = match.index + match[0].length;
  5564. // if an open bracket/brace/paren is escaped,
  5565. // set the index to the next closing character
  5566. var open = match[1];
  5567. var close = open ? chars[open] : null;
  5568. if (open && close) {
  5569. var n = str.indexOf(close, idx);
  5570. if (n !== -1) {
  5571. idx = n + 1;
  5572. }
  5573. }
  5574. str = str.slice(idx);
  5575. }
  5576. return false;
  5577. };
  5578. var isGlob$1 = isGlob$2;
  5579. var pathPosixDirname = path__default.posix.dirname;
  5580. var isWin32 = require$$0__default$1.platform() === 'win32';
  5581. var slash$2 = '/';
  5582. var backslash = /\\/g;
  5583. var enclosure = /[\{\[].*[\}\]]$/;
  5584. var globby$2 = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  5585. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  5586. /**
  5587. * @param {string} str
  5588. * @param {Object} opts
  5589. * @param {boolean} [opts.flipBackslashes=true]
  5590. * @returns {string}
  5591. */
  5592. var globParent$2 = function globParent(str, opts) {
  5593. var options = Object.assign({ flipBackslashes: true }, opts);
  5594. // flip windows path separators
  5595. if (options.flipBackslashes && isWin32 && str.indexOf(slash$2) < 0) {
  5596. str = str.replace(backslash, slash$2);
  5597. }
  5598. // special case for strings ending in enclosure containing path separator
  5599. if (enclosure.test(str)) {
  5600. str += slash$2;
  5601. }
  5602. // preserves full path in case of trailing path separator
  5603. str += 'a';
  5604. // remove path parts that are globby
  5605. do {
  5606. str = pathPosixDirname(str);
  5607. } while (isGlob$1(str) || globby$2.test(str));
  5608. // remove escape chars and return result
  5609. return str.replace(escaped, '$1');
  5610. };
  5611. var utils$j = {};
  5612. (function (exports) {
  5613. exports.isInteger = num => {
  5614. if (typeof num === 'number') {
  5615. return Number.isInteger(num);
  5616. }
  5617. if (typeof num === 'string' && num.trim() !== '') {
  5618. return Number.isInteger(Number(num));
  5619. }
  5620. return false;
  5621. };
  5622. /**
  5623. * Find a node of the given type
  5624. */
  5625. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  5626. /**
  5627. * Find a node of the given type
  5628. */
  5629. exports.exceedsLimit = (min, max, step = 1, limit) => {
  5630. if (limit === false) return false;
  5631. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  5632. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  5633. };
  5634. /**
  5635. * Escape the given node with '\\' before node.value
  5636. */
  5637. exports.escapeNode = (block, n = 0, type) => {
  5638. let node = block.nodes[n];
  5639. if (!node) return;
  5640. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  5641. if (node.escaped !== true) {
  5642. node.value = '\\' + node.value;
  5643. node.escaped = true;
  5644. }
  5645. }
  5646. };
  5647. /**
  5648. * Returns true if the given brace node should be enclosed in literal braces
  5649. */
  5650. exports.encloseBrace = node => {
  5651. if (node.type !== 'brace') return false;
  5652. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  5653. node.invalid = true;
  5654. return true;
  5655. }
  5656. return false;
  5657. };
  5658. /**
  5659. * Returns true if a brace node is invalid.
  5660. */
  5661. exports.isInvalidBrace = block => {
  5662. if (block.type !== 'brace') return false;
  5663. if (block.invalid === true || block.dollar) return true;
  5664. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  5665. block.invalid = true;
  5666. return true;
  5667. }
  5668. if (block.open !== true || block.close !== true) {
  5669. block.invalid = true;
  5670. return true;
  5671. }
  5672. return false;
  5673. };
  5674. /**
  5675. * Returns true if a node is an open or close node
  5676. */
  5677. exports.isOpenOrClose = node => {
  5678. if (node.type === 'open' || node.type === 'close') {
  5679. return true;
  5680. }
  5681. return node.open === true || node.close === true;
  5682. };
  5683. /**
  5684. * Reduce an array of text nodes.
  5685. */
  5686. exports.reduce = nodes => nodes.reduce((acc, node) => {
  5687. if (node.type === 'text') acc.push(node.value);
  5688. if (node.type === 'range') node.type = 'text';
  5689. return acc;
  5690. }, []);
  5691. /**
  5692. * Flatten an array
  5693. */
  5694. exports.flatten = (...args) => {
  5695. const result = [];
  5696. const flat = arr => {
  5697. for (let i = 0; i < arr.length; i++) {
  5698. let ele = arr[i];
  5699. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  5700. }
  5701. return result;
  5702. };
  5703. flat(args);
  5704. return result;
  5705. };
  5706. }(utils$j));
  5707. const utils$i = utils$j;
  5708. var stringify$7 = (ast, options = {}) => {
  5709. let stringify = (node, parent = {}) => {
  5710. let invalidBlock = options.escapeInvalid && utils$i.isInvalidBrace(parent);
  5711. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  5712. let output = '';
  5713. if (node.value) {
  5714. if ((invalidBlock || invalidNode) && utils$i.isOpenOrClose(node)) {
  5715. return '\\' + node.value;
  5716. }
  5717. return node.value;
  5718. }
  5719. if (node.value) {
  5720. return node.value;
  5721. }
  5722. if (node.nodes) {
  5723. for (let child of node.nodes) {
  5724. output += stringify(child);
  5725. }
  5726. }
  5727. return output;
  5728. };
  5729. return stringify(ast);
  5730. };
  5731. /*!
  5732. * is-number <https://github.com/jonschlinkert/is-number>
  5733. *
  5734. * Copyright (c) 2014-present, Jon Schlinkert.
  5735. * Released under the MIT License.
  5736. */
  5737. var isNumber$2 = function(num) {
  5738. if (typeof num === 'number') {
  5739. return num - num === 0;
  5740. }
  5741. if (typeof num === 'string' && num.trim() !== '') {
  5742. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  5743. }
  5744. return false;
  5745. };
  5746. /*!
  5747. * to-regex-range <https://github.com/micromatch/to-regex-range>
  5748. *
  5749. * Copyright (c) 2015-present, Jon Schlinkert.
  5750. * Released under the MIT License.
  5751. */
  5752. const isNumber$1 = isNumber$2;
  5753. const toRegexRange$1 = (min, max, options) => {
  5754. if (isNumber$1(min) === false) {
  5755. throw new TypeError('toRegexRange: expected the first argument to be a number');
  5756. }
  5757. if (max === void 0 || min === max) {
  5758. return String(min);
  5759. }
  5760. if (isNumber$1(max) === false) {
  5761. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  5762. }
  5763. let opts = { relaxZeros: true, ...options };
  5764. if (typeof opts.strictZeros === 'boolean') {
  5765. opts.relaxZeros = opts.strictZeros === false;
  5766. }
  5767. let relax = String(opts.relaxZeros);
  5768. let shorthand = String(opts.shorthand);
  5769. let capture = String(opts.capture);
  5770. let wrap = String(opts.wrap);
  5771. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  5772. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  5773. return toRegexRange$1.cache[cacheKey].result;
  5774. }
  5775. let a = Math.min(min, max);
  5776. let b = Math.max(min, max);
  5777. if (Math.abs(a - b) === 1) {
  5778. let result = min + '|' + max;
  5779. if (opts.capture) {
  5780. return `(${result})`;
  5781. }
  5782. if (opts.wrap === false) {
  5783. return result;
  5784. }
  5785. return `(?:${result})`;
  5786. }
  5787. let isPadded = hasPadding(min) || hasPadding(max);
  5788. let state = { min, max, a, b };
  5789. let positives = [];
  5790. let negatives = [];
  5791. if (isPadded) {
  5792. state.isPadded = isPadded;
  5793. state.maxLen = String(state.max).length;
  5794. }
  5795. if (a < 0) {
  5796. let newMin = b < 0 ? Math.abs(b) : 1;
  5797. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  5798. a = state.a = 0;
  5799. }
  5800. if (b >= 0) {
  5801. positives = splitToPatterns(a, b, state, opts);
  5802. }
  5803. state.negatives = negatives;
  5804. state.positives = positives;
  5805. state.result = collatePatterns(negatives, positives);
  5806. if (opts.capture === true) {
  5807. state.result = `(${state.result})`;
  5808. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  5809. state.result = `(?:${state.result})`;
  5810. }
  5811. toRegexRange$1.cache[cacheKey] = state;
  5812. return state.result;
  5813. };
  5814. function collatePatterns(neg, pos, options) {
  5815. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  5816. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  5817. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  5818. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  5819. return subpatterns.join('|');
  5820. }
  5821. function splitToRanges(min, max) {
  5822. let nines = 1;
  5823. let zeros = 1;
  5824. let stop = countNines(min, nines);
  5825. let stops = new Set([max]);
  5826. while (min <= stop && stop <= max) {
  5827. stops.add(stop);
  5828. nines += 1;
  5829. stop = countNines(min, nines);
  5830. }
  5831. stop = countZeros(max + 1, zeros) - 1;
  5832. while (min < stop && stop <= max) {
  5833. stops.add(stop);
  5834. zeros += 1;
  5835. stop = countZeros(max + 1, zeros) - 1;
  5836. }
  5837. stops = [...stops];
  5838. stops.sort(compare);
  5839. return stops;
  5840. }
  5841. /**
  5842. * Convert a range to a regex pattern
  5843. * @param {Number} `start`
  5844. * @param {Number} `stop`
  5845. * @return {String}
  5846. */
  5847. function rangeToPattern(start, stop, options) {
  5848. if (start === stop) {
  5849. return { pattern: start, count: [], digits: 0 };
  5850. }
  5851. let zipped = zip(start, stop);
  5852. let digits = zipped.length;
  5853. let pattern = '';
  5854. let count = 0;
  5855. for (let i = 0; i < digits; i++) {
  5856. let [startDigit, stopDigit] = zipped[i];
  5857. if (startDigit === stopDigit) {
  5858. pattern += startDigit;
  5859. } else if (startDigit !== '0' || stopDigit !== '9') {
  5860. pattern += toCharacterClass(startDigit, stopDigit);
  5861. } else {
  5862. count++;
  5863. }
  5864. }
  5865. if (count) {
  5866. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  5867. }
  5868. return { pattern, count: [count], digits };
  5869. }
  5870. function splitToPatterns(min, max, tok, options) {
  5871. let ranges = splitToRanges(min, max);
  5872. let tokens = [];
  5873. let start = min;
  5874. let prev;
  5875. for (let i = 0; i < ranges.length; i++) {
  5876. let max = ranges[i];
  5877. let obj = rangeToPattern(String(start), String(max), options);
  5878. let zeros = '';
  5879. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  5880. if (prev.count.length > 1) {
  5881. prev.count.pop();
  5882. }
  5883. prev.count.push(obj.count[0]);
  5884. prev.string = prev.pattern + toQuantifier(prev.count);
  5885. start = max + 1;
  5886. continue;
  5887. }
  5888. if (tok.isPadded) {
  5889. zeros = padZeros(max, tok, options);
  5890. }
  5891. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  5892. tokens.push(obj);
  5893. start = max + 1;
  5894. prev = obj;
  5895. }
  5896. return tokens;
  5897. }
  5898. function filterPatterns(arr, comparison, prefix, intersection, options) {
  5899. let result = [];
  5900. for (let ele of arr) {
  5901. let { string } = ele;
  5902. // only push if _both_ are negative...
  5903. if (!intersection && !contains(comparison, 'string', string)) {
  5904. result.push(prefix + string);
  5905. }
  5906. // or _both_ are positive
  5907. if (intersection && contains(comparison, 'string', string)) {
  5908. result.push(prefix + string);
  5909. }
  5910. }
  5911. return result;
  5912. }
  5913. /**
  5914. * Zip strings
  5915. */
  5916. function zip(a, b) {
  5917. let arr = [];
  5918. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  5919. return arr;
  5920. }
  5921. function compare(a, b) {
  5922. return a > b ? 1 : b > a ? -1 : 0;
  5923. }
  5924. function contains(arr, key, val) {
  5925. return arr.some(ele => ele[key] === val);
  5926. }
  5927. function countNines(min, len) {
  5928. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  5929. }
  5930. function countZeros(integer, zeros) {
  5931. return integer - (integer % Math.pow(10, zeros));
  5932. }
  5933. function toQuantifier(digits) {
  5934. let [start = 0, stop = ''] = digits;
  5935. if (stop || start > 1) {
  5936. return `{${start + (stop ? ',' + stop : '')}}`;
  5937. }
  5938. return '';
  5939. }
  5940. function toCharacterClass(a, b, options) {
  5941. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  5942. }
  5943. function hasPadding(str) {
  5944. return /^-?(0+)\d/.test(str);
  5945. }
  5946. function padZeros(value, tok, options) {
  5947. if (!tok.isPadded) {
  5948. return value;
  5949. }
  5950. let diff = Math.abs(tok.maxLen - String(value).length);
  5951. let relax = options.relaxZeros !== false;
  5952. switch (diff) {
  5953. case 0:
  5954. return '';
  5955. case 1:
  5956. return relax ? '0?' : '0';
  5957. case 2:
  5958. return relax ? '0{0,2}' : '00';
  5959. default: {
  5960. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  5961. }
  5962. }
  5963. }
  5964. /**
  5965. * Cache
  5966. */
  5967. toRegexRange$1.cache = {};
  5968. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  5969. /**
  5970. * Expose `toRegexRange`
  5971. */
  5972. var toRegexRange_1 = toRegexRange$1;
  5973. /*!
  5974. * fill-range <https://github.com/jonschlinkert/fill-range>
  5975. *
  5976. * Copyright (c) 2014-present, Jon Schlinkert.
  5977. * Licensed under the MIT License.
  5978. */
  5979. const util$b = require$$0__default$3;
  5980. const toRegexRange = toRegexRange_1;
  5981. const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  5982. const transform = toNumber => {
  5983. return value => toNumber === true ? Number(value) : String(value);
  5984. };
  5985. const isValidValue = value => {
  5986. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  5987. };
  5988. const isNumber = num => Number.isInteger(+num);
  5989. const zeros = input => {
  5990. let value = `${input}`;
  5991. let index = -1;
  5992. if (value[0] === '-') value = value.slice(1);
  5993. if (value === '0') return false;
  5994. while (value[++index] === '0');
  5995. return index > 0;
  5996. };
  5997. const stringify$6 = (start, end, options) => {
  5998. if (typeof start === 'string' || typeof end === 'string') {
  5999. return true;
  6000. }
  6001. return options.stringify === true;
  6002. };
  6003. const pad = (input, maxLength, toNumber) => {
  6004. if (maxLength > 0) {
  6005. let dash = input[0] === '-' ? '-' : '';
  6006. if (dash) input = input.slice(1);
  6007. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  6008. }
  6009. if (toNumber === false) {
  6010. return String(input);
  6011. }
  6012. return input;
  6013. };
  6014. const toMaxLen = (input, maxLength) => {
  6015. let negative = input[0] === '-' ? '-' : '';
  6016. if (negative) {
  6017. input = input.slice(1);
  6018. maxLength--;
  6019. }
  6020. while (input.length < maxLength) input = '0' + input;
  6021. return negative ? ('-' + input) : input;
  6022. };
  6023. const toSequence = (parts, options) => {
  6024. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  6025. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  6026. let prefix = options.capture ? '' : '?:';
  6027. let positives = '';
  6028. let negatives = '';
  6029. let result;
  6030. if (parts.positives.length) {
  6031. positives = parts.positives.join('|');
  6032. }
  6033. if (parts.negatives.length) {
  6034. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  6035. }
  6036. if (positives && negatives) {
  6037. result = `${positives}|${negatives}`;
  6038. } else {
  6039. result = positives || negatives;
  6040. }
  6041. if (options.wrap) {
  6042. return `(${prefix}${result})`;
  6043. }
  6044. return result;
  6045. };
  6046. const toRange = (a, b, isNumbers, options) => {
  6047. if (isNumbers) {
  6048. return toRegexRange(a, b, { wrap: false, ...options });
  6049. }
  6050. let start = String.fromCharCode(a);
  6051. if (a === b) return start;
  6052. let stop = String.fromCharCode(b);
  6053. return `[${start}-${stop}]`;
  6054. };
  6055. const toRegex = (start, end, options) => {
  6056. if (Array.isArray(start)) {
  6057. let wrap = options.wrap === true;
  6058. let prefix = options.capture ? '' : '?:';
  6059. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  6060. }
  6061. return toRegexRange(start, end, options);
  6062. };
  6063. const rangeError = (...args) => {
  6064. return new RangeError('Invalid range arguments: ' + util$b.inspect(...args));
  6065. };
  6066. const invalidRange = (start, end, options) => {
  6067. if (options.strictRanges === true) throw rangeError([start, end]);
  6068. return [];
  6069. };
  6070. const invalidStep = (step, options) => {
  6071. if (options.strictRanges === true) {
  6072. throw new TypeError(`Expected step "${step}" to be a number`);
  6073. }
  6074. return [];
  6075. };
  6076. const fillNumbers = (start, end, step = 1, options = {}) => {
  6077. let a = Number(start);
  6078. let b = Number(end);
  6079. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  6080. if (options.strictRanges === true) throw rangeError([start, end]);
  6081. return [];
  6082. }
  6083. // fix negative zero
  6084. if (a === 0) a = 0;
  6085. if (b === 0) b = 0;
  6086. let descending = a > b;
  6087. let startString = String(start);
  6088. let endString = String(end);
  6089. let stepString = String(step);
  6090. step = Math.max(Math.abs(step), 1);
  6091. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  6092. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  6093. let toNumber = padded === false && stringify$6(start, end, options) === false;
  6094. let format = options.transform || transform(toNumber);
  6095. if (options.toRegex && step === 1) {
  6096. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  6097. }
  6098. let parts = { negatives: [], positives: [] };
  6099. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  6100. let range = [];
  6101. let index = 0;
  6102. while (descending ? a >= b : a <= b) {
  6103. if (options.toRegex === true && step > 1) {
  6104. push(a);
  6105. } else {
  6106. range.push(pad(format(a, index), maxLen, toNumber));
  6107. }
  6108. a = descending ? a - step : a + step;
  6109. index++;
  6110. }
  6111. if (options.toRegex === true) {
  6112. return step > 1
  6113. ? toSequence(parts, options)
  6114. : toRegex(range, null, { wrap: false, ...options });
  6115. }
  6116. return range;
  6117. };
  6118. const fillLetters = (start, end, step = 1, options = {}) => {
  6119. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  6120. return invalidRange(start, end, options);
  6121. }
  6122. let format = options.transform || (val => String.fromCharCode(val));
  6123. let a = `${start}`.charCodeAt(0);
  6124. let b = `${end}`.charCodeAt(0);
  6125. let descending = a > b;
  6126. let min = Math.min(a, b);
  6127. let max = Math.max(a, b);
  6128. if (options.toRegex && step === 1) {
  6129. return toRange(min, max, false, options);
  6130. }
  6131. let range = [];
  6132. let index = 0;
  6133. while (descending ? a >= b : a <= b) {
  6134. range.push(format(a, index));
  6135. a = descending ? a - step : a + step;
  6136. index++;
  6137. }
  6138. if (options.toRegex === true) {
  6139. return toRegex(range, null, { wrap: false, options });
  6140. }
  6141. return range;
  6142. };
  6143. const fill$2 = (start, end, step, options = {}) => {
  6144. if (end == null && isValidValue(start)) {
  6145. return [start];
  6146. }
  6147. if (!isValidValue(start) || !isValidValue(end)) {
  6148. return invalidRange(start, end, options);
  6149. }
  6150. if (typeof step === 'function') {
  6151. return fill$2(start, end, 1, { transform: step });
  6152. }
  6153. if (isObject$1(step)) {
  6154. return fill$2(start, end, 0, step);
  6155. }
  6156. let opts = { ...options };
  6157. if (opts.capture === true) opts.wrap = true;
  6158. step = step || opts.step || 1;
  6159. if (!isNumber(step)) {
  6160. if (step != null && !isObject$1(step)) return invalidStep(step, opts);
  6161. return fill$2(start, end, 1, step);
  6162. }
  6163. if (isNumber(start) && isNumber(end)) {
  6164. return fillNumbers(start, end, step, opts);
  6165. }
  6166. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  6167. };
  6168. var fillRange = fill$2;
  6169. const fill$1 = fillRange;
  6170. const utils$h = utils$j;
  6171. const compile$1 = (ast, options = {}) => {
  6172. let walk = (node, parent = {}) => {
  6173. let invalidBlock = utils$h.isInvalidBrace(parent);
  6174. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  6175. let invalid = invalidBlock === true || invalidNode === true;
  6176. let prefix = options.escapeInvalid === true ? '\\' : '';
  6177. let output = '';
  6178. if (node.isOpen === true) {
  6179. return prefix + node.value;
  6180. }
  6181. if (node.isClose === true) {
  6182. return prefix + node.value;
  6183. }
  6184. if (node.type === 'open') {
  6185. return invalid ? (prefix + node.value) : '(';
  6186. }
  6187. if (node.type === 'close') {
  6188. return invalid ? (prefix + node.value) : ')';
  6189. }
  6190. if (node.type === 'comma') {
  6191. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  6192. }
  6193. if (node.value) {
  6194. return node.value;
  6195. }
  6196. if (node.nodes && node.ranges > 0) {
  6197. let args = utils$h.reduce(node.nodes);
  6198. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  6199. if (range.length !== 0) {
  6200. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  6201. }
  6202. }
  6203. if (node.nodes) {
  6204. for (let child of node.nodes) {
  6205. output += walk(child, node);
  6206. }
  6207. }
  6208. return output;
  6209. };
  6210. return walk(ast);
  6211. };
  6212. var compile_1 = compile$1;
  6213. const fill = fillRange;
  6214. const stringify$5 = stringify$7;
  6215. const utils$g = utils$j;
  6216. const append$1 = (queue = '', stash = '', enclose = false) => {
  6217. let result = [];
  6218. queue = [].concat(queue);
  6219. stash = [].concat(stash);
  6220. if (!stash.length) return queue;
  6221. if (!queue.length) {
  6222. return enclose ? utils$g.flatten(stash).map(ele => `{${ele}}`) : stash;
  6223. }
  6224. for (let item of queue) {
  6225. if (Array.isArray(item)) {
  6226. for (let value of item) {
  6227. result.push(append$1(value, stash, enclose));
  6228. }
  6229. } else {
  6230. for (let ele of stash) {
  6231. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  6232. result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele));
  6233. }
  6234. }
  6235. }
  6236. return utils$g.flatten(result);
  6237. };
  6238. const expand$3 = (ast, options = {}) => {
  6239. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  6240. let walk = (node, parent = {}) => {
  6241. node.queue = [];
  6242. let p = parent;
  6243. let q = parent.queue;
  6244. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  6245. p = p.parent;
  6246. q = p.queue;
  6247. }
  6248. if (node.invalid || node.dollar) {
  6249. q.push(append$1(q.pop(), stringify$5(node, options)));
  6250. return;
  6251. }
  6252. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  6253. q.push(append$1(q.pop(), ['{}']));
  6254. return;
  6255. }
  6256. if (node.nodes && node.ranges > 0) {
  6257. let args = utils$g.reduce(node.nodes);
  6258. if (utils$g.exceedsLimit(...args, options.step, rangeLimit)) {
  6259. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  6260. }
  6261. let range = fill(...args, options);
  6262. if (range.length === 0) {
  6263. range = stringify$5(node, options);
  6264. }
  6265. q.push(append$1(q.pop(), range));
  6266. node.nodes = [];
  6267. return;
  6268. }
  6269. let enclose = utils$g.encloseBrace(node);
  6270. let queue = node.queue;
  6271. let block = node;
  6272. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  6273. block = block.parent;
  6274. queue = block.queue;
  6275. }
  6276. for (let i = 0; i < node.nodes.length; i++) {
  6277. let child = node.nodes[i];
  6278. if (child.type === 'comma' && node.type === 'brace') {
  6279. if (i === 1) queue.push('');
  6280. queue.push('');
  6281. continue;
  6282. }
  6283. if (child.type === 'close') {
  6284. q.push(append$1(q.pop(), queue, enclose));
  6285. continue;
  6286. }
  6287. if (child.value && child.type !== 'open') {
  6288. queue.push(append$1(queue.pop(), child.value));
  6289. continue;
  6290. }
  6291. if (child.nodes) {
  6292. walk(child, node);
  6293. }
  6294. }
  6295. return queue;
  6296. };
  6297. return utils$g.flatten(walk(ast));
  6298. };
  6299. var expand_1 = expand$3;
  6300. var constants$6 = {
  6301. MAX_LENGTH: 1024 * 64,
  6302. // Digits
  6303. CHAR_0: '0', /* 0 */
  6304. CHAR_9: '9', /* 9 */
  6305. // Alphabet chars.
  6306. CHAR_UPPERCASE_A: 'A', /* A */
  6307. CHAR_LOWERCASE_A: 'a', /* a */
  6308. CHAR_UPPERCASE_Z: 'Z', /* Z */
  6309. CHAR_LOWERCASE_Z: 'z', /* z */
  6310. CHAR_LEFT_PARENTHESES: '(', /* ( */
  6311. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  6312. CHAR_ASTERISK: '*', /* * */
  6313. // Non-alphabetic chars.
  6314. CHAR_AMPERSAND: '&', /* & */
  6315. CHAR_AT: '@', /* @ */
  6316. CHAR_BACKSLASH: '\\', /* \ */
  6317. CHAR_BACKTICK: '`', /* ` */
  6318. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  6319. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  6320. CHAR_COLON: ':', /* : */
  6321. CHAR_COMMA: ',', /* , */
  6322. CHAR_DOLLAR: '$', /* . */
  6323. CHAR_DOT: '.', /* . */
  6324. CHAR_DOUBLE_QUOTE: '"', /* " */
  6325. CHAR_EQUAL: '=', /* = */
  6326. CHAR_EXCLAMATION_MARK: '!', /* ! */
  6327. CHAR_FORM_FEED: '\f', /* \f */
  6328. CHAR_FORWARD_SLASH: '/', /* / */
  6329. CHAR_HASH: '#', /* # */
  6330. CHAR_HYPHEN_MINUS: '-', /* - */
  6331. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  6332. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  6333. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  6334. CHAR_LINE_FEED: '\n', /* \n */
  6335. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  6336. CHAR_PERCENT: '%', /* % */
  6337. CHAR_PLUS: '+', /* + */
  6338. CHAR_QUESTION_MARK: '?', /* ? */
  6339. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  6340. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  6341. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  6342. CHAR_SEMICOLON: ';', /* ; */
  6343. CHAR_SINGLE_QUOTE: '\'', /* ' */
  6344. CHAR_SPACE: ' ', /* */
  6345. CHAR_TAB: '\t', /* \t */
  6346. CHAR_UNDERSCORE: '_', /* _ */
  6347. CHAR_VERTICAL_LINE: '|', /* | */
  6348. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  6349. };
  6350. const stringify$4 = stringify$7;
  6351. /**
  6352. * Constants
  6353. */
  6354. const {
  6355. MAX_LENGTH: MAX_LENGTH$1,
  6356. CHAR_BACKSLASH, /* \ */
  6357. CHAR_BACKTICK, /* ` */
  6358. CHAR_COMMA: CHAR_COMMA$1, /* , */
  6359. CHAR_DOT: CHAR_DOT$1, /* . */
  6360. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */
  6361. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */
  6362. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */
  6363. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */
  6364. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
  6365. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */
  6366. CHAR_DOUBLE_QUOTE, /* " */
  6367. CHAR_SINGLE_QUOTE, /* ' */
  6368. CHAR_NO_BREAK_SPACE,
  6369. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  6370. } = constants$6;
  6371. /**
  6372. * parse
  6373. */
  6374. const parse$k = (input, options = {}) => {
  6375. if (typeof input !== 'string') {
  6376. throw new TypeError('Expected a string');
  6377. }
  6378. let opts = options || {};
  6379. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  6380. if (input.length > max) {
  6381. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  6382. }
  6383. let ast = { type: 'root', input, nodes: [] };
  6384. let stack = [ast];
  6385. let block = ast;
  6386. let prev = ast;
  6387. let brackets = 0;
  6388. let length = input.length;
  6389. let index = 0;
  6390. let depth = 0;
  6391. let value;
  6392. /**
  6393. * Helpers
  6394. */
  6395. const advance = () => input[index++];
  6396. const push = node => {
  6397. if (node.type === 'text' && prev.type === 'dot') {
  6398. prev.type = 'text';
  6399. }
  6400. if (prev && prev.type === 'text' && node.type === 'text') {
  6401. prev.value += node.value;
  6402. return;
  6403. }
  6404. block.nodes.push(node);
  6405. node.parent = block;
  6406. node.prev = prev;
  6407. prev = node;
  6408. return node;
  6409. };
  6410. push({ type: 'bos' });
  6411. while (index < length) {
  6412. block = stack[stack.length - 1];
  6413. value = advance();
  6414. /**
  6415. * Invalid chars
  6416. */
  6417. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  6418. continue;
  6419. }
  6420. /**
  6421. * Escaped chars
  6422. */
  6423. if (value === CHAR_BACKSLASH) {
  6424. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  6425. continue;
  6426. }
  6427. /**
  6428. * Right square bracket (literal): ']'
  6429. */
  6430. if (value === CHAR_RIGHT_SQUARE_BRACKET$1) {
  6431. push({ type: 'text', value: '\\' + value });
  6432. continue;
  6433. }
  6434. /**
  6435. * Left square bracket: '['
  6436. */
  6437. if (value === CHAR_LEFT_SQUARE_BRACKET$1) {
  6438. brackets++;
  6439. let next;
  6440. while (index < length && (next = advance())) {
  6441. value += next;
  6442. if (next === CHAR_LEFT_SQUARE_BRACKET$1) {
  6443. brackets++;
  6444. continue;
  6445. }
  6446. if (next === CHAR_BACKSLASH) {
  6447. value += advance();
  6448. continue;
  6449. }
  6450. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  6451. brackets--;
  6452. if (brackets === 0) {
  6453. break;
  6454. }
  6455. }
  6456. }
  6457. push({ type: 'text', value });
  6458. continue;
  6459. }
  6460. /**
  6461. * Parentheses
  6462. */
  6463. if (value === CHAR_LEFT_PARENTHESES$1) {
  6464. block = push({ type: 'paren', nodes: [] });
  6465. stack.push(block);
  6466. push({ type: 'text', value });
  6467. continue;
  6468. }
  6469. if (value === CHAR_RIGHT_PARENTHESES$1) {
  6470. if (block.type !== 'paren') {
  6471. push({ type: 'text', value });
  6472. continue;
  6473. }
  6474. block = stack.pop();
  6475. push({ type: 'text', value });
  6476. block = stack[stack.length - 1];
  6477. continue;
  6478. }
  6479. /**
  6480. * Quotes: '|"|`
  6481. */
  6482. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  6483. let open = value;
  6484. let next;
  6485. if (options.keepQuotes !== true) {
  6486. value = '';
  6487. }
  6488. while (index < length && (next = advance())) {
  6489. if (next === CHAR_BACKSLASH) {
  6490. value += next + advance();
  6491. continue;
  6492. }
  6493. if (next === open) {
  6494. if (options.keepQuotes === true) value += next;
  6495. break;
  6496. }
  6497. value += next;
  6498. }
  6499. push({ type: 'text', value });
  6500. continue;
  6501. }
  6502. /**
  6503. * Left curly brace: '{'
  6504. */
  6505. if (value === CHAR_LEFT_CURLY_BRACE$1) {
  6506. depth++;
  6507. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  6508. let brace = {
  6509. type: 'brace',
  6510. open: true,
  6511. close: false,
  6512. dollar,
  6513. depth,
  6514. commas: 0,
  6515. ranges: 0,
  6516. nodes: []
  6517. };
  6518. block = push(brace);
  6519. stack.push(block);
  6520. push({ type: 'open', value });
  6521. continue;
  6522. }
  6523. /**
  6524. * Right curly brace: '}'
  6525. */
  6526. if (value === CHAR_RIGHT_CURLY_BRACE$1) {
  6527. if (block.type !== 'brace') {
  6528. push({ type: 'text', value });
  6529. continue;
  6530. }
  6531. let type = 'close';
  6532. block = stack.pop();
  6533. block.close = true;
  6534. push({ type, value });
  6535. depth--;
  6536. block = stack[stack.length - 1];
  6537. continue;
  6538. }
  6539. /**
  6540. * Comma: ','
  6541. */
  6542. if (value === CHAR_COMMA$1 && depth > 0) {
  6543. if (block.ranges > 0) {
  6544. block.ranges = 0;
  6545. let open = block.nodes.shift();
  6546. block.nodes = [open, { type: 'text', value: stringify$4(block) }];
  6547. }
  6548. push({ type: 'comma', value });
  6549. block.commas++;
  6550. continue;
  6551. }
  6552. /**
  6553. * Dot: '.'
  6554. */
  6555. if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) {
  6556. let siblings = block.nodes;
  6557. if (depth === 0 || siblings.length === 0) {
  6558. push({ type: 'text', value });
  6559. continue;
  6560. }
  6561. if (prev.type === 'dot') {
  6562. block.range = [];
  6563. prev.value += value;
  6564. prev.type = 'range';
  6565. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  6566. block.invalid = true;
  6567. block.ranges = 0;
  6568. prev.type = 'text';
  6569. continue;
  6570. }
  6571. block.ranges++;
  6572. block.args = [];
  6573. continue;
  6574. }
  6575. if (prev.type === 'range') {
  6576. siblings.pop();
  6577. let before = siblings[siblings.length - 1];
  6578. before.value += prev.value + value;
  6579. prev = before;
  6580. block.ranges--;
  6581. continue;
  6582. }
  6583. push({ type: 'dot', value });
  6584. continue;
  6585. }
  6586. /**
  6587. * Text
  6588. */
  6589. push({ type: 'text', value });
  6590. }
  6591. // Mark imbalanced braces and brackets as invalid
  6592. do {
  6593. block = stack.pop();
  6594. if (block.type !== 'root') {
  6595. block.nodes.forEach(node => {
  6596. if (!node.nodes) {
  6597. if (node.type === 'open') node.isOpen = true;
  6598. if (node.type === 'close') node.isClose = true;
  6599. if (!node.nodes) node.type = 'text';
  6600. node.invalid = true;
  6601. }
  6602. });
  6603. // get the location of the block on parent.nodes (block's siblings)
  6604. let parent = stack[stack.length - 1];
  6605. let index = parent.nodes.indexOf(block);
  6606. // replace the (invalid) block with it's nodes
  6607. parent.nodes.splice(index, 1, ...block.nodes);
  6608. }
  6609. } while (stack.length > 0);
  6610. push({ type: 'eos' });
  6611. return ast;
  6612. };
  6613. var parse_1$2 = parse$k;
  6614. const stringify$3 = stringify$7;
  6615. const compile = compile_1;
  6616. const expand$2 = expand_1;
  6617. const parse$j = parse_1$2;
  6618. /**
  6619. * Expand the given pattern or create a regex-compatible string.
  6620. *
  6621. * ```js
  6622. * const braces = require('braces');
  6623. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  6624. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  6625. * ```
  6626. * @param {String} `str`
  6627. * @param {Object} `options`
  6628. * @return {String}
  6629. * @api public
  6630. */
  6631. const braces$2 = (input, options = {}) => {
  6632. let output = [];
  6633. if (Array.isArray(input)) {
  6634. for (let pattern of input) {
  6635. let result = braces$2.create(pattern, options);
  6636. if (Array.isArray(result)) {
  6637. output.push(...result);
  6638. } else {
  6639. output.push(result);
  6640. }
  6641. }
  6642. } else {
  6643. output = [].concat(braces$2.create(input, options));
  6644. }
  6645. if (options && options.expand === true && options.nodupes === true) {
  6646. output = [...new Set(output)];
  6647. }
  6648. return output;
  6649. };
  6650. /**
  6651. * Parse the given `str` with the given `options`.
  6652. *
  6653. * ```js
  6654. * // braces.parse(pattern, [, options]);
  6655. * const ast = braces.parse('a/{b,c}/d');
  6656. * console.log(ast);
  6657. * ```
  6658. * @param {String} pattern Brace pattern to parse
  6659. * @param {Object} options
  6660. * @return {Object} Returns an AST
  6661. * @api public
  6662. */
  6663. braces$2.parse = (input, options = {}) => parse$j(input, options);
  6664. /**
  6665. * Creates a braces string from an AST, or an AST node.
  6666. *
  6667. * ```js
  6668. * const braces = require('braces');
  6669. * let ast = braces.parse('foo/{a,b}/bar');
  6670. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  6671. * ```
  6672. * @param {String} `input` Brace pattern or AST.
  6673. * @param {Object} `options`
  6674. * @return {Array} Returns an array of expanded values.
  6675. * @api public
  6676. */
  6677. braces$2.stringify = (input, options = {}) => {
  6678. if (typeof input === 'string') {
  6679. return stringify$3(braces$2.parse(input, options), options);
  6680. }
  6681. return stringify$3(input, options);
  6682. };
  6683. /**
  6684. * Compiles a brace pattern into a regex-compatible, optimized string.
  6685. * This method is called by the main [braces](#braces) function by default.
  6686. *
  6687. * ```js
  6688. * const braces = require('braces');
  6689. * console.log(braces.compile('a/{b,c}/d'));
  6690. * //=> ['a/(b|c)/d']
  6691. * ```
  6692. * @param {String} `input` Brace pattern or AST.
  6693. * @param {Object} `options`
  6694. * @return {Array} Returns an array of expanded values.
  6695. * @api public
  6696. */
  6697. braces$2.compile = (input, options = {}) => {
  6698. if (typeof input === 'string') {
  6699. input = braces$2.parse(input, options);
  6700. }
  6701. return compile(input, options);
  6702. };
  6703. /**
  6704. * Expands a brace pattern into an array. This method is called by the
  6705. * main [braces](#braces) function when `options.expand` is true. Before
  6706. * using this method it's recommended that you read the [performance notes](#performance))
  6707. * and advantages of using [.compile](#compile) instead.
  6708. *
  6709. * ```js
  6710. * const braces = require('braces');
  6711. * console.log(braces.expand('a/{b,c}/d'));
  6712. * //=> ['a/b/d', 'a/c/d'];
  6713. * ```
  6714. * @param {String} `pattern` Brace pattern
  6715. * @param {Object} `options`
  6716. * @return {Array} Returns an array of expanded values.
  6717. * @api public
  6718. */
  6719. braces$2.expand = (input, options = {}) => {
  6720. if (typeof input === 'string') {
  6721. input = braces$2.parse(input, options);
  6722. }
  6723. let result = expand$2(input, options);
  6724. // filter out empty strings if specified
  6725. if (options.noempty === true) {
  6726. result = result.filter(Boolean);
  6727. }
  6728. // filter out duplicates if specified
  6729. if (options.nodupes === true) {
  6730. result = [...new Set(result)];
  6731. }
  6732. return result;
  6733. };
  6734. /**
  6735. * Processes a brace pattern and returns either an expanded array
  6736. * (if `options.expand` is true), a highly optimized regex-compatible string.
  6737. * This method is called by the main [braces](#braces) function.
  6738. *
  6739. * ```js
  6740. * const braces = require('braces');
  6741. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  6742. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  6743. * ```
  6744. * @param {String} `pattern` Brace pattern
  6745. * @param {Object} `options`
  6746. * @return {Array} Returns an array of expanded values.
  6747. * @api public
  6748. */
  6749. braces$2.create = (input, options = {}) => {
  6750. if (input === '' || input.length < 3) {
  6751. return [input];
  6752. }
  6753. return options.expand !== true
  6754. ? braces$2.compile(input, options)
  6755. : braces$2.expand(input, options);
  6756. };
  6757. /**
  6758. * Expose "braces"
  6759. */
  6760. var braces_1 = braces$2;
  6761. var utils$f = {};
  6762. const path$t = path__default;
  6763. const WIN_SLASH = '\\\\/';
  6764. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  6765. /**
  6766. * Posix glob regex
  6767. */
  6768. const DOT_LITERAL = '\\.';
  6769. const PLUS_LITERAL = '\\+';
  6770. const QMARK_LITERAL = '\\?';
  6771. const SLASH_LITERAL = '\\/';
  6772. const ONE_CHAR = '(?=.)';
  6773. const QMARK = '[^/]';
  6774. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  6775. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  6776. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  6777. const NO_DOT = `(?!${DOT_LITERAL})`;
  6778. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  6779. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  6780. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  6781. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  6782. const STAR$1 = `${QMARK}*?`;
  6783. const POSIX_CHARS = {
  6784. DOT_LITERAL,
  6785. PLUS_LITERAL,
  6786. QMARK_LITERAL,
  6787. SLASH_LITERAL,
  6788. ONE_CHAR,
  6789. QMARK,
  6790. END_ANCHOR,
  6791. DOTS_SLASH,
  6792. NO_DOT,
  6793. NO_DOTS,
  6794. NO_DOT_SLASH,
  6795. NO_DOTS_SLASH,
  6796. QMARK_NO_DOT,
  6797. STAR: STAR$1,
  6798. START_ANCHOR
  6799. };
  6800. /**
  6801. * Windows glob regex
  6802. */
  6803. const WINDOWS_CHARS = {
  6804. ...POSIX_CHARS,
  6805. SLASH_LITERAL: `[${WIN_SLASH}]`,
  6806. QMARK: WIN_NO_SLASH,
  6807. STAR: `${WIN_NO_SLASH}*?`,
  6808. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  6809. NO_DOT: `(?!${DOT_LITERAL})`,
  6810. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  6811. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  6812. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  6813. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  6814. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  6815. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  6816. };
  6817. /**
  6818. * POSIX Bracket Regex
  6819. */
  6820. const POSIX_REGEX_SOURCE$1 = {
  6821. alnum: 'a-zA-Z0-9',
  6822. alpha: 'a-zA-Z',
  6823. ascii: '\\x00-\\x7F',
  6824. blank: ' \\t',
  6825. cntrl: '\\x00-\\x1F\\x7F',
  6826. digit: '0-9',
  6827. graph: '\\x21-\\x7E',
  6828. lower: 'a-z',
  6829. print: '\\x20-\\x7E ',
  6830. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  6831. space: ' \\t\\r\\n\\v\\f',
  6832. upper: 'A-Z',
  6833. word: 'A-Za-z0-9_',
  6834. xdigit: 'A-Fa-f0-9'
  6835. };
  6836. var constants$5 = {
  6837. MAX_LENGTH: 1024 * 64,
  6838. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  6839. // regular expressions
  6840. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  6841. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  6842. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  6843. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  6844. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  6845. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  6846. // Replace globs with equivalent patterns to reduce parsing time.
  6847. REPLACEMENTS: {
  6848. '***': '*',
  6849. '**/**': '**',
  6850. '**/**/**': '**'
  6851. },
  6852. // Digits
  6853. CHAR_0: 48, /* 0 */
  6854. CHAR_9: 57, /* 9 */
  6855. // Alphabet chars.
  6856. CHAR_UPPERCASE_A: 65, /* A */
  6857. CHAR_LOWERCASE_A: 97, /* a */
  6858. CHAR_UPPERCASE_Z: 90, /* Z */
  6859. CHAR_LOWERCASE_Z: 122, /* z */
  6860. CHAR_LEFT_PARENTHESES: 40, /* ( */
  6861. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  6862. CHAR_ASTERISK: 42, /* * */
  6863. // Non-alphabetic chars.
  6864. CHAR_AMPERSAND: 38, /* & */
  6865. CHAR_AT: 64, /* @ */
  6866. CHAR_BACKWARD_SLASH: 92, /* \ */
  6867. CHAR_CARRIAGE_RETURN: 13, /* \r */
  6868. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  6869. CHAR_COLON: 58, /* : */
  6870. CHAR_COMMA: 44, /* , */
  6871. CHAR_DOT: 46, /* . */
  6872. CHAR_DOUBLE_QUOTE: 34, /* " */
  6873. CHAR_EQUAL: 61, /* = */
  6874. CHAR_EXCLAMATION_MARK: 33, /* ! */
  6875. CHAR_FORM_FEED: 12, /* \f */
  6876. CHAR_FORWARD_SLASH: 47, /* / */
  6877. CHAR_GRAVE_ACCENT: 96, /* ` */
  6878. CHAR_HASH: 35, /* # */
  6879. CHAR_HYPHEN_MINUS: 45, /* - */
  6880. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  6881. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  6882. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  6883. CHAR_LINE_FEED: 10, /* \n */
  6884. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  6885. CHAR_PERCENT: 37, /* % */
  6886. CHAR_PLUS: 43, /* + */
  6887. CHAR_QUESTION_MARK: 63, /* ? */
  6888. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  6889. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  6890. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  6891. CHAR_SEMICOLON: 59, /* ; */
  6892. CHAR_SINGLE_QUOTE: 39, /* ' */
  6893. CHAR_SPACE: 32, /* */
  6894. CHAR_TAB: 9, /* \t */
  6895. CHAR_UNDERSCORE: 95, /* _ */
  6896. CHAR_VERTICAL_LINE: 124, /* | */
  6897. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  6898. SEP: path$t.sep,
  6899. /**
  6900. * Create EXTGLOB_CHARS
  6901. */
  6902. extglobChars(chars) {
  6903. return {
  6904. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  6905. '?': { type: 'qmark', open: '(?:', close: ')?' },
  6906. '+': { type: 'plus', open: '(?:', close: ')+' },
  6907. '*': { type: 'star', open: '(?:', close: ')*' },
  6908. '@': { type: 'at', open: '(?:', close: ')' }
  6909. };
  6910. },
  6911. /**
  6912. * Create GLOB_CHARS
  6913. */
  6914. globChars(win32) {
  6915. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  6916. }
  6917. };
  6918. (function (exports) {
  6919. const path = path__default;
  6920. const win32 = process.platform === 'win32';
  6921. const {
  6922. REGEX_BACKSLASH,
  6923. REGEX_REMOVE_BACKSLASH,
  6924. REGEX_SPECIAL_CHARS,
  6925. REGEX_SPECIAL_CHARS_GLOBAL
  6926. } = constants$5;
  6927. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  6928. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  6929. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  6930. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  6931. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  6932. exports.removeBackslashes = str => {
  6933. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  6934. return match === '\\' ? '' : match;
  6935. });
  6936. };
  6937. exports.supportsLookbehinds = () => {
  6938. const segs = process.version.slice(1).split('.').map(Number);
  6939. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  6940. return true;
  6941. }
  6942. return false;
  6943. };
  6944. exports.isWindows = options => {
  6945. if (options && typeof options.windows === 'boolean') {
  6946. return options.windows;
  6947. }
  6948. return win32 === true || path.sep === '\\';
  6949. };
  6950. exports.escapeLast = (input, char, lastIdx) => {
  6951. const idx = input.lastIndexOf(char, lastIdx);
  6952. if (idx === -1) return input;
  6953. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  6954. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  6955. };
  6956. exports.removePrefix = (input, state = {}) => {
  6957. let output = input;
  6958. if (output.startsWith('./')) {
  6959. output = output.slice(2);
  6960. state.prefix = './';
  6961. }
  6962. return output;
  6963. };
  6964. exports.wrapOutput = (input, state = {}, options = {}) => {
  6965. const prepend = options.contains ? '' : '^';
  6966. const append = options.contains ? '' : '$';
  6967. let output = `${prepend}(?:${input})${append}`;
  6968. if (state.negated === true) {
  6969. output = `(?:^(?!${output}).*$)`;
  6970. }
  6971. return output;
  6972. };
  6973. }(utils$f));
  6974. const utils$e = utils$f;
  6975. const {
  6976. CHAR_ASTERISK, /* * */
  6977. CHAR_AT, /* @ */
  6978. CHAR_BACKWARD_SLASH, /* \ */
  6979. CHAR_COMMA, /* , */
  6980. CHAR_DOT, /* . */
  6981. CHAR_EXCLAMATION_MARK, /* ! */
  6982. CHAR_FORWARD_SLASH, /* / */
  6983. CHAR_LEFT_CURLY_BRACE, /* { */
  6984. CHAR_LEFT_PARENTHESES, /* ( */
  6985. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  6986. CHAR_PLUS, /* + */
  6987. CHAR_QUESTION_MARK, /* ? */
  6988. CHAR_RIGHT_CURLY_BRACE, /* } */
  6989. CHAR_RIGHT_PARENTHESES, /* ) */
  6990. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  6991. } = constants$5;
  6992. const isPathSeparator = code => {
  6993. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  6994. };
  6995. const depth = token => {
  6996. if (token.isPrefix !== true) {
  6997. token.depth = token.isGlobstar ? Infinity : 1;
  6998. }
  6999. };
  7000. /**
  7001. * Quickly scans a glob pattern and returns an object with a handful of
  7002. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  7003. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  7004. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  7005. *
  7006. * ```js
  7007. * const pm = require('picomatch');
  7008. * console.log(pm.scan('foo/bar/*.js'));
  7009. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  7010. * ```
  7011. * @param {String} `str`
  7012. * @param {Object} `options`
  7013. * @return {Object} Returns an object with tokens and regex source string.
  7014. * @api public
  7015. */
  7016. const scan$1 = (input, options) => {
  7017. const opts = options || {};
  7018. const length = input.length - 1;
  7019. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  7020. const slashes = [];
  7021. const tokens = [];
  7022. const parts = [];
  7023. let str = input;
  7024. let index = -1;
  7025. let start = 0;
  7026. let lastIndex = 0;
  7027. let isBrace = false;
  7028. let isBracket = false;
  7029. let isGlob = false;
  7030. let isExtglob = false;
  7031. let isGlobstar = false;
  7032. let braceEscaped = false;
  7033. let backslashes = false;
  7034. let negated = false;
  7035. let negatedExtglob = false;
  7036. let finished = false;
  7037. let braces = 0;
  7038. let prev;
  7039. let code;
  7040. let token = { value: '', depth: 0, isGlob: false };
  7041. const eos = () => index >= length;
  7042. const peek = () => str.charCodeAt(index + 1);
  7043. const advance = () => {
  7044. prev = code;
  7045. return str.charCodeAt(++index);
  7046. };
  7047. while (index < length) {
  7048. code = advance();
  7049. let next;
  7050. if (code === CHAR_BACKWARD_SLASH) {
  7051. backslashes = token.backslashes = true;
  7052. code = advance();
  7053. if (code === CHAR_LEFT_CURLY_BRACE) {
  7054. braceEscaped = true;
  7055. }
  7056. continue;
  7057. }
  7058. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  7059. braces++;
  7060. while (eos() !== true && (code = advance())) {
  7061. if (code === CHAR_BACKWARD_SLASH) {
  7062. backslashes = token.backslashes = true;
  7063. advance();
  7064. continue;
  7065. }
  7066. if (code === CHAR_LEFT_CURLY_BRACE) {
  7067. braces++;
  7068. continue;
  7069. }
  7070. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  7071. isBrace = token.isBrace = true;
  7072. isGlob = token.isGlob = true;
  7073. finished = true;
  7074. if (scanToEnd === true) {
  7075. continue;
  7076. }
  7077. break;
  7078. }
  7079. if (braceEscaped !== true && code === CHAR_COMMA) {
  7080. isBrace = token.isBrace = true;
  7081. isGlob = token.isGlob = true;
  7082. finished = true;
  7083. if (scanToEnd === true) {
  7084. continue;
  7085. }
  7086. break;
  7087. }
  7088. if (code === CHAR_RIGHT_CURLY_BRACE) {
  7089. braces--;
  7090. if (braces === 0) {
  7091. braceEscaped = false;
  7092. isBrace = token.isBrace = true;
  7093. finished = true;
  7094. break;
  7095. }
  7096. }
  7097. }
  7098. if (scanToEnd === true) {
  7099. continue;
  7100. }
  7101. break;
  7102. }
  7103. if (code === CHAR_FORWARD_SLASH) {
  7104. slashes.push(index);
  7105. tokens.push(token);
  7106. token = { value: '', depth: 0, isGlob: false };
  7107. if (finished === true) continue;
  7108. if (prev === CHAR_DOT && index === (start + 1)) {
  7109. start += 2;
  7110. continue;
  7111. }
  7112. lastIndex = index + 1;
  7113. continue;
  7114. }
  7115. if (opts.noext !== true) {
  7116. const isExtglobChar = code === CHAR_PLUS
  7117. || code === CHAR_AT
  7118. || code === CHAR_ASTERISK
  7119. || code === CHAR_QUESTION_MARK
  7120. || code === CHAR_EXCLAMATION_MARK;
  7121. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  7122. isGlob = token.isGlob = true;
  7123. isExtglob = token.isExtglob = true;
  7124. finished = true;
  7125. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  7126. negatedExtglob = true;
  7127. }
  7128. if (scanToEnd === true) {
  7129. while (eos() !== true && (code = advance())) {
  7130. if (code === CHAR_BACKWARD_SLASH) {
  7131. backslashes = token.backslashes = true;
  7132. code = advance();
  7133. continue;
  7134. }
  7135. if (code === CHAR_RIGHT_PARENTHESES) {
  7136. isGlob = token.isGlob = true;
  7137. finished = true;
  7138. break;
  7139. }
  7140. }
  7141. continue;
  7142. }
  7143. break;
  7144. }
  7145. }
  7146. if (code === CHAR_ASTERISK) {
  7147. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  7148. isGlob = token.isGlob = true;
  7149. finished = true;
  7150. if (scanToEnd === true) {
  7151. continue;
  7152. }
  7153. break;
  7154. }
  7155. if (code === CHAR_QUESTION_MARK) {
  7156. isGlob = token.isGlob = true;
  7157. finished = true;
  7158. if (scanToEnd === true) {
  7159. continue;
  7160. }
  7161. break;
  7162. }
  7163. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  7164. while (eos() !== true && (next = advance())) {
  7165. if (next === CHAR_BACKWARD_SLASH) {
  7166. backslashes = token.backslashes = true;
  7167. advance();
  7168. continue;
  7169. }
  7170. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  7171. isBracket = token.isBracket = true;
  7172. isGlob = token.isGlob = true;
  7173. finished = true;
  7174. break;
  7175. }
  7176. }
  7177. if (scanToEnd === true) {
  7178. continue;
  7179. }
  7180. break;
  7181. }
  7182. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  7183. negated = token.negated = true;
  7184. start++;
  7185. continue;
  7186. }
  7187. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  7188. isGlob = token.isGlob = true;
  7189. if (scanToEnd === true) {
  7190. while (eos() !== true && (code = advance())) {
  7191. if (code === CHAR_LEFT_PARENTHESES) {
  7192. backslashes = token.backslashes = true;
  7193. code = advance();
  7194. continue;
  7195. }
  7196. if (code === CHAR_RIGHT_PARENTHESES) {
  7197. finished = true;
  7198. break;
  7199. }
  7200. }
  7201. continue;
  7202. }
  7203. break;
  7204. }
  7205. if (isGlob === true) {
  7206. finished = true;
  7207. if (scanToEnd === true) {
  7208. continue;
  7209. }
  7210. break;
  7211. }
  7212. }
  7213. if (opts.noext === true) {
  7214. isExtglob = false;
  7215. isGlob = false;
  7216. }
  7217. let base = str;
  7218. let prefix = '';
  7219. let glob = '';
  7220. if (start > 0) {
  7221. prefix = str.slice(0, start);
  7222. str = str.slice(start);
  7223. lastIndex -= start;
  7224. }
  7225. if (base && isGlob === true && lastIndex > 0) {
  7226. base = str.slice(0, lastIndex);
  7227. glob = str.slice(lastIndex);
  7228. } else if (isGlob === true) {
  7229. base = '';
  7230. glob = str;
  7231. } else {
  7232. base = str;
  7233. }
  7234. if (base && base !== '' && base !== '/' && base !== str) {
  7235. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  7236. base = base.slice(0, -1);
  7237. }
  7238. }
  7239. if (opts.unescape === true) {
  7240. if (glob) glob = utils$e.removeBackslashes(glob);
  7241. if (base && backslashes === true) {
  7242. base = utils$e.removeBackslashes(base);
  7243. }
  7244. }
  7245. const state = {
  7246. prefix,
  7247. input,
  7248. start,
  7249. base,
  7250. glob,
  7251. isBrace,
  7252. isBracket,
  7253. isGlob,
  7254. isExtglob,
  7255. isGlobstar,
  7256. negated,
  7257. negatedExtglob
  7258. };
  7259. if (opts.tokens === true) {
  7260. state.maxDepth = 0;
  7261. if (!isPathSeparator(code)) {
  7262. tokens.push(token);
  7263. }
  7264. state.tokens = tokens;
  7265. }
  7266. if (opts.parts === true || opts.tokens === true) {
  7267. let prevIndex;
  7268. for (let idx = 0; idx < slashes.length; idx++) {
  7269. const n = prevIndex ? prevIndex + 1 : start;
  7270. const i = slashes[idx];
  7271. const value = input.slice(n, i);
  7272. if (opts.tokens) {
  7273. if (idx === 0 && start !== 0) {
  7274. tokens[idx].isPrefix = true;
  7275. tokens[idx].value = prefix;
  7276. } else {
  7277. tokens[idx].value = value;
  7278. }
  7279. depth(tokens[idx]);
  7280. state.maxDepth += tokens[idx].depth;
  7281. }
  7282. if (idx !== 0 || value !== '') {
  7283. parts.push(value);
  7284. }
  7285. prevIndex = i;
  7286. }
  7287. if (prevIndex && prevIndex + 1 < input.length) {
  7288. const value = input.slice(prevIndex + 1);
  7289. parts.push(value);
  7290. if (opts.tokens) {
  7291. tokens[tokens.length - 1].value = value;
  7292. depth(tokens[tokens.length - 1]);
  7293. state.maxDepth += tokens[tokens.length - 1].depth;
  7294. }
  7295. }
  7296. state.slashes = slashes;
  7297. state.parts = parts;
  7298. }
  7299. return state;
  7300. };
  7301. var scan_1 = scan$1;
  7302. const constants$4 = constants$5;
  7303. const utils$d = utils$f;
  7304. /**
  7305. * Constants
  7306. */
  7307. const {
  7308. MAX_LENGTH,
  7309. POSIX_REGEX_SOURCE,
  7310. REGEX_NON_SPECIAL_CHARS,
  7311. REGEX_SPECIAL_CHARS_BACKREF,
  7312. REPLACEMENTS
  7313. } = constants$4;
  7314. /**
  7315. * Helpers
  7316. */
  7317. const expandRange = (args, options) => {
  7318. if (typeof options.expandRange === 'function') {
  7319. return options.expandRange(...args, options);
  7320. }
  7321. args.sort();
  7322. const value = `[${args.join('-')}]`;
  7323. return value;
  7324. };
  7325. /**
  7326. * Create the message for a syntax error
  7327. */
  7328. const syntaxError = (type, char) => {
  7329. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  7330. };
  7331. /**
  7332. * Parse the given input string.
  7333. * @param {String} input
  7334. * @param {Object} options
  7335. * @return {Object}
  7336. */
  7337. const parse$i = (input, options) => {
  7338. if (typeof input !== 'string') {
  7339. throw new TypeError('Expected a string');
  7340. }
  7341. input = REPLACEMENTS[input] || input;
  7342. const opts = { ...options };
  7343. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  7344. let len = input.length;
  7345. if (len > max) {
  7346. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  7347. }
  7348. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  7349. const tokens = [bos];
  7350. const capture = opts.capture ? '' : '?:';
  7351. const win32 = utils$d.isWindows(options);
  7352. // create constants based on platform, for windows or posix
  7353. const PLATFORM_CHARS = constants$4.globChars(win32);
  7354. const EXTGLOB_CHARS = constants$4.extglobChars(PLATFORM_CHARS);
  7355. const {
  7356. DOT_LITERAL,
  7357. PLUS_LITERAL,
  7358. SLASH_LITERAL,
  7359. ONE_CHAR,
  7360. DOTS_SLASH,
  7361. NO_DOT,
  7362. NO_DOT_SLASH,
  7363. NO_DOTS_SLASH,
  7364. QMARK,
  7365. QMARK_NO_DOT,
  7366. STAR,
  7367. START_ANCHOR
  7368. } = PLATFORM_CHARS;
  7369. const globstar = opts => {
  7370. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  7371. };
  7372. const nodot = opts.dot ? '' : NO_DOT;
  7373. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  7374. let star = opts.bash === true ? globstar(opts) : STAR;
  7375. if (opts.capture) {
  7376. star = `(${star})`;
  7377. }
  7378. // minimatch options support
  7379. if (typeof opts.noext === 'boolean') {
  7380. opts.noextglob = opts.noext;
  7381. }
  7382. const state = {
  7383. input,
  7384. index: -1,
  7385. start: 0,
  7386. dot: opts.dot === true,
  7387. consumed: '',
  7388. output: '',
  7389. prefix: '',
  7390. backtrack: false,
  7391. negated: false,
  7392. brackets: 0,
  7393. braces: 0,
  7394. parens: 0,
  7395. quotes: 0,
  7396. globstar: false,
  7397. tokens
  7398. };
  7399. input = utils$d.removePrefix(input, state);
  7400. len = input.length;
  7401. const extglobs = [];
  7402. const braces = [];
  7403. const stack = [];
  7404. let prev = bos;
  7405. let value;
  7406. /**
  7407. * Tokenizing helpers
  7408. */
  7409. const eos = () => state.index === len - 1;
  7410. const peek = state.peek = (n = 1) => input[state.index + n];
  7411. const advance = state.advance = () => input[++state.index] || '';
  7412. const remaining = () => input.slice(state.index + 1);
  7413. const consume = (value = '', num = 0) => {
  7414. state.consumed += value;
  7415. state.index += num;
  7416. };
  7417. const append = token => {
  7418. state.output += token.output != null ? token.output : token.value;
  7419. consume(token.value);
  7420. };
  7421. const negate = () => {
  7422. let count = 1;
  7423. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  7424. advance();
  7425. state.start++;
  7426. count++;
  7427. }
  7428. if (count % 2 === 0) {
  7429. return false;
  7430. }
  7431. state.negated = true;
  7432. state.start++;
  7433. return true;
  7434. };
  7435. const increment = type => {
  7436. state[type]++;
  7437. stack.push(type);
  7438. };
  7439. const decrement = type => {
  7440. state[type]--;
  7441. stack.pop();
  7442. };
  7443. /**
  7444. * Push tokens onto the tokens array. This helper speeds up
  7445. * tokenizing by 1) helping us avoid backtracking as much as possible,
  7446. * and 2) helping us avoid creating extra tokens when consecutive
  7447. * characters are plain text. This improves performance and simplifies
  7448. * lookbehinds.
  7449. */
  7450. const push = tok => {
  7451. if (prev.type === 'globstar') {
  7452. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  7453. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  7454. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  7455. state.output = state.output.slice(0, -prev.output.length);
  7456. prev.type = 'star';
  7457. prev.value = '*';
  7458. prev.output = star;
  7459. state.output += prev.output;
  7460. }
  7461. }
  7462. if (extglobs.length && tok.type !== 'paren') {
  7463. extglobs[extglobs.length - 1].inner += tok.value;
  7464. }
  7465. if (tok.value || tok.output) append(tok);
  7466. if (prev && prev.type === 'text' && tok.type === 'text') {
  7467. prev.value += tok.value;
  7468. prev.output = (prev.output || '') + tok.value;
  7469. return;
  7470. }
  7471. tok.prev = prev;
  7472. tokens.push(tok);
  7473. prev = tok;
  7474. };
  7475. const extglobOpen = (type, value) => {
  7476. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  7477. token.prev = prev;
  7478. token.parens = state.parens;
  7479. token.output = state.output;
  7480. const output = (opts.capture ? '(' : '') + token.open;
  7481. increment('parens');
  7482. push({ type, value, output: state.output ? '' : ONE_CHAR });
  7483. push({ type: 'paren', extglob: true, value: advance(), output });
  7484. extglobs.push(token);
  7485. };
  7486. const extglobClose = token => {
  7487. let output = token.close + (opts.capture ? ')' : '');
  7488. let rest;
  7489. if (token.type === 'negate') {
  7490. let extglobStar = star;
  7491. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  7492. extglobStar = globstar(opts);
  7493. }
  7494. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  7495. output = token.close = `)$))${extglobStar}`;
  7496. }
  7497. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  7498. output = token.close = `)${rest})${extglobStar})`;
  7499. }
  7500. if (token.prev.type === 'bos') {
  7501. state.negatedExtglob = true;
  7502. }
  7503. }
  7504. push({ type: 'paren', extglob: true, value, output });
  7505. decrement('parens');
  7506. };
  7507. /**
  7508. * Fast paths
  7509. */
  7510. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  7511. let backslashes = false;
  7512. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  7513. if (first === '\\') {
  7514. backslashes = true;
  7515. return m;
  7516. }
  7517. if (first === '?') {
  7518. if (esc) {
  7519. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  7520. }
  7521. if (index === 0) {
  7522. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  7523. }
  7524. return QMARK.repeat(chars.length);
  7525. }
  7526. if (first === '.') {
  7527. return DOT_LITERAL.repeat(chars.length);
  7528. }
  7529. if (first === '*') {
  7530. if (esc) {
  7531. return esc + first + (rest ? star : '');
  7532. }
  7533. return star;
  7534. }
  7535. return esc ? m : `\\${m}`;
  7536. });
  7537. if (backslashes === true) {
  7538. if (opts.unescape === true) {
  7539. output = output.replace(/\\/g, '');
  7540. } else {
  7541. output = output.replace(/\\+/g, m => {
  7542. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  7543. });
  7544. }
  7545. }
  7546. if (output === input && opts.contains === true) {
  7547. state.output = input;
  7548. return state;
  7549. }
  7550. state.output = utils$d.wrapOutput(output, state, options);
  7551. return state;
  7552. }
  7553. /**
  7554. * Tokenize input until we reach end-of-string
  7555. */
  7556. while (!eos()) {
  7557. value = advance();
  7558. if (value === '\u0000') {
  7559. continue;
  7560. }
  7561. /**
  7562. * Escaped characters
  7563. */
  7564. if (value === '\\') {
  7565. const next = peek();
  7566. if (next === '/' && opts.bash !== true) {
  7567. continue;
  7568. }
  7569. if (next === '.' || next === ';') {
  7570. continue;
  7571. }
  7572. if (!next) {
  7573. value += '\\';
  7574. push({ type: 'text', value });
  7575. continue;
  7576. }
  7577. // collapse slashes to reduce potential for exploits
  7578. const match = /^\\+/.exec(remaining());
  7579. let slashes = 0;
  7580. if (match && match[0].length > 2) {
  7581. slashes = match[0].length;
  7582. state.index += slashes;
  7583. if (slashes % 2 !== 0) {
  7584. value += '\\';
  7585. }
  7586. }
  7587. if (opts.unescape === true) {
  7588. value = advance();
  7589. } else {
  7590. value += advance();
  7591. }
  7592. if (state.brackets === 0) {
  7593. push({ type: 'text', value });
  7594. continue;
  7595. }
  7596. }
  7597. /**
  7598. * If we're inside a regex character class, continue
  7599. * until we reach the closing bracket.
  7600. */
  7601. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  7602. if (opts.posix !== false && value === ':') {
  7603. const inner = prev.value.slice(1);
  7604. if (inner.includes('[')) {
  7605. prev.posix = true;
  7606. if (inner.includes(':')) {
  7607. const idx = prev.value.lastIndexOf('[');
  7608. const pre = prev.value.slice(0, idx);
  7609. const rest = prev.value.slice(idx + 2);
  7610. const posix = POSIX_REGEX_SOURCE[rest];
  7611. if (posix) {
  7612. prev.value = pre + posix;
  7613. state.backtrack = true;
  7614. advance();
  7615. if (!bos.output && tokens.indexOf(prev) === 1) {
  7616. bos.output = ONE_CHAR;
  7617. }
  7618. continue;
  7619. }
  7620. }
  7621. }
  7622. }
  7623. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  7624. value = `\\${value}`;
  7625. }
  7626. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  7627. value = `\\${value}`;
  7628. }
  7629. if (opts.posix === true && value === '!' && prev.value === '[') {
  7630. value = '^';
  7631. }
  7632. prev.value += value;
  7633. append({ value });
  7634. continue;
  7635. }
  7636. /**
  7637. * If we're inside a quoted string, continue
  7638. * until we reach the closing double quote.
  7639. */
  7640. if (state.quotes === 1 && value !== '"') {
  7641. value = utils$d.escapeRegex(value);
  7642. prev.value += value;
  7643. append({ value });
  7644. continue;
  7645. }
  7646. /**
  7647. * Double quotes
  7648. */
  7649. if (value === '"') {
  7650. state.quotes = state.quotes === 1 ? 0 : 1;
  7651. if (opts.keepQuotes === true) {
  7652. push({ type: 'text', value });
  7653. }
  7654. continue;
  7655. }
  7656. /**
  7657. * Parentheses
  7658. */
  7659. if (value === '(') {
  7660. increment('parens');
  7661. push({ type: 'paren', value });
  7662. continue;
  7663. }
  7664. if (value === ')') {
  7665. if (state.parens === 0 && opts.strictBrackets === true) {
  7666. throw new SyntaxError(syntaxError('opening', '('));
  7667. }
  7668. const extglob = extglobs[extglobs.length - 1];
  7669. if (extglob && state.parens === extglob.parens + 1) {
  7670. extglobClose(extglobs.pop());
  7671. continue;
  7672. }
  7673. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  7674. decrement('parens');
  7675. continue;
  7676. }
  7677. /**
  7678. * Square brackets
  7679. */
  7680. if (value === '[') {
  7681. if (opts.nobracket === true || !remaining().includes(']')) {
  7682. if (opts.nobracket !== true && opts.strictBrackets === true) {
  7683. throw new SyntaxError(syntaxError('closing', ']'));
  7684. }
  7685. value = `\\${value}`;
  7686. } else {
  7687. increment('brackets');
  7688. }
  7689. push({ type: 'bracket', value });
  7690. continue;
  7691. }
  7692. if (value === ']') {
  7693. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  7694. push({ type: 'text', value, output: `\\${value}` });
  7695. continue;
  7696. }
  7697. if (state.brackets === 0) {
  7698. if (opts.strictBrackets === true) {
  7699. throw new SyntaxError(syntaxError('opening', '['));
  7700. }
  7701. push({ type: 'text', value, output: `\\${value}` });
  7702. continue;
  7703. }
  7704. decrement('brackets');
  7705. const prevValue = prev.value.slice(1);
  7706. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  7707. value = `/${value}`;
  7708. }
  7709. prev.value += value;
  7710. append({ value });
  7711. // when literal brackets are explicitly disabled
  7712. // assume we should match with a regex character class
  7713. if (opts.literalBrackets === false || utils$d.hasRegexChars(prevValue)) {
  7714. continue;
  7715. }
  7716. const escaped = utils$d.escapeRegex(prev.value);
  7717. state.output = state.output.slice(0, -prev.value.length);
  7718. // when literal brackets are explicitly enabled
  7719. // assume we should escape the brackets to match literal characters
  7720. if (opts.literalBrackets === true) {
  7721. state.output += escaped;
  7722. prev.value = escaped;
  7723. continue;
  7724. }
  7725. // when the user specifies nothing, try to match both
  7726. prev.value = `(${capture}${escaped}|${prev.value})`;
  7727. state.output += prev.value;
  7728. continue;
  7729. }
  7730. /**
  7731. * Braces
  7732. */
  7733. if (value === '{' && opts.nobrace !== true) {
  7734. increment('braces');
  7735. const open = {
  7736. type: 'brace',
  7737. value,
  7738. output: '(',
  7739. outputIndex: state.output.length,
  7740. tokensIndex: state.tokens.length
  7741. };
  7742. braces.push(open);
  7743. push(open);
  7744. continue;
  7745. }
  7746. if (value === '}') {
  7747. const brace = braces[braces.length - 1];
  7748. if (opts.nobrace === true || !brace) {
  7749. push({ type: 'text', value, output: value });
  7750. continue;
  7751. }
  7752. let output = ')';
  7753. if (brace.dots === true) {
  7754. const arr = tokens.slice();
  7755. const range = [];
  7756. for (let i = arr.length - 1; i >= 0; i--) {
  7757. tokens.pop();
  7758. if (arr[i].type === 'brace') {
  7759. break;
  7760. }
  7761. if (arr[i].type !== 'dots') {
  7762. range.unshift(arr[i].value);
  7763. }
  7764. }
  7765. output = expandRange(range, opts);
  7766. state.backtrack = true;
  7767. }
  7768. if (brace.comma !== true && brace.dots !== true) {
  7769. const out = state.output.slice(0, brace.outputIndex);
  7770. const toks = state.tokens.slice(brace.tokensIndex);
  7771. brace.value = brace.output = '\\{';
  7772. value = output = '\\}';
  7773. state.output = out;
  7774. for (const t of toks) {
  7775. state.output += (t.output || t.value);
  7776. }
  7777. }
  7778. push({ type: 'brace', value, output });
  7779. decrement('braces');
  7780. braces.pop();
  7781. continue;
  7782. }
  7783. /**
  7784. * Pipes
  7785. */
  7786. if (value === '|') {
  7787. if (extglobs.length > 0) {
  7788. extglobs[extglobs.length - 1].conditions++;
  7789. }
  7790. push({ type: 'text', value });
  7791. continue;
  7792. }
  7793. /**
  7794. * Commas
  7795. */
  7796. if (value === ',') {
  7797. let output = value;
  7798. const brace = braces[braces.length - 1];
  7799. if (brace && stack[stack.length - 1] === 'braces') {
  7800. brace.comma = true;
  7801. output = '|';
  7802. }
  7803. push({ type: 'comma', value, output });
  7804. continue;
  7805. }
  7806. /**
  7807. * Slashes
  7808. */
  7809. if (value === '/') {
  7810. // if the beginning of the glob is "./", advance the start
  7811. // to the current index, and don't add the "./" characters
  7812. // to the state. This greatly simplifies lookbehinds when
  7813. // checking for BOS characters like "!" and "." (not "./")
  7814. if (prev.type === 'dot' && state.index === state.start + 1) {
  7815. state.start = state.index + 1;
  7816. state.consumed = '';
  7817. state.output = '';
  7818. tokens.pop();
  7819. prev = bos; // reset "prev" to the first token
  7820. continue;
  7821. }
  7822. push({ type: 'slash', value, output: SLASH_LITERAL });
  7823. continue;
  7824. }
  7825. /**
  7826. * Dots
  7827. */
  7828. if (value === '.') {
  7829. if (state.braces > 0 && prev.type === 'dot') {
  7830. if (prev.value === '.') prev.output = DOT_LITERAL;
  7831. const brace = braces[braces.length - 1];
  7832. prev.type = 'dots';
  7833. prev.output += value;
  7834. prev.value += value;
  7835. brace.dots = true;
  7836. continue;
  7837. }
  7838. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  7839. push({ type: 'text', value, output: DOT_LITERAL });
  7840. continue;
  7841. }
  7842. push({ type: 'dot', value, output: DOT_LITERAL });
  7843. continue;
  7844. }
  7845. /**
  7846. * Question marks
  7847. */
  7848. if (value === '?') {
  7849. const isGroup = prev && prev.value === '(';
  7850. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7851. extglobOpen('qmark', value);
  7852. continue;
  7853. }
  7854. if (prev && prev.type === 'paren') {
  7855. const next = peek();
  7856. let output = value;
  7857. if (next === '<' && !utils$d.supportsLookbehinds()) {
  7858. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  7859. }
  7860. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  7861. output = `\\${value}`;
  7862. }
  7863. push({ type: 'text', value, output });
  7864. continue;
  7865. }
  7866. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  7867. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  7868. continue;
  7869. }
  7870. push({ type: 'qmark', value, output: QMARK });
  7871. continue;
  7872. }
  7873. /**
  7874. * Exclamation
  7875. */
  7876. if (value === '!') {
  7877. if (opts.noextglob !== true && peek() === '(') {
  7878. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  7879. extglobOpen('negate', value);
  7880. continue;
  7881. }
  7882. }
  7883. if (opts.nonegate !== true && state.index === 0) {
  7884. negate();
  7885. continue;
  7886. }
  7887. }
  7888. /**
  7889. * Plus
  7890. */
  7891. if (value === '+') {
  7892. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7893. extglobOpen('plus', value);
  7894. continue;
  7895. }
  7896. if ((prev && prev.value === '(') || opts.regex === false) {
  7897. push({ type: 'plus', value, output: PLUS_LITERAL });
  7898. continue;
  7899. }
  7900. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  7901. push({ type: 'plus', value });
  7902. continue;
  7903. }
  7904. push({ type: 'plus', value: PLUS_LITERAL });
  7905. continue;
  7906. }
  7907. /**
  7908. * Plain text
  7909. */
  7910. if (value === '@') {
  7911. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7912. push({ type: 'at', extglob: true, value, output: '' });
  7913. continue;
  7914. }
  7915. push({ type: 'text', value });
  7916. continue;
  7917. }
  7918. /**
  7919. * Plain text
  7920. */
  7921. if (value !== '*') {
  7922. if (value === '$' || value === '^') {
  7923. value = `\\${value}`;
  7924. }
  7925. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  7926. if (match) {
  7927. value += match[0];
  7928. state.index += match[0].length;
  7929. }
  7930. push({ type: 'text', value });
  7931. continue;
  7932. }
  7933. /**
  7934. * Stars
  7935. */
  7936. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  7937. prev.type = 'star';
  7938. prev.star = true;
  7939. prev.value += value;
  7940. prev.output = star;
  7941. state.backtrack = true;
  7942. state.globstar = true;
  7943. consume(value);
  7944. continue;
  7945. }
  7946. let rest = remaining();
  7947. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  7948. extglobOpen('star', value);
  7949. continue;
  7950. }
  7951. if (prev.type === 'star') {
  7952. if (opts.noglobstar === true) {
  7953. consume(value);
  7954. continue;
  7955. }
  7956. const prior = prev.prev;
  7957. const before = prior.prev;
  7958. const isStart = prior.type === 'slash' || prior.type === 'bos';
  7959. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  7960. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  7961. push({ type: 'star', value, output: '' });
  7962. continue;
  7963. }
  7964. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  7965. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  7966. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  7967. push({ type: 'star', value, output: '' });
  7968. continue;
  7969. }
  7970. // strip consecutive `/**/`
  7971. while (rest.slice(0, 3) === '/**') {
  7972. const after = input[state.index + 4];
  7973. if (after && after !== '/') {
  7974. break;
  7975. }
  7976. rest = rest.slice(3);
  7977. consume('/**', 3);
  7978. }
  7979. if (prior.type === 'bos' && eos()) {
  7980. prev.type = 'globstar';
  7981. prev.value += value;
  7982. prev.output = globstar(opts);
  7983. state.output = prev.output;
  7984. state.globstar = true;
  7985. consume(value);
  7986. continue;
  7987. }
  7988. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  7989. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  7990. prior.output = `(?:${prior.output}`;
  7991. prev.type = 'globstar';
  7992. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  7993. prev.value += value;
  7994. state.globstar = true;
  7995. state.output += prior.output + prev.output;
  7996. consume(value);
  7997. continue;
  7998. }
  7999. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  8000. const end = rest[1] !== void 0 ? '|$' : '';
  8001. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  8002. prior.output = `(?:${prior.output}`;
  8003. prev.type = 'globstar';
  8004. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  8005. prev.value += value;
  8006. state.output += prior.output + prev.output;
  8007. state.globstar = true;
  8008. consume(value + advance());
  8009. push({ type: 'slash', value: '/', output: '' });
  8010. continue;
  8011. }
  8012. if (prior.type === 'bos' && rest[0] === '/') {
  8013. prev.type = 'globstar';
  8014. prev.value += value;
  8015. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  8016. state.output = prev.output;
  8017. state.globstar = true;
  8018. consume(value + advance());
  8019. push({ type: 'slash', value: '/', output: '' });
  8020. continue;
  8021. }
  8022. // remove single star from output
  8023. state.output = state.output.slice(0, -prev.output.length);
  8024. // reset previous token to globstar
  8025. prev.type = 'globstar';
  8026. prev.output = globstar(opts);
  8027. prev.value += value;
  8028. // reset output with globstar
  8029. state.output += prev.output;
  8030. state.globstar = true;
  8031. consume(value);
  8032. continue;
  8033. }
  8034. const token = { type: 'star', value, output: star };
  8035. if (opts.bash === true) {
  8036. token.output = '.*?';
  8037. if (prev.type === 'bos' || prev.type === 'slash') {
  8038. token.output = nodot + token.output;
  8039. }
  8040. push(token);
  8041. continue;
  8042. }
  8043. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  8044. token.output = value;
  8045. push(token);
  8046. continue;
  8047. }
  8048. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  8049. if (prev.type === 'dot') {
  8050. state.output += NO_DOT_SLASH;
  8051. prev.output += NO_DOT_SLASH;
  8052. } else if (opts.dot === true) {
  8053. state.output += NO_DOTS_SLASH;
  8054. prev.output += NO_DOTS_SLASH;
  8055. } else {
  8056. state.output += nodot;
  8057. prev.output += nodot;
  8058. }
  8059. if (peek() !== '*') {
  8060. state.output += ONE_CHAR;
  8061. prev.output += ONE_CHAR;
  8062. }
  8063. }
  8064. push(token);
  8065. }
  8066. while (state.brackets > 0) {
  8067. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  8068. state.output = utils$d.escapeLast(state.output, '[');
  8069. decrement('brackets');
  8070. }
  8071. while (state.parens > 0) {
  8072. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  8073. state.output = utils$d.escapeLast(state.output, '(');
  8074. decrement('parens');
  8075. }
  8076. while (state.braces > 0) {
  8077. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  8078. state.output = utils$d.escapeLast(state.output, '{');
  8079. decrement('braces');
  8080. }
  8081. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  8082. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  8083. }
  8084. // rebuild the output if we had to backtrack at any point
  8085. if (state.backtrack === true) {
  8086. state.output = '';
  8087. for (const token of state.tokens) {
  8088. state.output += token.output != null ? token.output : token.value;
  8089. if (token.suffix) {
  8090. state.output += token.suffix;
  8091. }
  8092. }
  8093. }
  8094. return state;
  8095. };
  8096. /**
  8097. * Fast paths for creating regular expressions for common glob patterns.
  8098. * This can significantly speed up processing and has very little downside
  8099. * impact when none of the fast paths match.
  8100. */
  8101. parse$i.fastpaths = (input, options) => {
  8102. const opts = { ...options };
  8103. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  8104. const len = input.length;
  8105. if (len > max) {
  8106. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  8107. }
  8108. input = REPLACEMENTS[input] || input;
  8109. const win32 = utils$d.isWindows(options);
  8110. // create constants based on platform, for windows or posix
  8111. const {
  8112. DOT_LITERAL,
  8113. SLASH_LITERAL,
  8114. ONE_CHAR,
  8115. DOTS_SLASH,
  8116. NO_DOT,
  8117. NO_DOTS,
  8118. NO_DOTS_SLASH,
  8119. STAR,
  8120. START_ANCHOR
  8121. } = constants$4.globChars(win32);
  8122. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  8123. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  8124. const capture = opts.capture ? '' : '?:';
  8125. const state = { negated: false, prefix: '' };
  8126. let star = opts.bash === true ? '.*?' : STAR;
  8127. if (opts.capture) {
  8128. star = `(${star})`;
  8129. }
  8130. const globstar = opts => {
  8131. if (opts.noglobstar === true) return star;
  8132. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  8133. };
  8134. const create = str => {
  8135. switch (str) {
  8136. case '*':
  8137. return `${nodot}${ONE_CHAR}${star}`;
  8138. case '.*':
  8139. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  8140. case '*.*':
  8141. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  8142. case '*/*':
  8143. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  8144. case '**':
  8145. return nodot + globstar(opts);
  8146. case '**/*':
  8147. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  8148. case '**/*.*':
  8149. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  8150. case '**/.*':
  8151. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  8152. default: {
  8153. const match = /^(.*?)\.(\w+)$/.exec(str);
  8154. if (!match) return;
  8155. const source = create(match[1]);
  8156. if (!source) return;
  8157. return source + DOT_LITERAL + match[2];
  8158. }
  8159. }
  8160. };
  8161. const output = utils$d.removePrefix(input, state);
  8162. let source = create(output);
  8163. if (source && opts.strictSlashes !== true) {
  8164. source += `${SLASH_LITERAL}?`;
  8165. }
  8166. return source;
  8167. };
  8168. var parse_1$1 = parse$i;
  8169. const path$s = path__default;
  8170. const scan = scan_1;
  8171. const parse$h = parse_1$1;
  8172. const utils$c = utils$f;
  8173. const constants$3 = constants$5;
  8174. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  8175. /**
  8176. * Creates a matcher function from one or more glob patterns. The
  8177. * returned function takes a string to match as its first argument,
  8178. * and returns true if the string is a match. The returned matcher
  8179. * function also takes a boolean as the second argument that, when true,
  8180. * returns an object with additional information.
  8181. *
  8182. * ```js
  8183. * const picomatch = require('picomatch');
  8184. * // picomatch(glob[, options]);
  8185. *
  8186. * const isMatch = picomatch('*.!(*a)');
  8187. * console.log(isMatch('a.a')); //=> false
  8188. * console.log(isMatch('a.b')); //=> true
  8189. * ```
  8190. * @name picomatch
  8191. * @param {String|Array} `globs` One or more glob patterns.
  8192. * @param {Object=} `options`
  8193. * @return {Function=} Returns a matcher function.
  8194. * @api public
  8195. */
  8196. const picomatch$4 = (glob, options, returnState = false) => {
  8197. if (Array.isArray(glob)) {
  8198. const fns = glob.map(input => picomatch$4(input, options, returnState));
  8199. const arrayMatcher = str => {
  8200. for (const isMatch of fns) {
  8201. const state = isMatch(str);
  8202. if (state) return state;
  8203. }
  8204. return false;
  8205. };
  8206. return arrayMatcher;
  8207. }
  8208. const isState = isObject(glob) && glob.tokens && glob.input;
  8209. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  8210. throw new TypeError('Expected pattern to be a non-empty string');
  8211. }
  8212. const opts = options || {};
  8213. const posix = utils$c.isWindows(options);
  8214. const regex = isState
  8215. ? picomatch$4.compileRe(glob, options)
  8216. : picomatch$4.makeRe(glob, options, false, true);
  8217. const state = regex.state;
  8218. delete regex.state;
  8219. let isIgnored = () => false;
  8220. if (opts.ignore) {
  8221. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  8222. isIgnored = picomatch$4(opts.ignore, ignoreOpts, returnState);
  8223. }
  8224. const matcher = (input, returnObject = false) => {
  8225. const { isMatch, match, output } = picomatch$4.test(input, regex, options, { glob, posix });
  8226. const result = { glob, state, regex, posix, input, output, match, isMatch };
  8227. if (typeof opts.onResult === 'function') {
  8228. opts.onResult(result);
  8229. }
  8230. if (isMatch === false) {
  8231. result.isMatch = false;
  8232. return returnObject ? result : false;
  8233. }
  8234. if (isIgnored(input)) {
  8235. if (typeof opts.onIgnore === 'function') {
  8236. opts.onIgnore(result);
  8237. }
  8238. result.isMatch = false;
  8239. return returnObject ? result : false;
  8240. }
  8241. if (typeof opts.onMatch === 'function') {
  8242. opts.onMatch(result);
  8243. }
  8244. return returnObject ? result : true;
  8245. };
  8246. if (returnState) {
  8247. matcher.state = state;
  8248. }
  8249. return matcher;
  8250. };
  8251. /**
  8252. * Test `input` with the given `regex`. This is used by the main
  8253. * `picomatch()` function to test the input string.
  8254. *
  8255. * ```js
  8256. * const picomatch = require('picomatch');
  8257. * // picomatch.test(input, regex[, options]);
  8258. *
  8259. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  8260. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  8261. * ```
  8262. * @param {String} `input` String to test.
  8263. * @param {RegExp} `regex`
  8264. * @return {Object} Returns an object with matching info.
  8265. * @api public
  8266. */
  8267. picomatch$4.test = (input, regex, options, { glob, posix } = {}) => {
  8268. if (typeof input !== 'string') {
  8269. throw new TypeError('Expected input to be a string');
  8270. }
  8271. if (input === '') {
  8272. return { isMatch: false, output: '' };
  8273. }
  8274. const opts = options || {};
  8275. const format = opts.format || (posix ? utils$c.toPosixSlashes : null);
  8276. let match = input === glob;
  8277. let output = (match && format) ? format(input) : input;
  8278. if (match === false) {
  8279. output = format ? format(input) : input;
  8280. match = output === glob;
  8281. }
  8282. if (match === false || opts.capture === true) {
  8283. if (opts.matchBase === true || opts.basename === true) {
  8284. match = picomatch$4.matchBase(input, regex, options, posix);
  8285. } else {
  8286. match = regex.exec(output);
  8287. }
  8288. }
  8289. return { isMatch: Boolean(match), match, output };
  8290. };
  8291. /**
  8292. * Match the basename of a filepath.
  8293. *
  8294. * ```js
  8295. * const picomatch = require('picomatch');
  8296. * // picomatch.matchBase(input, glob[, options]);
  8297. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  8298. * ```
  8299. * @param {String} `input` String to test.
  8300. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  8301. * @return {Boolean}
  8302. * @api public
  8303. */
  8304. picomatch$4.matchBase = (input, glob, options, posix = utils$c.isWindows(options)) => {
  8305. const regex = glob instanceof RegExp ? glob : picomatch$4.makeRe(glob, options);
  8306. return regex.test(path$s.basename(input));
  8307. };
  8308. /**
  8309. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  8310. *
  8311. * ```js
  8312. * const picomatch = require('picomatch');
  8313. * // picomatch.isMatch(string, patterns[, options]);
  8314. *
  8315. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  8316. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  8317. * ```
  8318. * @param {String|Array} str The string to test.
  8319. * @param {String|Array} patterns One or more glob patterns to use for matching.
  8320. * @param {Object} [options] See available [options](#options).
  8321. * @return {Boolean} Returns true if any patterns match `str`
  8322. * @api public
  8323. */
  8324. picomatch$4.isMatch = (str, patterns, options) => picomatch$4(patterns, options)(str);
  8325. /**
  8326. * Parse a glob pattern to create the source string for a regular
  8327. * expression.
  8328. *
  8329. * ```js
  8330. * const picomatch = require('picomatch');
  8331. * const result = picomatch.parse(pattern[, options]);
  8332. * ```
  8333. * @param {String} `pattern`
  8334. * @param {Object} `options`
  8335. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  8336. * @api public
  8337. */
  8338. picomatch$4.parse = (pattern, options) => {
  8339. if (Array.isArray(pattern)) return pattern.map(p => picomatch$4.parse(p, options));
  8340. return parse$h(pattern, { ...options, fastpaths: false });
  8341. };
  8342. /**
  8343. * Scan a glob pattern to separate the pattern into segments.
  8344. *
  8345. * ```js
  8346. * const picomatch = require('picomatch');
  8347. * // picomatch.scan(input[, options]);
  8348. *
  8349. * const result = picomatch.scan('!./foo/*.js');
  8350. * console.log(result);
  8351. * { prefix: '!./',
  8352. * input: '!./foo/*.js',
  8353. * start: 3,
  8354. * base: 'foo',
  8355. * glob: '*.js',
  8356. * isBrace: false,
  8357. * isBracket: false,
  8358. * isGlob: true,
  8359. * isExtglob: false,
  8360. * isGlobstar: false,
  8361. * negated: true }
  8362. * ```
  8363. * @param {String} `input` Glob pattern to scan.
  8364. * @param {Object} `options`
  8365. * @return {Object} Returns an object with
  8366. * @api public
  8367. */
  8368. picomatch$4.scan = (input, options) => scan(input, options);
  8369. /**
  8370. * Compile a regular expression from the `state` object returned by the
  8371. * [parse()](#parse) method.
  8372. *
  8373. * @param {Object} `state`
  8374. * @param {Object} `options`
  8375. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  8376. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  8377. * @return {RegExp}
  8378. * @api public
  8379. */
  8380. picomatch$4.compileRe = (state, options, returnOutput = false, returnState = false) => {
  8381. if (returnOutput === true) {
  8382. return state.output;
  8383. }
  8384. const opts = options || {};
  8385. const prepend = opts.contains ? '' : '^';
  8386. const append = opts.contains ? '' : '$';
  8387. let source = `${prepend}(?:${state.output})${append}`;
  8388. if (state && state.negated === true) {
  8389. source = `^(?!${source}).*$`;
  8390. }
  8391. const regex = picomatch$4.toRegex(source, options);
  8392. if (returnState === true) {
  8393. regex.state = state;
  8394. }
  8395. return regex;
  8396. };
  8397. /**
  8398. * Create a regular expression from a parsed glob pattern.
  8399. *
  8400. * ```js
  8401. * const picomatch = require('picomatch');
  8402. * const state = picomatch.parse('*.js');
  8403. * // picomatch.compileRe(state[, options]);
  8404. *
  8405. * console.log(picomatch.compileRe(state));
  8406. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  8407. * ```
  8408. * @param {String} `state` The object returned from the `.parse` method.
  8409. * @param {Object} `options`
  8410. * @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.
  8411. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  8412. * @return {RegExp} Returns a regex created from the given pattern.
  8413. * @api public
  8414. */
  8415. picomatch$4.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  8416. if (!input || typeof input !== 'string') {
  8417. throw new TypeError('Expected a non-empty string');
  8418. }
  8419. let parsed = { negated: false, fastpaths: true };
  8420. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  8421. parsed.output = parse$h.fastpaths(input, options);
  8422. }
  8423. if (!parsed.output) {
  8424. parsed = parse$h(input, options);
  8425. }
  8426. return picomatch$4.compileRe(parsed, options, returnOutput, returnState);
  8427. };
  8428. /**
  8429. * Create a regular expression from the given regex source string.
  8430. *
  8431. * ```js
  8432. * const picomatch = require('picomatch');
  8433. * // picomatch.toRegex(source[, options]);
  8434. *
  8435. * const { output } = picomatch.parse('*.js');
  8436. * console.log(picomatch.toRegex(output));
  8437. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  8438. * ```
  8439. * @param {String} `source` Regular expression source string.
  8440. * @param {Object} `options`
  8441. * @return {RegExp}
  8442. * @api public
  8443. */
  8444. picomatch$4.toRegex = (source, options) => {
  8445. try {
  8446. const opts = options || {};
  8447. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  8448. } catch (err) {
  8449. if (options && options.debug === true) throw err;
  8450. return /$^/;
  8451. }
  8452. };
  8453. /**
  8454. * Picomatch constants.
  8455. * @return {Object}
  8456. */
  8457. picomatch$4.constants = constants$3;
  8458. /**
  8459. * Expose "picomatch"
  8460. */
  8461. var picomatch_1 = picomatch$4;
  8462. var picomatch$3 = picomatch_1;
  8463. const util$a = require$$0__default$3;
  8464. const braces$1 = braces_1;
  8465. const picomatch$2 = picomatch$3;
  8466. const utils$b = utils$f;
  8467. const isEmptyString = val => val === '' || val === './';
  8468. /**
  8469. * Returns an array of strings that match one or more glob patterns.
  8470. *
  8471. * ```js
  8472. * const mm = require('micromatch');
  8473. * // mm(list, patterns[, options]);
  8474. *
  8475. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  8476. * //=> [ 'a.js' ]
  8477. * ```
  8478. * @param {String|Array<string>} `list` List of strings to match.
  8479. * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
  8480. * @param {Object} `options` See available [options](#options)
  8481. * @return {Array} Returns an array of matches
  8482. * @summary false
  8483. * @api public
  8484. */
  8485. const micromatch$1 = (list, patterns, options) => {
  8486. patterns = [].concat(patterns);
  8487. list = [].concat(list);
  8488. let omit = new Set();
  8489. let keep = new Set();
  8490. let items = new Set();
  8491. let negatives = 0;
  8492. let onResult = state => {
  8493. items.add(state.output);
  8494. if (options && options.onResult) {
  8495. options.onResult(state);
  8496. }
  8497. };
  8498. for (let i = 0; i < patterns.length; i++) {
  8499. let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true);
  8500. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  8501. if (negated) negatives++;
  8502. for (let item of list) {
  8503. let matched = isMatch(item, true);
  8504. let match = negated ? !matched.isMatch : matched.isMatch;
  8505. if (!match) continue;
  8506. if (negated) {
  8507. omit.add(matched.output);
  8508. } else {
  8509. omit.delete(matched.output);
  8510. keep.add(matched.output);
  8511. }
  8512. }
  8513. }
  8514. let result = negatives === patterns.length ? [...items] : [...keep];
  8515. let matches = result.filter(item => !omit.has(item));
  8516. if (options && matches.length === 0) {
  8517. if (options.failglob === true) {
  8518. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  8519. }
  8520. if (options.nonull === true || options.nullglob === true) {
  8521. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  8522. }
  8523. }
  8524. return matches;
  8525. };
  8526. /**
  8527. * Backwards compatibility
  8528. */
  8529. micromatch$1.match = micromatch$1;
  8530. /**
  8531. * Returns a matcher function from the given glob `pattern` and `options`.
  8532. * The returned function takes a string to match as its only argument and returns
  8533. * true if the string is a match.
  8534. *
  8535. * ```js
  8536. * const mm = require('micromatch');
  8537. * // mm.matcher(pattern[, options]);
  8538. *
  8539. * const isMatch = mm.matcher('*.!(*a)');
  8540. * console.log(isMatch('a.a')); //=> false
  8541. * console.log(isMatch('a.b')); //=> true
  8542. * ```
  8543. * @param {String} `pattern` Glob pattern
  8544. * @param {Object} `options`
  8545. * @return {Function} Returns a matcher function.
  8546. * @api public
  8547. */
  8548. micromatch$1.matcher = (pattern, options) => picomatch$2(pattern, options);
  8549. /**
  8550. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  8551. *
  8552. * ```js
  8553. * const mm = require('micromatch');
  8554. * // mm.isMatch(string, patterns[, options]);
  8555. *
  8556. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  8557. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  8558. * ```
  8559. * @param {String} `str` The string to test.
  8560. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8561. * @param {Object} `[options]` See available [options](#options).
  8562. * @return {Boolean} Returns true if any patterns match `str`
  8563. * @api public
  8564. */
  8565. micromatch$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
  8566. /**
  8567. * Backwards compatibility
  8568. */
  8569. micromatch$1.any = micromatch$1.isMatch;
  8570. /**
  8571. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  8572. *
  8573. * ```js
  8574. * const mm = require('micromatch');
  8575. * // mm.not(list, patterns[, options]);
  8576. *
  8577. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  8578. * //=> ['b.b', 'c.c']
  8579. * ```
  8580. * @param {Array} `list` Array of strings to match.
  8581. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  8582. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8583. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  8584. * @api public
  8585. */
  8586. micromatch$1.not = (list, patterns, options = {}) => {
  8587. patterns = [].concat(patterns).map(String);
  8588. let result = new Set();
  8589. let items = [];
  8590. let onResult = state => {
  8591. if (options.onResult) options.onResult(state);
  8592. items.push(state.output);
  8593. };
  8594. let matches = micromatch$1(list, patterns, { ...options, onResult });
  8595. for (let item of items) {
  8596. if (!matches.includes(item)) {
  8597. result.add(item);
  8598. }
  8599. }
  8600. return [...result];
  8601. };
  8602. /**
  8603. * Returns true if the given `string` contains the given pattern. Similar
  8604. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  8605. *
  8606. * ```js
  8607. * var mm = require('micromatch');
  8608. * // mm.contains(string, pattern[, options]);
  8609. *
  8610. * console.log(mm.contains('aa/bb/cc', '*b'));
  8611. * //=> true
  8612. * console.log(mm.contains('aa/bb/cc', '*d'));
  8613. * //=> false
  8614. * ```
  8615. * @param {String} `str` The string to match.
  8616. * @param {String|Array} `patterns` Glob pattern to use for matching.
  8617. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8618. * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
  8619. * @api public
  8620. */
  8621. micromatch$1.contains = (str, pattern, options) => {
  8622. if (typeof str !== 'string') {
  8623. throw new TypeError(`Expected a string: "${util$a.inspect(str)}"`);
  8624. }
  8625. if (Array.isArray(pattern)) {
  8626. return pattern.some(p => micromatch$1.contains(str, p, options));
  8627. }
  8628. if (typeof pattern === 'string') {
  8629. if (isEmptyString(str) || isEmptyString(pattern)) {
  8630. return false;
  8631. }
  8632. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  8633. return true;
  8634. }
  8635. }
  8636. return micromatch$1.isMatch(str, pattern, { ...options, contains: true });
  8637. };
  8638. /**
  8639. * Filter the keys of the given object with the given `glob` pattern
  8640. * and `options`. Does not attempt to match nested keys. If you need this feature,
  8641. * use [glob-object][] instead.
  8642. *
  8643. * ```js
  8644. * const mm = require('micromatch');
  8645. * // mm.matchKeys(object, patterns[, options]);
  8646. *
  8647. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  8648. * console.log(mm.matchKeys(obj, '*b'));
  8649. * //=> { ab: 'b' }
  8650. * ```
  8651. * @param {Object} `object` The object with keys to filter.
  8652. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8653. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8654. * @return {Object} Returns an object with only keys that match the given patterns.
  8655. * @api public
  8656. */
  8657. micromatch$1.matchKeys = (obj, patterns, options) => {
  8658. if (!utils$b.isObject(obj)) {
  8659. throw new TypeError('Expected the first argument to be an object');
  8660. }
  8661. let keys = micromatch$1(Object.keys(obj), patterns, options);
  8662. let res = {};
  8663. for (let key of keys) res[key] = obj[key];
  8664. return res;
  8665. };
  8666. /**
  8667. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  8668. *
  8669. * ```js
  8670. * const mm = require('micromatch');
  8671. * // mm.some(list, patterns[, options]);
  8672. *
  8673. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  8674. * // true
  8675. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  8676. * // false
  8677. * ```
  8678. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  8679. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8680. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8681. * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
  8682. * @api public
  8683. */
  8684. micromatch$1.some = (list, patterns, options) => {
  8685. let items = [].concat(list);
  8686. for (let pattern of [].concat(patterns)) {
  8687. let isMatch = picomatch$2(String(pattern), options);
  8688. if (items.some(item => isMatch(item))) {
  8689. return true;
  8690. }
  8691. }
  8692. return false;
  8693. };
  8694. /**
  8695. * Returns true if every string in the given `list` matches
  8696. * any of the given glob `patterns`.
  8697. *
  8698. * ```js
  8699. * const mm = require('micromatch');
  8700. * // mm.every(list, patterns[, options]);
  8701. *
  8702. * console.log(mm.every('foo.js', ['foo.js']));
  8703. * // true
  8704. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  8705. * // true
  8706. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  8707. * // false
  8708. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  8709. * // false
  8710. * ```
  8711. * @param {String|Array} `list` The string or array of strings to test.
  8712. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8713. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8714. * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
  8715. * @api public
  8716. */
  8717. micromatch$1.every = (list, patterns, options) => {
  8718. let items = [].concat(list);
  8719. for (let pattern of [].concat(patterns)) {
  8720. let isMatch = picomatch$2(String(pattern), options);
  8721. if (!items.every(item => isMatch(item))) {
  8722. return false;
  8723. }
  8724. }
  8725. return true;
  8726. };
  8727. /**
  8728. * Returns true if **all** of the given `patterns` match
  8729. * the specified string.
  8730. *
  8731. * ```js
  8732. * const mm = require('micromatch');
  8733. * // mm.all(string, patterns[, options]);
  8734. *
  8735. * console.log(mm.all('foo.js', ['foo.js']));
  8736. * // true
  8737. *
  8738. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  8739. * // false
  8740. *
  8741. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  8742. * // true
  8743. *
  8744. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  8745. * // true
  8746. * ```
  8747. * @param {String|Array} `str` The string to test.
  8748. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8749. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8750. * @return {Boolean} Returns true if any patterns match `str`
  8751. * @api public
  8752. */
  8753. micromatch$1.all = (str, patterns, options) => {
  8754. if (typeof str !== 'string') {
  8755. throw new TypeError(`Expected a string: "${util$a.inspect(str)}"`);
  8756. }
  8757. return [].concat(patterns).every(p => picomatch$2(p, options)(str));
  8758. };
  8759. /**
  8760. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  8761. *
  8762. * ```js
  8763. * const mm = require('micromatch');
  8764. * // mm.capture(pattern, string[, options]);
  8765. *
  8766. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  8767. * //=> ['foo']
  8768. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  8769. * //=> null
  8770. * ```
  8771. * @param {String} `glob` Glob pattern to use for matching.
  8772. * @param {String} `input` String to match
  8773. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8774. * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  8775. * @api public
  8776. */
  8777. micromatch$1.capture = (glob, input, options) => {
  8778. let posix = utils$b.isWindows(options);
  8779. let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true });
  8780. let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input);
  8781. if (match) {
  8782. return match.slice(1).map(v => v === void 0 ? '' : v);
  8783. }
  8784. };
  8785. /**
  8786. * Create a regular expression from the given glob `pattern`.
  8787. *
  8788. * ```js
  8789. * const mm = require('micromatch');
  8790. * // mm.makeRe(pattern[, options]);
  8791. *
  8792. * console.log(mm.makeRe('*.js'));
  8793. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  8794. * ```
  8795. * @param {String} `pattern` A glob pattern to convert to regex.
  8796. * @param {Object} `options`
  8797. * @return {RegExp} Returns a regex created from the given pattern.
  8798. * @api public
  8799. */
  8800. micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args);
  8801. /**
  8802. * Scan a glob pattern to separate the pattern into segments. Used
  8803. * by the [split](#split) method.
  8804. *
  8805. * ```js
  8806. * const mm = require('micromatch');
  8807. * const state = mm.scan(pattern[, options]);
  8808. * ```
  8809. * @param {String} `pattern`
  8810. * @param {Object} `options`
  8811. * @return {Object} Returns an object with
  8812. * @api public
  8813. */
  8814. micromatch$1.scan = (...args) => picomatch$2.scan(...args);
  8815. /**
  8816. * Parse a glob pattern to create the source string for a regular
  8817. * expression.
  8818. *
  8819. * ```js
  8820. * const mm = require('micromatch');
  8821. * const state = mm(pattern[, options]);
  8822. * ```
  8823. * @param {String} `glob`
  8824. * @param {Object} `options`
  8825. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  8826. * @api public
  8827. */
  8828. micromatch$1.parse = (patterns, options) => {
  8829. let res = [];
  8830. for (let pattern of [].concat(patterns || [])) {
  8831. for (let str of braces$1(String(pattern), options)) {
  8832. res.push(picomatch$2.parse(str, options));
  8833. }
  8834. }
  8835. return res;
  8836. };
  8837. /**
  8838. * Process the given brace `pattern`.
  8839. *
  8840. * ```js
  8841. * const { braces } = require('micromatch');
  8842. * console.log(braces('foo/{a,b,c}/bar'));
  8843. * //=> [ 'foo/(a|b|c)/bar' ]
  8844. *
  8845. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  8846. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  8847. * ```
  8848. * @param {String} `pattern` String with brace pattern to process.
  8849. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  8850. * @return {Array}
  8851. * @api public
  8852. */
  8853. micromatch$1.braces = (pattern, options) => {
  8854. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  8855. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  8856. return [pattern];
  8857. }
  8858. return braces$1(pattern, options);
  8859. };
  8860. /**
  8861. * Expand braces
  8862. */
  8863. micromatch$1.braceExpand = (pattern, options) => {
  8864. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  8865. return micromatch$1.braces(pattern, { ...options, expand: true });
  8866. };
  8867. /**
  8868. * Expose micromatch
  8869. */
  8870. var micromatch_1 = micromatch$1;
  8871. Object.defineProperty(pattern$1, "__esModule", { value: true });
  8872. pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
  8873. const path$r = path__default;
  8874. const globParent$1 = globParent$2;
  8875. const micromatch = micromatch_1;
  8876. const GLOBSTAR$2 = '**';
  8877. const ESCAPE_SYMBOL = '\\';
  8878. const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
  8879. const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
  8880. const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
  8881. const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
  8882. const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
  8883. function isStaticPattern(pattern, options = {}) {
  8884. return !isDynamicPattern(pattern, options);
  8885. }
  8886. pattern$1.isStaticPattern = isStaticPattern;
  8887. function isDynamicPattern(pattern, options = {}) {
  8888. /**
  8889. * A special case with an empty string is necessary for matching patterns that start with a forward slash.
  8890. * An empty string cannot be a dynamic pattern.
  8891. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
  8892. */
  8893. if (pattern === '') {
  8894. return false;
  8895. }
  8896. /**
  8897. * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
  8898. * filepath directly (without read directory).
  8899. */
  8900. if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
  8901. return true;
  8902. }
  8903. if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
  8904. return true;
  8905. }
  8906. if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
  8907. return true;
  8908. }
  8909. if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
  8910. return true;
  8911. }
  8912. return false;
  8913. }
  8914. pattern$1.isDynamicPattern = isDynamicPattern;
  8915. function convertToPositivePattern(pattern) {
  8916. return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
  8917. }
  8918. pattern$1.convertToPositivePattern = convertToPositivePattern;
  8919. function convertToNegativePattern(pattern) {
  8920. return '!' + pattern;
  8921. }
  8922. pattern$1.convertToNegativePattern = convertToNegativePattern;
  8923. function isNegativePattern(pattern) {
  8924. return pattern.startsWith('!') && pattern[1] !== '(';
  8925. }
  8926. pattern$1.isNegativePattern = isNegativePattern;
  8927. function isPositivePattern(pattern) {
  8928. return !isNegativePattern(pattern);
  8929. }
  8930. pattern$1.isPositivePattern = isPositivePattern;
  8931. function getNegativePatterns(patterns) {
  8932. return patterns.filter(isNegativePattern);
  8933. }
  8934. pattern$1.getNegativePatterns = getNegativePatterns;
  8935. function getPositivePatterns$1(patterns) {
  8936. return patterns.filter(isPositivePattern);
  8937. }
  8938. pattern$1.getPositivePatterns = getPositivePatterns$1;
  8939. /**
  8940. * Returns patterns that can be applied inside the current directory.
  8941. *
  8942. * @example
  8943. * // ['./*', '*', 'a/*']
  8944. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  8945. */
  8946. function getPatternsInsideCurrentDirectory(patterns) {
  8947. return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
  8948. }
  8949. pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
  8950. /**
  8951. * Returns patterns to be expanded relative to (outside) the current directory.
  8952. *
  8953. * @example
  8954. * // ['../*', './../*']
  8955. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  8956. */
  8957. function getPatternsOutsideCurrentDirectory(patterns) {
  8958. return patterns.filter(isPatternRelatedToParentDirectory);
  8959. }
  8960. pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
  8961. function isPatternRelatedToParentDirectory(pattern) {
  8962. return pattern.startsWith('..') || pattern.startsWith('./..');
  8963. }
  8964. pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
  8965. function getBaseDirectory(pattern) {
  8966. return globParent$1(pattern, { flipBackslashes: false });
  8967. }
  8968. pattern$1.getBaseDirectory = getBaseDirectory;
  8969. function hasGlobStar(pattern) {
  8970. return pattern.includes(GLOBSTAR$2);
  8971. }
  8972. pattern$1.hasGlobStar = hasGlobStar;
  8973. function endsWithSlashGlobStar(pattern) {
  8974. return pattern.endsWith('/' + GLOBSTAR$2);
  8975. }
  8976. pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
  8977. function isAffectDepthOfReadingPattern(pattern) {
  8978. const basename = path$r.basename(pattern);
  8979. return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
  8980. }
  8981. pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
  8982. function expandPatternsWithBraceExpansion(patterns) {
  8983. return patterns.reduce((collection, pattern) => {
  8984. return collection.concat(expandBraceExpansion(pattern));
  8985. }, []);
  8986. }
  8987. pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
  8988. function expandBraceExpansion(pattern) {
  8989. return micromatch.braces(pattern, {
  8990. expand: true,
  8991. nodupes: true
  8992. });
  8993. }
  8994. pattern$1.expandBraceExpansion = expandBraceExpansion;
  8995. function getPatternParts(pattern, options) {
  8996. let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
  8997. /**
  8998. * The scan method returns an empty array in some cases.
  8999. * See micromatch/picomatch#58 for more details.
  9000. */
  9001. if (parts.length === 0) {
  9002. parts = [pattern];
  9003. }
  9004. /**
  9005. * The scan method does not return an empty part for the pattern with a forward slash.
  9006. * This is another part of micromatch/picomatch#58.
  9007. */
  9008. if (parts[0].startsWith('/')) {
  9009. parts[0] = parts[0].slice(1);
  9010. parts.unshift('');
  9011. }
  9012. return parts;
  9013. }
  9014. pattern$1.getPatternParts = getPatternParts;
  9015. function makeRe$1(pattern, options) {
  9016. return micromatch.makeRe(pattern, options);
  9017. }
  9018. pattern$1.makeRe = makeRe$1;
  9019. function convertPatternsToRe(patterns, options) {
  9020. return patterns.map((pattern) => makeRe$1(pattern, options));
  9021. }
  9022. pattern$1.convertPatternsToRe = convertPatternsToRe;
  9023. function matchAny(entry, patternsRe) {
  9024. return patternsRe.some((patternRe) => patternRe.test(entry));
  9025. }
  9026. pattern$1.matchAny = matchAny;
  9027. var stream$7 = {};
  9028. /*
  9029. * merge2
  9030. * https://github.com/teambition/merge2
  9031. *
  9032. * Copyright (c) 2014-2020 Teambition
  9033. * Licensed under the MIT license.
  9034. */
  9035. const Stream = require$$0__default$2;
  9036. const PassThrough$1 = Stream.PassThrough;
  9037. const slice$1 = Array.prototype.slice;
  9038. var merge2_1 = merge2$2;
  9039. function merge2$2 () {
  9040. const streamsQueue = [];
  9041. const args = slice$1.call(arguments);
  9042. let merging = false;
  9043. let options = args[args.length - 1];
  9044. if (options && !Array.isArray(options) && options.pipe == null) {
  9045. args.pop();
  9046. } else {
  9047. options = {};
  9048. }
  9049. const doEnd = options.end !== false;
  9050. const doPipeError = options.pipeError === true;
  9051. if (options.objectMode == null) {
  9052. options.objectMode = true;
  9053. }
  9054. if (options.highWaterMark == null) {
  9055. options.highWaterMark = 64 * 1024;
  9056. }
  9057. const mergedStream = PassThrough$1(options);
  9058. function addStream () {
  9059. for (let i = 0, len = arguments.length; i < len; i++) {
  9060. streamsQueue.push(pauseStreams(arguments[i], options));
  9061. }
  9062. mergeStream();
  9063. return this
  9064. }
  9065. function mergeStream () {
  9066. if (merging) {
  9067. return
  9068. }
  9069. merging = true;
  9070. let streams = streamsQueue.shift();
  9071. if (!streams) {
  9072. process.nextTick(endStream);
  9073. return
  9074. }
  9075. if (!Array.isArray(streams)) {
  9076. streams = [streams];
  9077. }
  9078. let pipesCount = streams.length + 1;
  9079. function next () {
  9080. if (--pipesCount > 0) {
  9081. return
  9082. }
  9083. merging = false;
  9084. mergeStream();
  9085. }
  9086. function pipe (stream) {
  9087. function onend () {
  9088. stream.removeListener('merge2UnpipeEnd', onend);
  9089. stream.removeListener('end', onend);
  9090. if (doPipeError) {
  9091. stream.removeListener('error', onerror);
  9092. }
  9093. next();
  9094. }
  9095. function onerror (err) {
  9096. mergedStream.emit('error', err);
  9097. }
  9098. // skip ended stream
  9099. if (stream._readableState.endEmitted) {
  9100. return next()
  9101. }
  9102. stream.on('merge2UnpipeEnd', onend);
  9103. stream.on('end', onend);
  9104. if (doPipeError) {
  9105. stream.on('error', onerror);
  9106. }
  9107. stream.pipe(mergedStream, { end: false });
  9108. // compatible for old stream
  9109. stream.resume();
  9110. }
  9111. for (let i = 0; i < streams.length; i++) {
  9112. pipe(streams[i]);
  9113. }
  9114. next();
  9115. }
  9116. function endStream () {
  9117. merging = false;
  9118. // emit 'queueDrain' when all streams merged.
  9119. mergedStream.emit('queueDrain');
  9120. if (doEnd) {
  9121. mergedStream.end();
  9122. }
  9123. }
  9124. mergedStream.setMaxListeners(0);
  9125. mergedStream.add = addStream;
  9126. mergedStream.on('unpipe', function (stream) {
  9127. stream.emit('merge2UnpipeEnd');
  9128. });
  9129. if (args.length) {
  9130. addStream.apply(null, args);
  9131. }
  9132. return mergedStream
  9133. }
  9134. // check and pause streams for pipe.
  9135. function pauseStreams (streams, options) {
  9136. if (!Array.isArray(streams)) {
  9137. // Backwards-compat with old-style streams
  9138. if (!streams._readableState && streams.pipe) {
  9139. streams = streams.pipe(PassThrough$1(options));
  9140. }
  9141. if (!streams._readableState || !streams.pause || !streams.pipe) {
  9142. throw new Error('Only readable stream can be merged.')
  9143. }
  9144. streams.pause();
  9145. } else {
  9146. for (let i = 0, len = streams.length; i < len; i++) {
  9147. streams[i] = pauseStreams(streams[i], options);
  9148. }
  9149. }
  9150. return streams
  9151. }
  9152. Object.defineProperty(stream$7, "__esModule", { value: true });
  9153. stream$7.merge = void 0;
  9154. const merge2$1 = merge2_1;
  9155. function merge$2(streams) {
  9156. const mergedStream = merge2$1(streams);
  9157. streams.forEach((stream) => {
  9158. stream.once('error', (error) => mergedStream.emit('error', error));
  9159. });
  9160. mergedStream.once('close', () => propagateCloseEventToSources(streams));
  9161. mergedStream.once('end', () => propagateCloseEventToSources(streams));
  9162. return mergedStream;
  9163. }
  9164. stream$7.merge = merge$2;
  9165. function propagateCloseEventToSources(streams) {
  9166. streams.forEach((stream) => stream.emit('close'));
  9167. }
  9168. var string$2 = {};
  9169. Object.defineProperty(string$2, "__esModule", { value: true });
  9170. string$2.isEmpty = string$2.isString = void 0;
  9171. function isString$1(input) {
  9172. return typeof input === 'string';
  9173. }
  9174. string$2.isString = isString$1;
  9175. function isEmpty(input) {
  9176. return input === '';
  9177. }
  9178. string$2.isEmpty = isEmpty;
  9179. Object.defineProperty(utils$k, "__esModule", { value: true });
  9180. utils$k.string = utils$k.stream = utils$k.pattern = utils$k.path = utils$k.fs = utils$k.errno = utils$k.array = void 0;
  9181. const array = array$1;
  9182. utils$k.array = array;
  9183. const errno = errno$1;
  9184. utils$k.errno = errno;
  9185. const fs$t = fs$u;
  9186. utils$k.fs = fs$t;
  9187. const path$q = path$v;
  9188. utils$k.path = path$q;
  9189. const pattern = pattern$1;
  9190. utils$k.pattern = pattern;
  9191. const stream$6 = stream$7;
  9192. utils$k.stream = stream$6;
  9193. const string$1 = string$2;
  9194. utils$k.string = string$1;
  9195. Object.defineProperty(tasks, "__esModule", { value: true });
  9196. tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
  9197. const utils$a = utils$k;
  9198. function generate(patterns, settings) {
  9199. const positivePatterns = getPositivePatterns(patterns);
  9200. const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
  9201. const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings));
  9202. const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings));
  9203. const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
  9204. const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
  9205. return staticTasks.concat(dynamicTasks);
  9206. }
  9207. tasks.generate = generate;
  9208. /**
  9209. * Returns tasks grouped by basic pattern directories.
  9210. *
  9211. * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
  9212. * This is necessary because directory traversal starts at the base directory and goes deeper.
  9213. */
  9214. function convertPatternsToTasks(positive, negative, dynamic) {
  9215. const tasks = [];
  9216. const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive);
  9217. const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive);
  9218. const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
  9219. const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
  9220. tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
  9221. /*
  9222. * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
  9223. * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
  9224. */
  9225. if ('.' in insideCurrentDirectoryGroup) {
  9226. tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
  9227. }
  9228. else {
  9229. tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
  9230. }
  9231. return tasks;
  9232. }
  9233. tasks.convertPatternsToTasks = convertPatternsToTasks;
  9234. function getPositivePatterns(patterns) {
  9235. return utils$a.pattern.getPositivePatterns(patterns);
  9236. }
  9237. tasks.getPositivePatterns = getPositivePatterns;
  9238. function getNegativePatternsAsPositive(patterns, ignore) {
  9239. const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore);
  9240. const positive = negative.map(utils$a.pattern.convertToPositivePattern);
  9241. return positive;
  9242. }
  9243. tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
  9244. function groupPatternsByBaseDirectory(patterns) {
  9245. const group = {};
  9246. return patterns.reduce((collection, pattern) => {
  9247. const base = utils$a.pattern.getBaseDirectory(pattern);
  9248. if (base in collection) {
  9249. collection[base].push(pattern);
  9250. }
  9251. else {
  9252. collection[base] = [pattern];
  9253. }
  9254. return collection;
  9255. }, group);
  9256. }
  9257. tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
  9258. function convertPatternGroupsToTasks(positive, negative, dynamic) {
  9259. return Object.keys(positive).map((base) => {
  9260. return convertPatternGroupToTask(base, positive[base], negative, dynamic);
  9261. });
  9262. }
  9263. tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
  9264. function convertPatternGroupToTask(base, positive, negative, dynamic) {
  9265. return {
  9266. dynamic,
  9267. positive,
  9268. negative,
  9269. base,
  9270. patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern))
  9271. };
  9272. }
  9273. tasks.convertPatternGroupToTask = convertPatternGroupToTask;
  9274. var async$6 = {};
  9275. var stream$5 = {};
  9276. var out$3 = {};
  9277. var async$5 = {};
  9278. Object.defineProperty(async$5, "__esModule", { value: true });
  9279. async$5.read = void 0;
  9280. function read$4(path, settings, callback) {
  9281. settings.fs.lstat(path, (lstatError, lstat) => {
  9282. if (lstatError !== null) {
  9283. callFailureCallback$2(callback, lstatError);
  9284. return;
  9285. }
  9286. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  9287. callSuccessCallback$2(callback, lstat);
  9288. return;
  9289. }
  9290. settings.fs.stat(path, (statError, stat) => {
  9291. if (statError !== null) {
  9292. if (settings.throwErrorOnBrokenSymbolicLink) {
  9293. callFailureCallback$2(callback, statError);
  9294. return;
  9295. }
  9296. callSuccessCallback$2(callback, lstat);
  9297. return;
  9298. }
  9299. if (settings.markSymbolicLink) {
  9300. stat.isSymbolicLink = () => true;
  9301. }
  9302. callSuccessCallback$2(callback, stat);
  9303. });
  9304. });
  9305. }
  9306. async$5.read = read$4;
  9307. function callFailureCallback$2(callback, error) {
  9308. callback(error);
  9309. }
  9310. function callSuccessCallback$2(callback, result) {
  9311. callback(null, result);
  9312. }
  9313. var sync$b = {};
  9314. Object.defineProperty(sync$b, "__esModule", { value: true });
  9315. sync$b.read = void 0;
  9316. function read$3(path, settings) {
  9317. const lstat = settings.fs.lstatSync(path);
  9318. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  9319. return lstat;
  9320. }
  9321. try {
  9322. const stat = settings.fs.statSync(path);
  9323. if (settings.markSymbolicLink) {
  9324. stat.isSymbolicLink = () => true;
  9325. }
  9326. return stat;
  9327. }
  9328. catch (error) {
  9329. if (!settings.throwErrorOnBrokenSymbolicLink) {
  9330. return lstat;
  9331. }
  9332. throw error;
  9333. }
  9334. }
  9335. sync$b.read = read$3;
  9336. var settings$3 = {};
  9337. var fs$s = {};
  9338. (function (exports) {
  9339. Object.defineProperty(exports, "__esModule", { value: true });
  9340. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  9341. const fs = fs__default;
  9342. exports.FILE_SYSTEM_ADAPTER = {
  9343. lstat: fs.lstat,
  9344. stat: fs.stat,
  9345. lstatSync: fs.lstatSync,
  9346. statSync: fs.statSync
  9347. };
  9348. function createFileSystemAdapter(fsMethods) {
  9349. if (fsMethods === undefined) {
  9350. return exports.FILE_SYSTEM_ADAPTER;
  9351. }
  9352. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  9353. }
  9354. exports.createFileSystemAdapter = createFileSystemAdapter;
  9355. }(fs$s));
  9356. Object.defineProperty(settings$3, "__esModule", { value: true });
  9357. const fs$r = fs$s;
  9358. class Settings$2 {
  9359. constructor(_options = {}) {
  9360. this._options = _options;
  9361. this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
  9362. this.fs = fs$r.createFileSystemAdapter(this._options.fs);
  9363. this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
  9364. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  9365. }
  9366. _getValue(option, value) {
  9367. return option !== null && option !== void 0 ? option : value;
  9368. }
  9369. }
  9370. settings$3.default = Settings$2;
  9371. Object.defineProperty(out$3, "__esModule", { value: true });
  9372. out$3.statSync = out$3.stat = out$3.Settings = void 0;
  9373. const async$4 = async$5;
  9374. const sync$a = sync$b;
  9375. const settings_1$3 = settings$3;
  9376. out$3.Settings = settings_1$3.default;
  9377. function stat$5(path, optionsOrSettingsOrCallback, callback) {
  9378. if (typeof optionsOrSettingsOrCallback === 'function') {
  9379. async$4.read(path, getSettings$2(), optionsOrSettingsOrCallback);
  9380. return;
  9381. }
  9382. async$4.read(path, getSettings$2(optionsOrSettingsOrCallback), callback);
  9383. }
  9384. out$3.stat = stat$5;
  9385. function statSync(path, optionsOrSettings) {
  9386. const settings = getSettings$2(optionsOrSettings);
  9387. return sync$a.read(path, settings);
  9388. }
  9389. out$3.statSync = statSync;
  9390. function getSettings$2(settingsOrOptions = {}) {
  9391. if (settingsOrOptions instanceof settings_1$3.default) {
  9392. return settingsOrOptions;
  9393. }
  9394. return new settings_1$3.default(settingsOrOptions);
  9395. }
  9396. var out$2 = {};
  9397. var async$3 = {};
  9398. var async$2 = {};
  9399. var out$1 = {};
  9400. var async$1 = {};
  9401. /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  9402. let promise$1;
  9403. var queueMicrotask_1 = typeof queueMicrotask === 'function'
  9404. ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
  9405. // reuse resolved promise, and allocate it lazily
  9406. : cb => (promise$1 || (promise$1 = Promise.resolve()))
  9407. .then(cb)
  9408. .catch(err => setTimeout(() => { throw err }, 0));
  9409. /*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  9410. var runParallel_1 = runParallel;
  9411. const queueMicrotask$1 = queueMicrotask_1;
  9412. function runParallel (tasks, cb) {
  9413. let results, pending, keys;
  9414. let isSync = true;
  9415. if (Array.isArray(tasks)) {
  9416. results = [];
  9417. pending = tasks.length;
  9418. } else {
  9419. keys = Object.keys(tasks);
  9420. results = {};
  9421. pending = keys.length;
  9422. }
  9423. function done (err) {
  9424. function end () {
  9425. if (cb) cb(err, results);
  9426. cb = null;
  9427. }
  9428. if (isSync) queueMicrotask$1(end);
  9429. else end();
  9430. }
  9431. function each (i, err, result) {
  9432. results[i] = result;
  9433. if (--pending === 0 || err) {
  9434. done(err);
  9435. }
  9436. }
  9437. if (!pending) {
  9438. // empty
  9439. done(null);
  9440. } else if (keys) {
  9441. // object
  9442. keys.forEach(function (key) {
  9443. tasks[key](function (err, result) { each(key, err, result); });
  9444. });
  9445. } else {
  9446. // array
  9447. tasks.forEach(function (task, i) {
  9448. task(function (err, result) { each(i, err, result); });
  9449. });
  9450. }
  9451. isSync = false;
  9452. }
  9453. var constants$2 = {};
  9454. Object.defineProperty(constants$2, "__esModule", { value: true });
  9455. constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
  9456. const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
  9457. if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
  9458. throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
  9459. }
  9460. const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
  9461. const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
  9462. const SUPPORTED_MAJOR_VERSION = 10;
  9463. const SUPPORTED_MINOR_VERSION = 10;
  9464. const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
  9465. const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
  9466. /**
  9467. * IS `true` for Node.js 10.10 and greater.
  9468. */
  9469. constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
  9470. var utils$9 = {};
  9471. var fs$q = {};
  9472. Object.defineProperty(fs$q, "__esModule", { value: true });
  9473. fs$q.createDirentFromStats = void 0;
  9474. class DirentFromStats {
  9475. constructor(name, stats) {
  9476. this.name = name;
  9477. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  9478. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  9479. this.isDirectory = stats.isDirectory.bind(stats);
  9480. this.isFIFO = stats.isFIFO.bind(stats);
  9481. this.isFile = stats.isFile.bind(stats);
  9482. this.isSocket = stats.isSocket.bind(stats);
  9483. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  9484. }
  9485. }
  9486. function createDirentFromStats(name, stats) {
  9487. return new DirentFromStats(name, stats);
  9488. }
  9489. fs$q.createDirentFromStats = createDirentFromStats;
  9490. Object.defineProperty(utils$9, "__esModule", { value: true });
  9491. utils$9.fs = void 0;
  9492. const fs$p = fs$q;
  9493. utils$9.fs = fs$p;
  9494. var common$d = {};
  9495. Object.defineProperty(common$d, "__esModule", { value: true });
  9496. common$d.joinPathSegments = void 0;
  9497. function joinPathSegments$1(a, b, separator) {
  9498. /**
  9499. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  9500. */
  9501. if (a.endsWith(separator)) {
  9502. return a + b;
  9503. }
  9504. return a + separator + b;
  9505. }
  9506. common$d.joinPathSegments = joinPathSegments$1;
  9507. Object.defineProperty(async$1, "__esModule", { value: true });
  9508. async$1.readdir = async$1.readdirWithFileTypes = async$1.read = void 0;
  9509. const fsStat$5 = out$3;
  9510. const rpl = runParallel_1;
  9511. const constants_1$1 = constants$2;
  9512. const utils$8 = utils$9;
  9513. const common$c = common$d;
  9514. function read$2(directory, settings, callback) {
  9515. if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  9516. readdirWithFileTypes$1(directory, settings, callback);
  9517. return;
  9518. }
  9519. readdir$3(directory, settings, callback);
  9520. }
  9521. async$1.read = read$2;
  9522. function readdirWithFileTypes$1(directory, settings, callback) {
  9523. settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
  9524. if (readdirError !== null) {
  9525. callFailureCallback$1(callback, readdirError);
  9526. return;
  9527. }
  9528. const entries = dirents.map((dirent) => ({
  9529. dirent,
  9530. name: dirent.name,
  9531. path: common$c.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  9532. }));
  9533. if (!settings.followSymbolicLinks) {
  9534. callSuccessCallback$1(callback, entries);
  9535. return;
  9536. }
  9537. const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
  9538. rpl(tasks, (rplError, rplEntries) => {
  9539. if (rplError !== null) {
  9540. callFailureCallback$1(callback, rplError);
  9541. return;
  9542. }
  9543. callSuccessCallback$1(callback, rplEntries);
  9544. });
  9545. });
  9546. }
  9547. async$1.readdirWithFileTypes = readdirWithFileTypes$1;
  9548. function makeRplTaskEntry(entry, settings) {
  9549. return (done) => {
  9550. if (!entry.dirent.isSymbolicLink()) {
  9551. done(null, entry);
  9552. return;
  9553. }
  9554. settings.fs.stat(entry.path, (statError, stats) => {
  9555. if (statError !== null) {
  9556. if (settings.throwErrorOnBrokenSymbolicLink) {
  9557. done(statError);
  9558. return;
  9559. }
  9560. done(null, entry);
  9561. return;
  9562. }
  9563. entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats);
  9564. done(null, entry);
  9565. });
  9566. };
  9567. }
  9568. function readdir$3(directory, settings, callback) {
  9569. settings.fs.readdir(directory, (readdirError, names) => {
  9570. if (readdirError !== null) {
  9571. callFailureCallback$1(callback, readdirError);
  9572. return;
  9573. }
  9574. const tasks = names.map((name) => {
  9575. const path = common$c.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  9576. return (done) => {
  9577. fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => {
  9578. if (error !== null) {
  9579. done(error);
  9580. return;
  9581. }
  9582. const entry = {
  9583. name,
  9584. path,
  9585. dirent: utils$8.fs.createDirentFromStats(name, stats)
  9586. };
  9587. if (settings.stats) {
  9588. entry.stats = stats;
  9589. }
  9590. done(null, entry);
  9591. });
  9592. };
  9593. });
  9594. rpl(tasks, (rplError, entries) => {
  9595. if (rplError !== null) {
  9596. callFailureCallback$1(callback, rplError);
  9597. return;
  9598. }
  9599. callSuccessCallback$1(callback, entries);
  9600. });
  9601. });
  9602. }
  9603. async$1.readdir = readdir$3;
  9604. function callFailureCallback$1(callback, error) {
  9605. callback(error);
  9606. }
  9607. function callSuccessCallback$1(callback, result) {
  9608. callback(null, result);
  9609. }
  9610. var sync$9 = {};
  9611. Object.defineProperty(sync$9, "__esModule", { value: true });
  9612. sync$9.readdir = sync$9.readdirWithFileTypes = sync$9.read = void 0;
  9613. const fsStat$4 = out$3;
  9614. const constants_1 = constants$2;
  9615. const utils$7 = utils$9;
  9616. const common$b = common$d;
  9617. function read$1(directory, settings) {
  9618. if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  9619. return readdirWithFileTypes(directory, settings);
  9620. }
  9621. return readdir$2(directory, settings);
  9622. }
  9623. sync$9.read = read$1;
  9624. function readdirWithFileTypes(directory, settings) {
  9625. const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
  9626. return dirents.map((dirent) => {
  9627. const entry = {
  9628. dirent,
  9629. name: dirent.name,
  9630. path: common$b.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  9631. };
  9632. if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
  9633. try {
  9634. const stats = settings.fs.statSync(entry.path);
  9635. entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats);
  9636. }
  9637. catch (error) {
  9638. if (settings.throwErrorOnBrokenSymbolicLink) {
  9639. throw error;
  9640. }
  9641. }
  9642. }
  9643. return entry;
  9644. });
  9645. }
  9646. sync$9.readdirWithFileTypes = readdirWithFileTypes;
  9647. function readdir$2(directory, settings) {
  9648. const names = settings.fs.readdirSync(directory);
  9649. return names.map((name) => {
  9650. const entryPath = common$b.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  9651. const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings);
  9652. const entry = {
  9653. name,
  9654. path: entryPath,
  9655. dirent: utils$7.fs.createDirentFromStats(name, stats)
  9656. };
  9657. if (settings.stats) {
  9658. entry.stats = stats;
  9659. }
  9660. return entry;
  9661. });
  9662. }
  9663. sync$9.readdir = readdir$2;
  9664. var settings$2 = {};
  9665. var fs$o = {};
  9666. (function (exports) {
  9667. Object.defineProperty(exports, "__esModule", { value: true });
  9668. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  9669. const fs = fs__default;
  9670. exports.FILE_SYSTEM_ADAPTER = {
  9671. lstat: fs.lstat,
  9672. stat: fs.stat,
  9673. lstatSync: fs.lstatSync,
  9674. statSync: fs.statSync,
  9675. readdir: fs.readdir,
  9676. readdirSync: fs.readdirSync
  9677. };
  9678. function createFileSystemAdapter(fsMethods) {
  9679. if (fsMethods === undefined) {
  9680. return exports.FILE_SYSTEM_ADAPTER;
  9681. }
  9682. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  9683. }
  9684. exports.createFileSystemAdapter = createFileSystemAdapter;
  9685. }(fs$o));
  9686. Object.defineProperty(settings$2, "__esModule", { value: true });
  9687. const path$p = path__default;
  9688. const fsStat$3 = out$3;
  9689. const fs$n = fs$o;
  9690. class Settings$1 {
  9691. constructor(_options = {}) {
  9692. this._options = _options;
  9693. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
  9694. this.fs = fs$n.createFileSystemAdapter(this._options.fs);
  9695. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$p.sep);
  9696. this.stats = this._getValue(this._options.stats, false);
  9697. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  9698. this.fsStatSettings = new fsStat$3.Settings({
  9699. followSymbolicLink: this.followSymbolicLinks,
  9700. fs: this.fs,
  9701. throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
  9702. });
  9703. }
  9704. _getValue(option, value) {
  9705. return option !== null && option !== void 0 ? option : value;
  9706. }
  9707. }
  9708. settings$2.default = Settings$1;
  9709. Object.defineProperty(out$1, "__esModule", { value: true });
  9710. out$1.Settings = out$1.scandirSync = out$1.scandir = void 0;
  9711. const async = async$1;
  9712. const sync$8 = sync$9;
  9713. const settings_1$2 = settings$2;
  9714. out$1.Settings = settings_1$2.default;
  9715. function scandir(path, optionsOrSettingsOrCallback, callback) {
  9716. if (typeof optionsOrSettingsOrCallback === 'function') {
  9717. async.read(path, getSettings$1(), optionsOrSettingsOrCallback);
  9718. return;
  9719. }
  9720. async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback);
  9721. }
  9722. out$1.scandir = scandir;
  9723. function scandirSync(path, optionsOrSettings) {
  9724. const settings = getSettings$1(optionsOrSettings);
  9725. return sync$8.read(path, settings);
  9726. }
  9727. out$1.scandirSync = scandirSync;
  9728. function getSettings$1(settingsOrOptions = {}) {
  9729. if (settingsOrOptions instanceof settings_1$2.default) {
  9730. return settingsOrOptions;
  9731. }
  9732. return new settings_1$2.default(settingsOrOptions);
  9733. }
  9734. var queue = {exports: {}};
  9735. function reusify$1 (Constructor) {
  9736. var head = new Constructor();
  9737. var tail = head;
  9738. function get () {
  9739. var current = head;
  9740. if (current.next) {
  9741. head = current.next;
  9742. } else {
  9743. head = new Constructor();
  9744. tail = head;
  9745. }
  9746. current.next = null;
  9747. return current
  9748. }
  9749. function release (obj) {
  9750. tail.next = obj;
  9751. tail = obj;
  9752. }
  9753. return {
  9754. get: get,
  9755. release: release
  9756. }
  9757. }
  9758. var reusify_1 = reusify$1;
  9759. /* eslint-disable no-var */
  9760. var reusify = reusify_1;
  9761. function fastqueue (context, worker, concurrency) {
  9762. if (typeof context === 'function') {
  9763. concurrency = worker;
  9764. worker = context;
  9765. context = null;
  9766. }
  9767. if (concurrency < 1) {
  9768. throw new Error('fastqueue concurrency must be greater than 1')
  9769. }
  9770. var cache = reusify(Task);
  9771. var queueHead = null;
  9772. var queueTail = null;
  9773. var _running = 0;
  9774. var errorHandler = null;
  9775. var self = {
  9776. push: push,
  9777. drain: noop$4,
  9778. saturated: noop$4,
  9779. pause: pause,
  9780. paused: false,
  9781. concurrency: concurrency,
  9782. running: running,
  9783. resume: resume,
  9784. idle: idle,
  9785. length: length,
  9786. getQueue: getQueue,
  9787. unshift: unshift,
  9788. empty: noop$4,
  9789. kill: kill,
  9790. killAndDrain: killAndDrain,
  9791. error: error
  9792. };
  9793. return self
  9794. function running () {
  9795. return _running
  9796. }
  9797. function pause () {
  9798. self.paused = true;
  9799. }
  9800. function length () {
  9801. var current = queueHead;
  9802. var counter = 0;
  9803. while (current) {
  9804. current = current.next;
  9805. counter++;
  9806. }
  9807. return counter
  9808. }
  9809. function getQueue () {
  9810. var current = queueHead;
  9811. var tasks = [];
  9812. while (current) {
  9813. tasks.push(current.value);
  9814. current = current.next;
  9815. }
  9816. return tasks
  9817. }
  9818. function resume () {
  9819. if (!self.paused) return
  9820. self.paused = false;
  9821. for (var i = 0; i < self.concurrency; i++) {
  9822. _running++;
  9823. release();
  9824. }
  9825. }
  9826. function idle () {
  9827. return _running === 0 && self.length() === 0
  9828. }
  9829. function push (value, done) {
  9830. var current = cache.get();
  9831. current.context = context;
  9832. current.release = release;
  9833. current.value = value;
  9834. current.callback = done || noop$4;
  9835. current.errorHandler = errorHandler;
  9836. if (_running === self.concurrency || self.paused) {
  9837. if (queueTail) {
  9838. queueTail.next = current;
  9839. queueTail = current;
  9840. } else {
  9841. queueHead = current;
  9842. queueTail = current;
  9843. self.saturated();
  9844. }
  9845. } else {
  9846. _running++;
  9847. worker.call(context, current.value, current.worked);
  9848. }
  9849. }
  9850. function unshift (value, done) {
  9851. var current = cache.get();
  9852. current.context = context;
  9853. current.release = release;
  9854. current.value = value;
  9855. current.callback = done || noop$4;
  9856. if (_running === self.concurrency || self.paused) {
  9857. if (queueHead) {
  9858. current.next = queueHead;
  9859. queueHead = current;
  9860. } else {
  9861. queueHead = current;
  9862. queueTail = current;
  9863. self.saturated();
  9864. }
  9865. } else {
  9866. _running++;
  9867. worker.call(context, current.value, current.worked);
  9868. }
  9869. }
  9870. function release (holder) {
  9871. if (holder) {
  9872. cache.release(holder);
  9873. }
  9874. var next = queueHead;
  9875. if (next) {
  9876. if (!self.paused) {
  9877. if (queueTail === queueHead) {
  9878. queueTail = null;
  9879. }
  9880. queueHead = next.next;
  9881. next.next = null;
  9882. worker.call(context, next.value, next.worked);
  9883. if (queueTail === null) {
  9884. self.empty();
  9885. }
  9886. } else {
  9887. _running--;
  9888. }
  9889. } else if (--_running === 0) {
  9890. self.drain();
  9891. }
  9892. }
  9893. function kill () {
  9894. queueHead = null;
  9895. queueTail = null;
  9896. self.drain = noop$4;
  9897. }
  9898. function killAndDrain () {
  9899. queueHead = null;
  9900. queueTail = null;
  9901. self.drain();
  9902. self.drain = noop$4;
  9903. }
  9904. function error (handler) {
  9905. errorHandler = handler;
  9906. }
  9907. }
  9908. function noop$4 () {}
  9909. function Task () {
  9910. this.value = null;
  9911. this.callback = noop$4;
  9912. this.next = null;
  9913. this.release = noop$4;
  9914. this.context = null;
  9915. this.errorHandler = null;
  9916. var self = this;
  9917. this.worked = function worked (err, result) {
  9918. var callback = self.callback;
  9919. var errorHandler = self.errorHandler;
  9920. var val = self.value;
  9921. self.value = null;
  9922. self.callback = noop$4;
  9923. if (self.errorHandler) {
  9924. errorHandler(err, val);
  9925. }
  9926. callback.call(self.context, err, result);
  9927. self.release(self);
  9928. };
  9929. }
  9930. function queueAsPromised (context, worker, concurrency) {
  9931. if (typeof context === 'function') {
  9932. concurrency = worker;
  9933. worker = context;
  9934. context = null;
  9935. }
  9936. function asyncWrapper (arg, cb) {
  9937. worker.call(this, arg)
  9938. .then(function (res) {
  9939. cb(null, res);
  9940. }, cb);
  9941. }
  9942. var queue = fastqueue(context, asyncWrapper, concurrency);
  9943. var pushCb = queue.push;
  9944. var unshiftCb = queue.unshift;
  9945. queue.push = push;
  9946. queue.unshift = unshift;
  9947. return queue
  9948. function push (value) {
  9949. var p = new Promise(function (resolve, reject) {
  9950. pushCb(value, function (err, result) {
  9951. if (err) {
  9952. reject(err);
  9953. return
  9954. }
  9955. resolve(result);
  9956. });
  9957. });
  9958. // Let's fork the promise chain to
  9959. // make the error bubble up to the user but
  9960. // not lead to a unhandledRejection
  9961. p.catch(noop$4);
  9962. return p
  9963. }
  9964. function unshift (value) {
  9965. var p = new Promise(function (resolve, reject) {
  9966. unshiftCb(value, function (err, result) {
  9967. if (err) {
  9968. reject(err);
  9969. return
  9970. }
  9971. resolve(result);
  9972. });
  9973. });
  9974. // Let's fork the promise chain to
  9975. // make the error bubble up to the user but
  9976. // not lead to a unhandledRejection
  9977. p.catch(noop$4);
  9978. return p
  9979. }
  9980. }
  9981. queue.exports = fastqueue;
  9982. queue.exports.promise = queueAsPromised;
  9983. var common$a = {};
  9984. Object.defineProperty(common$a, "__esModule", { value: true });
  9985. common$a.joinPathSegments = common$a.replacePathSegmentSeparator = common$a.isAppliedFilter = common$a.isFatalError = void 0;
  9986. function isFatalError(settings, error) {
  9987. if (settings.errorFilter === null) {
  9988. return true;
  9989. }
  9990. return !settings.errorFilter(error);
  9991. }
  9992. common$a.isFatalError = isFatalError;
  9993. function isAppliedFilter(filter, value) {
  9994. return filter === null || filter(value);
  9995. }
  9996. common$a.isAppliedFilter = isAppliedFilter;
  9997. function replacePathSegmentSeparator(filepath, separator) {
  9998. return filepath.split(/[/\\]/).join(separator);
  9999. }
  10000. common$a.replacePathSegmentSeparator = replacePathSegmentSeparator;
  10001. function joinPathSegments(a, b, separator) {
  10002. if (a === '') {
  10003. return b;
  10004. }
  10005. /**
  10006. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  10007. */
  10008. if (a.endsWith(separator)) {
  10009. return a + b;
  10010. }
  10011. return a + separator + b;
  10012. }
  10013. common$a.joinPathSegments = joinPathSegments;
  10014. var reader$1 = {};
  10015. Object.defineProperty(reader$1, "__esModule", { value: true });
  10016. const common$9 = common$a;
  10017. class Reader$1 {
  10018. constructor(_root, _settings) {
  10019. this._root = _root;
  10020. this._settings = _settings;
  10021. this._root = common$9.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
  10022. }
  10023. }
  10024. reader$1.default = Reader$1;
  10025. Object.defineProperty(async$2, "__esModule", { value: true });
  10026. const events_1 = require$$0__default$6;
  10027. const fsScandir$2 = out$1;
  10028. const fastq = queue.exports;
  10029. const common$8 = common$a;
  10030. const reader_1$3 = reader$1;
  10031. class AsyncReader extends reader_1$3.default {
  10032. constructor(_root, _settings) {
  10033. super(_root, _settings);
  10034. this._settings = _settings;
  10035. this._scandir = fsScandir$2.scandir;
  10036. this._emitter = new events_1.EventEmitter();
  10037. this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
  10038. this._isFatalError = false;
  10039. this._isDestroyed = false;
  10040. this._queue.drain = () => {
  10041. if (!this._isFatalError) {
  10042. this._emitter.emit('end');
  10043. }
  10044. };
  10045. }
  10046. read() {
  10047. this._isFatalError = false;
  10048. this._isDestroyed = false;
  10049. setImmediate(() => {
  10050. this._pushToQueue(this._root, this._settings.basePath);
  10051. });
  10052. return this._emitter;
  10053. }
  10054. get isDestroyed() {
  10055. return this._isDestroyed;
  10056. }
  10057. destroy() {
  10058. if (this._isDestroyed) {
  10059. throw new Error('The reader is already destroyed');
  10060. }
  10061. this._isDestroyed = true;
  10062. this._queue.killAndDrain();
  10063. }
  10064. onEntry(callback) {
  10065. this._emitter.on('entry', callback);
  10066. }
  10067. onError(callback) {
  10068. this._emitter.once('error', callback);
  10069. }
  10070. onEnd(callback) {
  10071. this._emitter.once('end', callback);
  10072. }
  10073. _pushToQueue(directory, base) {
  10074. const queueItem = { directory, base };
  10075. this._queue.push(queueItem, (error) => {
  10076. if (error !== null) {
  10077. this._handleError(error);
  10078. }
  10079. });
  10080. }
  10081. _worker(item, done) {
  10082. this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
  10083. if (error !== null) {
  10084. done(error, undefined);
  10085. return;
  10086. }
  10087. for (const entry of entries) {
  10088. this._handleEntry(entry, item.base);
  10089. }
  10090. done(null, undefined);
  10091. });
  10092. }
  10093. _handleError(error) {
  10094. if (this._isDestroyed || !common$8.isFatalError(this._settings, error)) {
  10095. return;
  10096. }
  10097. this._isFatalError = true;
  10098. this._isDestroyed = true;
  10099. this._emitter.emit('error', error);
  10100. }
  10101. _handleEntry(entry, base) {
  10102. if (this._isDestroyed || this._isFatalError) {
  10103. return;
  10104. }
  10105. const fullpath = entry.path;
  10106. if (base !== undefined) {
  10107. entry.path = common$8.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  10108. }
  10109. if (common$8.isAppliedFilter(this._settings.entryFilter, entry)) {
  10110. this._emitEntry(entry);
  10111. }
  10112. if (entry.dirent.isDirectory() && common$8.isAppliedFilter(this._settings.deepFilter, entry)) {
  10113. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  10114. }
  10115. }
  10116. _emitEntry(entry) {
  10117. this._emitter.emit('entry', entry);
  10118. }
  10119. }
  10120. async$2.default = AsyncReader;
  10121. Object.defineProperty(async$3, "__esModule", { value: true });
  10122. const async_1$3 = async$2;
  10123. class AsyncProvider {
  10124. constructor(_root, _settings) {
  10125. this._root = _root;
  10126. this._settings = _settings;
  10127. this._reader = new async_1$3.default(this._root, this._settings);
  10128. this._storage = [];
  10129. }
  10130. read(callback) {
  10131. this._reader.onError((error) => {
  10132. callFailureCallback(callback, error);
  10133. });
  10134. this._reader.onEntry((entry) => {
  10135. this._storage.push(entry);
  10136. });
  10137. this._reader.onEnd(() => {
  10138. callSuccessCallback(callback, this._storage);
  10139. });
  10140. this._reader.read();
  10141. }
  10142. }
  10143. async$3.default = AsyncProvider;
  10144. function callFailureCallback(callback, error) {
  10145. callback(error);
  10146. }
  10147. function callSuccessCallback(callback, entries) {
  10148. callback(null, entries);
  10149. }
  10150. var stream$4 = {};
  10151. Object.defineProperty(stream$4, "__esModule", { value: true });
  10152. const stream_1$5 = require$$0__default$2;
  10153. const async_1$2 = async$2;
  10154. class StreamProvider {
  10155. constructor(_root, _settings) {
  10156. this._root = _root;
  10157. this._settings = _settings;
  10158. this._reader = new async_1$2.default(this._root, this._settings);
  10159. this._stream = new stream_1$5.Readable({
  10160. objectMode: true,
  10161. read: () => { },
  10162. destroy: () => {
  10163. if (!this._reader.isDestroyed) {
  10164. this._reader.destroy();
  10165. }
  10166. }
  10167. });
  10168. }
  10169. read() {
  10170. this._reader.onError((error) => {
  10171. this._stream.emit('error', error);
  10172. });
  10173. this._reader.onEntry((entry) => {
  10174. this._stream.push(entry);
  10175. });
  10176. this._reader.onEnd(() => {
  10177. this._stream.push(null);
  10178. });
  10179. this._reader.read();
  10180. return this._stream;
  10181. }
  10182. }
  10183. stream$4.default = StreamProvider;
  10184. var sync$7 = {};
  10185. var sync$6 = {};
  10186. Object.defineProperty(sync$6, "__esModule", { value: true });
  10187. const fsScandir$1 = out$1;
  10188. const common$7 = common$a;
  10189. const reader_1$2 = reader$1;
  10190. class SyncReader extends reader_1$2.default {
  10191. constructor() {
  10192. super(...arguments);
  10193. this._scandir = fsScandir$1.scandirSync;
  10194. this._storage = [];
  10195. this._queue = new Set();
  10196. }
  10197. read() {
  10198. this._pushToQueue(this._root, this._settings.basePath);
  10199. this._handleQueue();
  10200. return this._storage;
  10201. }
  10202. _pushToQueue(directory, base) {
  10203. this._queue.add({ directory, base });
  10204. }
  10205. _handleQueue() {
  10206. for (const item of this._queue.values()) {
  10207. this._handleDirectory(item.directory, item.base);
  10208. }
  10209. }
  10210. _handleDirectory(directory, base) {
  10211. try {
  10212. const entries = this._scandir(directory, this._settings.fsScandirSettings);
  10213. for (const entry of entries) {
  10214. this._handleEntry(entry, base);
  10215. }
  10216. }
  10217. catch (error) {
  10218. this._handleError(error);
  10219. }
  10220. }
  10221. _handleError(error) {
  10222. if (!common$7.isFatalError(this._settings, error)) {
  10223. return;
  10224. }
  10225. throw error;
  10226. }
  10227. _handleEntry(entry, base) {
  10228. const fullpath = entry.path;
  10229. if (base !== undefined) {
  10230. entry.path = common$7.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  10231. }
  10232. if (common$7.isAppliedFilter(this._settings.entryFilter, entry)) {
  10233. this._pushToStorage(entry);
  10234. }
  10235. if (entry.dirent.isDirectory() && common$7.isAppliedFilter(this._settings.deepFilter, entry)) {
  10236. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  10237. }
  10238. }
  10239. _pushToStorage(entry) {
  10240. this._storage.push(entry);
  10241. }
  10242. }
  10243. sync$6.default = SyncReader;
  10244. Object.defineProperty(sync$7, "__esModule", { value: true });
  10245. const sync_1$3 = sync$6;
  10246. class SyncProvider {
  10247. constructor(_root, _settings) {
  10248. this._root = _root;
  10249. this._settings = _settings;
  10250. this._reader = new sync_1$3.default(this._root, this._settings);
  10251. }
  10252. read() {
  10253. return this._reader.read();
  10254. }
  10255. }
  10256. sync$7.default = SyncProvider;
  10257. var settings$1 = {};
  10258. Object.defineProperty(settings$1, "__esModule", { value: true });
  10259. const path$o = path__default;
  10260. const fsScandir = out$1;
  10261. class Settings {
  10262. constructor(_options = {}) {
  10263. this._options = _options;
  10264. this.basePath = this._getValue(this._options.basePath, undefined);
  10265. this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
  10266. this.deepFilter = this._getValue(this._options.deepFilter, null);
  10267. this.entryFilter = this._getValue(this._options.entryFilter, null);
  10268. this.errorFilter = this._getValue(this._options.errorFilter, null);
  10269. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$o.sep);
  10270. this.fsScandirSettings = new fsScandir.Settings({
  10271. followSymbolicLinks: this._options.followSymbolicLinks,
  10272. fs: this._options.fs,
  10273. pathSegmentSeparator: this._options.pathSegmentSeparator,
  10274. stats: this._options.stats,
  10275. throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
  10276. });
  10277. }
  10278. _getValue(option, value) {
  10279. return option !== null && option !== void 0 ? option : value;
  10280. }
  10281. }
  10282. settings$1.default = Settings;
  10283. Object.defineProperty(out$2, "__esModule", { value: true });
  10284. out$2.Settings = out$2.walkStream = out$2.walkSync = out$2.walk = void 0;
  10285. const async_1$1 = async$3;
  10286. const stream_1$4 = stream$4;
  10287. const sync_1$2 = sync$7;
  10288. const settings_1$1 = settings$1;
  10289. out$2.Settings = settings_1$1.default;
  10290. function walk$5(directory, optionsOrSettingsOrCallback, callback) {
  10291. if (typeof optionsOrSettingsOrCallback === 'function') {
  10292. new async_1$1.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
  10293. return;
  10294. }
  10295. new async_1$1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
  10296. }
  10297. out$2.walk = walk$5;
  10298. function walkSync(directory, optionsOrSettings) {
  10299. const settings = getSettings(optionsOrSettings);
  10300. const provider = new sync_1$2.default(directory, settings);
  10301. return provider.read();
  10302. }
  10303. out$2.walkSync = walkSync;
  10304. function walkStream(directory, optionsOrSettings) {
  10305. const settings = getSettings(optionsOrSettings);
  10306. const provider = new stream_1$4.default(directory, settings);
  10307. return provider.read();
  10308. }
  10309. out$2.walkStream = walkStream;
  10310. function getSettings(settingsOrOptions = {}) {
  10311. if (settingsOrOptions instanceof settings_1$1.default) {
  10312. return settingsOrOptions;
  10313. }
  10314. return new settings_1$1.default(settingsOrOptions);
  10315. }
  10316. var reader = {};
  10317. Object.defineProperty(reader, "__esModule", { value: true });
  10318. const path$n = path__default;
  10319. const fsStat$2 = out$3;
  10320. const utils$6 = utils$k;
  10321. class Reader {
  10322. constructor(_settings) {
  10323. this._settings = _settings;
  10324. this._fsStatSettings = new fsStat$2.Settings({
  10325. followSymbolicLink: this._settings.followSymbolicLinks,
  10326. fs: this._settings.fs,
  10327. throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
  10328. });
  10329. }
  10330. _getFullEntryPath(filepath) {
  10331. return path$n.resolve(this._settings.cwd, filepath);
  10332. }
  10333. _makeEntry(stats, pattern) {
  10334. const entry = {
  10335. name: pattern,
  10336. path: pattern,
  10337. dirent: utils$6.fs.createDirentFromStats(pattern, stats)
  10338. };
  10339. if (this._settings.stats) {
  10340. entry.stats = stats;
  10341. }
  10342. return entry;
  10343. }
  10344. _isFatalError(error) {
  10345. return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
  10346. }
  10347. }
  10348. reader.default = Reader;
  10349. Object.defineProperty(stream$5, "__esModule", { value: true });
  10350. const stream_1$3 = require$$0__default$2;
  10351. const fsStat$1 = out$3;
  10352. const fsWalk$1 = out$2;
  10353. const reader_1$1 = reader;
  10354. class ReaderStream extends reader_1$1.default {
  10355. constructor() {
  10356. super(...arguments);
  10357. this._walkStream = fsWalk$1.walkStream;
  10358. this._stat = fsStat$1.stat;
  10359. }
  10360. dynamic(root, options) {
  10361. return this._walkStream(root, options);
  10362. }
  10363. static(patterns, options) {
  10364. const filepaths = patterns.map(this._getFullEntryPath, this);
  10365. const stream = new stream_1$3.PassThrough({ objectMode: true });
  10366. stream._write = (index, _enc, done) => {
  10367. return this._getEntry(filepaths[index], patterns[index], options)
  10368. .then((entry) => {
  10369. if (entry !== null && options.entryFilter(entry)) {
  10370. stream.push(entry);
  10371. }
  10372. if (index === filepaths.length - 1) {
  10373. stream.end();
  10374. }
  10375. done();
  10376. })
  10377. .catch(done);
  10378. };
  10379. for (let i = 0; i < filepaths.length; i++) {
  10380. stream.write(i);
  10381. }
  10382. return stream;
  10383. }
  10384. _getEntry(filepath, pattern, options) {
  10385. return this._getStat(filepath)
  10386. .then((stats) => this._makeEntry(stats, pattern))
  10387. .catch((error) => {
  10388. if (options.errorFilter(error)) {
  10389. return null;
  10390. }
  10391. throw error;
  10392. });
  10393. }
  10394. _getStat(filepath) {
  10395. return new Promise((resolve, reject) => {
  10396. this._stat(filepath, this._fsStatSettings, (error, stats) => {
  10397. return error === null ? resolve(stats) : reject(error);
  10398. });
  10399. });
  10400. }
  10401. }
  10402. stream$5.default = ReaderStream;
  10403. var provider = {};
  10404. var deep = {};
  10405. var partial = {};
  10406. var matcher = {};
  10407. Object.defineProperty(matcher, "__esModule", { value: true });
  10408. const utils$5 = utils$k;
  10409. class Matcher {
  10410. constructor(_patterns, _settings, _micromatchOptions) {
  10411. this._patterns = _patterns;
  10412. this._settings = _settings;
  10413. this._micromatchOptions = _micromatchOptions;
  10414. this._storage = [];
  10415. this._fillStorage();
  10416. }
  10417. _fillStorage() {
  10418. /**
  10419. * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
  10420. * So, before expand patterns with brace expansion into separated patterns.
  10421. */
  10422. const patterns = utils$5.pattern.expandPatternsWithBraceExpansion(this._patterns);
  10423. for (const pattern of patterns) {
  10424. const segments = this._getPatternSegments(pattern);
  10425. const sections = this._splitSegmentsIntoSections(segments);
  10426. this._storage.push({
  10427. complete: sections.length <= 1,
  10428. pattern,
  10429. segments,
  10430. sections
  10431. });
  10432. }
  10433. }
  10434. _getPatternSegments(pattern) {
  10435. const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions);
  10436. return parts.map((part) => {
  10437. const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings);
  10438. if (!dynamic) {
  10439. return {
  10440. dynamic: false,
  10441. pattern: part
  10442. };
  10443. }
  10444. return {
  10445. dynamic: true,
  10446. pattern: part,
  10447. patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions)
  10448. };
  10449. });
  10450. }
  10451. _splitSegmentsIntoSections(segments) {
  10452. return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern));
  10453. }
  10454. }
  10455. matcher.default = Matcher;
  10456. Object.defineProperty(partial, "__esModule", { value: true });
  10457. const matcher_1 = matcher;
  10458. class PartialMatcher extends matcher_1.default {
  10459. match(filepath) {
  10460. const parts = filepath.split('/');
  10461. const levels = parts.length;
  10462. const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
  10463. for (const pattern of patterns) {
  10464. const section = pattern.sections[0];
  10465. /**
  10466. * In this case, the pattern has a globstar and we must read all directories unconditionally,
  10467. * but only if the level has reached the end of the first group.
  10468. *
  10469. * fixtures/{a,b}/**
  10470. * ^ true/false ^ always true
  10471. */
  10472. if (!pattern.complete && levels > section.length) {
  10473. return true;
  10474. }
  10475. const match = parts.every((part, index) => {
  10476. const segment = pattern.segments[index];
  10477. if (segment.dynamic && segment.patternRe.test(part)) {
  10478. return true;
  10479. }
  10480. if (!segment.dynamic && segment.pattern === part) {
  10481. return true;
  10482. }
  10483. return false;
  10484. });
  10485. if (match) {
  10486. return true;
  10487. }
  10488. }
  10489. return false;
  10490. }
  10491. }
  10492. partial.default = PartialMatcher;
  10493. Object.defineProperty(deep, "__esModule", { value: true });
  10494. const utils$4 = utils$k;
  10495. const partial_1 = partial;
  10496. class DeepFilter {
  10497. constructor(_settings, _micromatchOptions) {
  10498. this._settings = _settings;
  10499. this._micromatchOptions = _micromatchOptions;
  10500. }
  10501. getFilter(basePath, positive, negative) {
  10502. const matcher = this._getMatcher(positive);
  10503. const negativeRe = this._getNegativePatternsRe(negative);
  10504. return (entry) => this._filter(basePath, entry, matcher, negativeRe);
  10505. }
  10506. _getMatcher(patterns) {
  10507. return new partial_1.default(patterns, this._settings, this._micromatchOptions);
  10508. }
  10509. _getNegativePatternsRe(patterns) {
  10510. const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
  10511. return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
  10512. }
  10513. _filter(basePath, entry, matcher, negativeRe) {
  10514. if (this._isSkippedByDeep(basePath, entry.path)) {
  10515. return false;
  10516. }
  10517. if (this._isSkippedSymbolicLink(entry)) {
  10518. return false;
  10519. }
  10520. const filepath = utils$4.path.removeLeadingDotSegment(entry.path);
  10521. if (this._isSkippedByPositivePatterns(filepath, matcher)) {
  10522. return false;
  10523. }
  10524. return this._isSkippedByNegativePatterns(filepath, negativeRe);
  10525. }
  10526. _isSkippedByDeep(basePath, entryPath) {
  10527. /**
  10528. * Avoid unnecessary depth calculations when it doesn't matter.
  10529. */
  10530. if (this._settings.deep === Infinity) {
  10531. return false;
  10532. }
  10533. return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
  10534. }
  10535. _getEntryLevel(basePath, entryPath) {
  10536. const entryPathDepth = entryPath.split('/').length;
  10537. if (basePath === '') {
  10538. return entryPathDepth;
  10539. }
  10540. const basePathDepth = basePath.split('/').length;
  10541. return entryPathDepth - basePathDepth;
  10542. }
  10543. _isSkippedSymbolicLink(entry) {
  10544. return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
  10545. }
  10546. _isSkippedByPositivePatterns(entryPath, matcher) {
  10547. return !this._settings.baseNameMatch && !matcher.match(entryPath);
  10548. }
  10549. _isSkippedByNegativePatterns(entryPath, patternsRe) {
  10550. return !utils$4.pattern.matchAny(entryPath, patternsRe);
  10551. }
  10552. }
  10553. deep.default = DeepFilter;
  10554. var entry$1 = {};
  10555. Object.defineProperty(entry$1, "__esModule", { value: true });
  10556. const utils$3 = utils$k;
  10557. class EntryFilter {
  10558. constructor(_settings, _micromatchOptions) {
  10559. this._settings = _settings;
  10560. this._micromatchOptions = _micromatchOptions;
  10561. this.index = new Map();
  10562. }
  10563. getFilter(positive, negative) {
  10564. const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
  10565. const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions);
  10566. return (entry) => this._filter(entry, positiveRe, negativeRe);
  10567. }
  10568. _filter(entry, positiveRe, negativeRe) {
  10569. if (this._settings.unique && this._isDuplicateEntry(entry)) {
  10570. return false;
  10571. }
  10572. if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
  10573. return false;
  10574. }
  10575. if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
  10576. return false;
  10577. }
  10578. const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
  10579. const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
  10580. if (this._settings.unique && isMatched) {
  10581. this._createIndexRecord(entry);
  10582. }
  10583. return isMatched;
  10584. }
  10585. _isDuplicateEntry(entry) {
  10586. return this.index.has(entry.path);
  10587. }
  10588. _createIndexRecord(entry) {
  10589. this.index.set(entry.path, undefined);
  10590. }
  10591. _onlyFileFilter(entry) {
  10592. return this._settings.onlyFiles && !entry.dirent.isFile();
  10593. }
  10594. _onlyDirectoryFilter(entry) {
  10595. return this._settings.onlyDirectories && !entry.dirent.isDirectory();
  10596. }
  10597. _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
  10598. if (!this._settings.absolute) {
  10599. return false;
  10600. }
  10601. const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
  10602. return utils$3.pattern.matchAny(fullpath, patternsRe);
  10603. }
  10604. _isMatchToPatterns(entryPath, patternsRe) {
  10605. const filepath = utils$3.path.removeLeadingDotSegment(entryPath);
  10606. return utils$3.pattern.matchAny(filepath, patternsRe);
  10607. }
  10608. }
  10609. entry$1.default = EntryFilter;
  10610. var error$4 = {};
  10611. Object.defineProperty(error$4, "__esModule", { value: true });
  10612. const utils$2 = utils$k;
  10613. class ErrorFilter {
  10614. constructor(_settings) {
  10615. this._settings = _settings;
  10616. }
  10617. getFilter() {
  10618. return (error) => this._isNonFatalError(error);
  10619. }
  10620. _isNonFatalError(error) {
  10621. return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
  10622. }
  10623. }
  10624. error$4.default = ErrorFilter;
  10625. var entry = {};
  10626. Object.defineProperty(entry, "__esModule", { value: true });
  10627. const utils$1 = utils$k;
  10628. class EntryTransformer {
  10629. constructor(_settings) {
  10630. this._settings = _settings;
  10631. }
  10632. getTransformer() {
  10633. return (entry) => this._transform(entry);
  10634. }
  10635. _transform(entry) {
  10636. let filepath = entry.path;
  10637. if (this._settings.absolute) {
  10638. filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath);
  10639. filepath = utils$1.path.unixify(filepath);
  10640. }
  10641. if (this._settings.markDirectories && entry.dirent.isDirectory()) {
  10642. filepath += '/';
  10643. }
  10644. if (!this._settings.objectMode) {
  10645. return filepath;
  10646. }
  10647. return Object.assign(Object.assign({}, entry), { path: filepath });
  10648. }
  10649. }
  10650. entry.default = EntryTransformer;
  10651. Object.defineProperty(provider, "__esModule", { value: true });
  10652. const path$m = path__default;
  10653. const deep_1 = deep;
  10654. const entry_1 = entry$1;
  10655. const error_1 = error$4;
  10656. const entry_2 = entry;
  10657. class Provider {
  10658. constructor(_settings) {
  10659. this._settings = _settings;
  10660. this.errorFilter = new error_1.default(this._settings);
  10661. this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
  10662. this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
  10663. this.entryTransformer = new entry_2.default(this._settings);
  10664. }
  10665. _getRootDirectory(task) {
  10666. return path$m.resolve(this._settings.cwd, task.base);
  10667. }
  10668. _getReaderOptions(task) {
  10669. const basePath = task.base === '.' ? '' : task.base;
  10670. return {
  10671. basePath,
  10672. pathSegmentSeparator: '/',
  10673. concurrency: this._settings.concurrency,
  10674. deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
  10675. entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
  10676. errorFilter: this.errorFilter.getFilter(),
  10677. followSymbolicLinks: this._settings.followSymbolicLinks,
  10678. fs: this._settings.fs,
  10679. stats: this._settings.stats,
  10680. throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
  10681. transform: this.entryTransformer.getTransformer()
  10682. };
  10683. }
  10684. _getMicromatchOptions() {
  10685. return {
  10686. dot: this._settings.dot,
  10687. matchBase: this._settings.baseNameMatch,
  10688. nobrace: !this._settings.braceExpansion,
  10689. nocase: !this._settings.caseSensitiveMatch,
  10690. noext: !this._settings.extglob,
  10691. noglobstar: !this._settings.globstar,
  10692. posix: true,
  10693. strictSlashes: false
  10694. };
  10695. }
  10696. }
  10697. provider.default = Provider;
  10698. Object.defineProperty(async$6, "__esModule", { value: true });
  10699. const stream_1$2 = stream$5;
  10700. const provider_1$2 = provider;
  10701. class ProviderAsync extends provider_1$2.default {
  10702. constructor() {
  10703. super(...arguments);
  10704. this._reader = new stream_1$2.default(this._settings);
  10705. }
  10706. read(task) {
  10707. const root = this._getRootDirectory(task);
  10708. const options = this._getReaderOptions(task);
  10709. const entries = [];
  10710. return new Promise((resolve, reject) => {
  10711. const stream = this.api(root, task, options);
  10712. stream.once('error', reject);
  10713. stream.on('data', (entry) => entries.push(options.transform(entry)));
  10714. stream.once('end', () => resolve(entries));
  10715. });
  10716. }
  10717. api(root, task, options) {
  10718. if (task.dynamic) {
  10719. return this._reader.dynamic(root, options);
  10720. }
  10721. return this._reader.static(task.patterns, options);
  10722. }
  10723. }
  10724. async$6.default = ProviderAsync;
  10725. var stream$3 = {};
  10726. Object.defineProperty(stream$3, "__esModule", { value: true });
  10727. const stream_1$1 = require$$0__default$2;
  10728. const stream_2 = stream$5;
  10729. const provider_1$1 = provider;
  10730. class ProviderStream extends provider_1$1.default {
  10731. constructor() {
  10732. super(...arguments);
  10733. this._reader = new stream_2.default(this._settings);
  10734. }
  10735. read(task) {
  10736. const root = this._getRootDirectory(task);
  10737. const options = this._getReaderOptions(task);
  10738. const source = this.api(root, task, options);
  10739. const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } });
  10740. source
  10741. .once('error', (error) => destination.emit('error', error))
  10742. .on('data', (entry) => destination.emit('data', options.transform(entry)))
  10743. .once('end', () => destination.emit('end'));
  10744. destination
  10745. .once('close', () => source.destroy());
  10746. return destination;
  10747. }
  10748. api(root, task, options) {
  10749. if (task.dynamic) {
  10750. return this._reader.dynamic(root, options);
  10751. }
  10752. return this._reader.static(task.patterns, options);
  10753. }
  10754. }
  10755. stream$3.default = ProviderStream;
  10756. var sync$5 = {};
  10757. var sync$4 = {};
  10758. Object.defineProperty(sync$4, "__esModule", { value: true });
  10759. const fsStat = out$3;
  10760. const fsWalk = out$2;
  10761. const reader_1 = reader;
  10762. class ReaderSync extends reader_1.default {
  10763. constructor() {
  10764. super(...arguments);
  10765. this._walkSync = fsWalk.walkSync;
  10766. this._statSync = fsStat.statSync;
  10767. }
  10768. dynamic(root, options) {
  10769. return this._walkSync(root, options);
  10770. }
  10771. static(patterns, options) {
  10772. const entries = [];
  10773. for (const pattern of patterns) {
  10774. const filepath = this._getFullEntryPath(pattern);
  10775. const entry = this._getEntry(filepath, pattern, options);
  10776. if (entry === null || !options.entryFilter(entry)) {
  10777. continue;
  10778. }
  10779. entries.push(entry);
  10780. }
  10781. return entries;
  10782. }
  10783. _getEntry(filepath, pattern, options) {
  10784. try {
  10785. const stats = this._getStat(filepath);
  10786. return this._makeEntry(stats, pattern);
  10787. }
  10788. catch (error) {
  10789. if (options.errorFilter(error)) {
  10790. return null;
  10791. }
  10792. throw error;
  10793. }
  10794. }
  10795. _getStat(filepath) {
  10796. return this._statSync(filepath, this._fsStatSettings);
  10797. }
  10798. }
  10799. sync$4.default = ReaderSync;
  10800. Object.defineProperty(sync$5, "__esModule", { value: true });
  10801. const sync_1$1 = sync$4;
  10802. const provider_1 = provider;
  10803. class ProviderSync extends provider_1.default {
  10804. constructor() {
  10805. super(...arguments);
  10806. this._reader = new sync_1$1.default(this._settings);
  10807. }
  10808. read(task) {
  10809. const root = this._getRootDirectory(task);
  10810. const options = this._getReaderOptions(task);
  10811. const entries = this.api(root, task, options);
  10812. return entries.map(options.transform);
  10813. }
  10814. api(root, task, options) {
  10815. if (task.dynamic) {
  10816. return this._reader.dynamic(root, options);
  10817. }
  10818. return this._reader.static(task.patterns, options);
  10819. }
  10820. }
  10821. sync$5.default = ProviderSync;
  10822. var settings = {};
  10823. (function (exports) {
  10824. Object.defineProperty(exports, "__esModule", { value: true });
  10825. exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
  10826. const fs = fs__default;
  10827. const os = require$$0__default$1;
  10828. /**
  10829. * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
  10830. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
  10831. */
  10832. const CPU_COUNT = Math.max(os.cpus().length, 1);
  10833. exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
  10834. lstat: fs.lstat,
  10835. lstatSync: fs.lstatSync,
  10836. stat: fs.stat,
  10837. statSync: fs.statSync,
  10838. readdir: fs.readdir,
  10839. readdirSync: fs.readdirSync
  10840. };
  10841. class Settings {
  10842. constructor(_options = {}) {
  10843. this._options = _options;
  10844. this.absolute = this._getValue(this._options.absolute, false);
  10845. this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
  10846. this.braceExpansion = this._getValue(this._options.braceExpansion, true);
  10847. this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
  10848. this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
  10849. this.cwd = this._getValue(this._options.cwd, process.cwd());
  10850. this.deep = this._getValue(this._options.deep, Infinity);
  10851. this.dot = this._getValue(this._options.dot, false);
  10852. this.extglob = this._getValue(this._options.extglob, true);
  10853. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
  10854. this.fs = this._getFileSystemMethods(this._options.fs);
  10855. this.globstar = this._getValue(this._options.globstar, true);
  10856. this.ignore = this._getValue(this._options.ignore, []);
  10857. this.markDirectories = this._getValue(this._options.markDirectories, false);
  10858. this.objectMode = this._getValue(this._options.objectMode, false);
  10859. this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
  10860. this.onlyFiles = this._getValue(this._options.onlyFiles, true);
  10861. this.stats = this._getValue(this._options.stats, false);
  10862. this.suppressErrors = this._getValue(this._options.suppressErrors, false);
  10863. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
  10864. this.unique = this._getValue(this._options.unique, true);
  10865. if (this.onlyDirectories) {
  10866. this.onlyFiles = false;
  10867. }
  10868. if (this.stats) {
  10869. this.objectMode = true;
  10870. }
  10871. }
  10872. _getValue(option, value) {
  10873. return option === undefined ? value : option;
  10874. }
  10875. _getFileSystemMethods(methods = {}) {
  10876. return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
  10877. }
  10878. }
  10879. exports.default = Settings;
  10880. }(settings));
  10881. const taskManager = tasks;
  10882. const async_1 = async$6;
  10883. const stream_1 = stream$3;
  10884. const sync_1 = sync$5;
  10885. const settings_1 = settings;
  10886. const utils = utils$k;
  10887. async function FastGlob(source, options) {
  10888. assertPatternsInput$1(source);
  10889. const works = getWorks(source, async_1.default, options);
  10890. const result = await Promise.all(works);
  10891. return utils.array.flatten(result);
  10892. }
  10893. // https://github.com/typescript-eslint/typescript-eslint/issues/60
  10894. // eslint-disable-next-line no-redeclare
  10895. (function (FastGlob) {
  10896. function sync(source, options) {
  10897. assertPatternsInput$1(source);
  10898. const works = getWorks(source, sync_1.default, options);
  10899. return utils.array.flatten(works);
  10900. }
  10901. FastGlob.sync = sync;
  10902. function stream(source, options) {
  10903. assertPatternsInput$1(source);
  10904. const works = getWorks(source, stream_1.default, options);
  10905. /**
  10906. * The stream returned by the provider cannot work with an asynchronous iterator.
  10907. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
  10908. * This affects performance (+25%). I don't see best solution right now.
  10909. */
  10910. return utils.stream.merge(works);
  10911. }
  10912. FastGlob.stream = stream;
  10913. function generateTasks(source, options) {
  10914. assertPatternsInput$1(source);
  10915. const patterns = [].concat(source);
  10916. const settings = new settings_1.default(options);
  10917. return taskManager.generate(patterns, settings);
  10918. }
  10919. FastGlob.generateTasks = generateTasks;
  10920. function isDynamicPattern(source, options) {
  10921. assertPatternsInput$1(source);
  10922. const settings = new settings_1.default(options);
  10923. return utils.pattern.isDynamicPattern(source, settings);
  10924. }
  10925. FastGlob.isDynamicPattern = isDynamicPattern;
  10926. function escapePath(source) {
  10927. assertPatternsInput$1(source);
  10928. return utils.path.escape(source);
  10929. }
  10930. FastGlob.escapePath = escapePath;
  10931. })(FastGlob || (FastGlob = {}));
  10932. function getWorks(source, _Provider, options) {
  10933. const patterns = [].concat(source);
  10934. const settings = new settings_1.default(options);
  10935. const tasks = taskManager.generate(patterns, settings);
  10936. const provider = new _Provider(settings);
  10937. return tasks.map(provider.read, provider);
  10938. }
  10939. function assertPatternsInput$1(input) {
  10940. const source = [].concat(input);
  10941. const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
  10942. if (!isValidSource) {
  10943. throw new TypeError('Patterns must be a string (non empty) or an array of strings');
  10944. }
  10945. }
  10946. var out = FastGlob;
  10947. var dist$3 = {};
  10948. (function (exports) {
  10949. Object.defineProperty(exports, "__esModule", { value: true });
  10950. exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0;
  10951. const path = path__default;
  10952. const fs = fs__default;
  10953. const os = require$$0__default$1;
  10954. const fsReadFileAsync = fs.promises.readFile;
  10955. function getDefaultSearchPlaces(name) {
  10956. return [
  10957. 'package.json',
  10958. `.${name}rc.json`,
  10959. `.${name}rc.js`,
  10960. `${name}.config.js`,
  10961. `.${name}rc.cjs`,
  10962. `${name}.config.cjs`,
  10963. ];
  10964. }
  10965. function getSearchPaths(startDir, stopDir) {
  10966. return startDir
  10967. .split(path.sep)
  10968. .reduceRight((acc, _, ind, arr) => {
  10969. const currentPath = arr.slice(0, ind + 1).join(path.sep);
  10970. if (!acc.passedStopDir)
  10971. acc.searchPlaces.push(currentPath || path.sep);
  10972. if (currentPath === stopDir)
  10973. acc.passedStopDir = true;
  10974. return acc;
  10975. }, { searchPlaces: [], passedStopDir: false }).searchPlaces;
  10976. }
  10977. exports.defaultLoaders = Object.freeze({
  10978. '.js': eval('require'),
  10979. '.json': eval('require'),
  10980. '.cjs': eval('require'),
  10981. noExt(_, content) {
  10982. return JSON.parse(content);
  10983. },
  10984. });
  10985. function getExtDesc(ext) {
  10986. return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`;
  10987. }
  10988. function getOptions(name, options = {}) {
  10989. const conf = {
  10990. stopDir: os.homedir(),
  10991. searchPlaces: getDefaultSearchPlaces(name),
  10992. ignoreEmptySearchPlaces: true,
  10993. transform: (x) => x,
  10994. packageProp: [name],
  10995. ...options,
  10996. loaders: { ...exports.defaultLoaders, ...options.loaders },
  10997. };
  10998. conf.searchPlaces.forEach(place => {
  10999. const key = path.extname(place) || 'noExt';
  11000. const loader = conf.loaders[key];
  11001. if (!loader) {
  11002. throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`);
  11003. }
  11004. if (typeof loader !== 'function') {
  11005. throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
  11006. }
  11007. });
  11008. return conf;
  11009. }
  11010. function getPackageProp(props, obj) {
  11011. if (typeof props === 'string' && props in obj)
  11012. return obj[props];
  11013. return ((Array.isArray(props) ? props : props.split('.')).reduce((acc, prop) => (acc === undefined ? acc : acc[prop]), obj) || null);
  11014. }
  11015. function getSearchItems(searchPlaces, searchPaths) {
  11016. return searchPaths.reduce((acc, searchPath) => {
  11017. searchPlaces.forEach(fileName => acc.push({
  11018. fileName,
  11019. filepath: path.join(searchPath, fileName),
  11020. loaderKey: path.extname(fileName) || 'noExt',
  11021. }));
  11022. return acc;
  11023. }, []);
  11024. }
  11025. function validateFilePath(filepath) {
  11026. if (!filepath)
  11027. throw new Error('load must pass a non-empty string');
  11028. }
  11029. function validateLoader(loader, ext) {
  11030. if (!loader)
  11031. throw new Error(`No loader specified for extension "${ext}"`);
  11032. if (typeof loader !== 'function')
  11033. throw new Error('loader is not a function');
  11034. }
  11035. function lilconfig(name, options) {
  11036. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
  11037. return {
  11038. async search(searchFrom = process.cwd()) {
  11039. const searchPaths = getSearchPaths(searchFrom, stopDir);
  11040. const result = {
  11041. config: null,
  11042. filepath: '',
  11043. };
  11044. const searchItems = getSearchItems(searchPlaces, searchPaths);
  11045. for (const { fileName, filepath, loaderKey } of searchItems) {
  11046. try {
  11047. await fs.promises.access(filepath);
  11048. }
  11049. catch (_a) {
  11050. continue;
  11051. }
  11052. const content = String(await fsReadFileAsync(filepath));
  11053. const loader = loaders[loaderKey];
  11054. if (fileName === 'package.json') {
  11055. const pkg = loader(filepath, content);
  11056. const maybeConfig = getPackageProp(packageProp, pkg);
  11057. if (maybeConfig != null) {
  11058. result.config = maybeConfig;
  11059. result.filepath = filepath;
  11060. break;
  11061. }
  11062. continue;
  11063. }
  11064. const isEmpty = content.trim() === '';
  11065. if (isEmpty && ignoreEmptySearchPlaces)
  11066. continue;
  11067. if (isEmpty) {
  11068. result.isEmpty = true;
  11069. result.config = undefined;
  11070. }
  11071. else {
  11072. validateLoader(loader, loaderKey);
  11073. result.config = loader(filepath, content);
  11074. }
  11075. result.filepath = filepath;
  11076. break;
  11077. }
  11078. if (result.filepath === '' && result.config === null)
  11079. return transform(null);
  11080. return transform(result);
  11081. },
  11082. async load(filepath) {
  11083. validateFilePath(filepath);
  11084. const { base, ext } = path.parse(filepath);
  11085. const loaderKey = ext || 'noExt';
  11086. const loader = loaders[loaderKey];
  11087. validateLoader(loader, loaderKey);
  11088. const content = String(await fsReadFileAsync(filepath));
  11089. if (base === 'package.json') {
  11090. const pkg = await loader(filepath, content);
  11091. return transform({
  11092. config: getPackageProp(packageProp, pkg),
  11093. filepath,
  11094. });
  11095. }
  11096. const result = {
  11097. config: null,
  11098. filepath,
  11099. };
  11100. const isEmpty = content.trim() === '';
  11101. if (isEmpty && ignoreEmptySearchPlaces)
  11102. return transform({
  11103. config: undefined,
  11104. filepath,
  11105. isEmpty: true,
  11106. });
  11107. result.config = isEmpty
  11108. ? undefined
  11109. : await loader(filepath, content);
  11110. return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
  11111. },
  11112. };
  11113. }
  11114. exports.lilconfig = lilconfig;
  11115. function lilconfigSync(name, options) {
  11116. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
  11117. return {
  11118. search(searchFrom = process.cwd()) {
  11119. const searchPaths = getSearchPaths(searchFrom, stopDir);
  11120. const result = {
  11121. config: null,
  11122. filepath: '',
  11123. };
  11124. const searchItems = getSearchItems(searchPlaces, searchPaths);
  11125. for (const { fileName, filepath, loaderKey } of searchItems) {
  11126. try {
  11127. fs.accessSync(filepath);
  11128. }
  11129. catch (_a) {
  11130. continue;
  11131. }
  11132. const loader = loaders[loaderKey];
  11133. const content = String(fs.readFileSync(filepath));
  11134. if (fileName === 'package.json') {
  11135. const pkg = loader(filepath, content);
  11136. const maybeConfig = getPackageProp(packageProp, pkg);
  11137. if (maybeConfig != null) {
  11138. result.config = maybeConfig;
  11139. result.filepath = filepath;
  11140. break;
  11141. }
  11142. continue;
  11143. }
  11144. const isEmpty = content.trim() === '';
  11145. if (isEmpty && ignoreEmptySearchPlaces)
  11146. continue;
  11147. if (isEmpty) {
  11148. result.isEmpty = true;
  11149. result.config = undefined;
  11150. }
  11151. else {
  11152. validateLoader(loader, loaderKey);
  11153. result.config = loader(filepath, content);
  11154. }
  11155. result.filepath = filepath;
  11156. break;
  11157. }
  11158. if (result.filepath === '' && result.config === null)
  11159. return transform(null);
  11160. return transform(result);
  11161. },
  11162. load(filepath) {
  11163. validateFilePath(filepath);
  11164. const { base, ext } = path.parse(filepath);
  11165. const loaderKey = ext || 'noExt';
  11166. const loader = loaders[loaderKey];
  11167. validateLoader(loader, loaderKey);
  11168. const content = String(fs.readFileSync(filepath));
  11169. if (base === 'package.json') {
  11170. const pkg = loader(filepath, content);
  11171. return transform({
  11172. config: getPackageProp(packageProp, pkg),
  11173. filepath,
  11174. });
  11175. }
  11176. const result = {
  11177. config: null,
  11178. filepath,
  11179. };
  11180. const isEmpty = content.trim() === '';
  11181. if (isEmpty && ignoreEmptySearchPlaces)
  11182. return transform({
  11183. filepath,
  11184. config: undefined,
  11185. isEmpty: true,
  11186. });
  11187. result.config = isEmpty ? undefined : loader(filepath, content);
  11188. return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
  11189. },
  11190. };
  11191. }
  11192. exports.lilconfigSync = lilconfigSync;
  11193. }(dist$3));
  11194. var dist$2 = {};
  11195. var parseCst$1 = {};
  11196. var PlainValueEc8e588e = {};
  11197. const Char = {
  11198. ANCHOR: '&',
  11199. COMMENT: '#',
  11200. TAG: '!',
  11201. DIRECTIVES_END: '-',
  11202. DOCUMENT_END: '.'
  11203. };
  11204. const Type = {
  11205. ALIAS: 'ALIAS',
  11206. BLANK_LINE: 'BLANK_LINE',
  11207. BLOCK_FOLDED: 'BLOCK_FOLDED',
  11208. BLOCK_LITERAL: 'BLOCK_LITERAL',
  11209. COMMENT: 'COMMENT',
  11210. DIRECTIVE: 'DIRECTIVE',
  11211. DOCUMENT: 'DOCUMENT',
  11212. FLOW_MAP: 'FLOW_MAP',
  11213. FLOW_SEQ: 'FLOW_SEQ',
  11214. MAP: 'MAP',
  11215. MAP_KEY: 'MAP_KEY',
  11216. MAP_VALUE: 'MAP_VALUE',
  11217. PLAIN: 'PLAIN',
  11218. QUOTE_DOUBLE: 'QUOTE_DOUBLE',
  11219. QUOTE_SINGLE: 'QUOTE_SINGLE',
  11220. SEQ: 'SEQ',
  11221. SEQ_ITEM: 'SEQ_ITEM'
  11222. };
  11223. const defaultTagPrefix = 'tag:yaml.org,2002:';
  11224. const defaultTags = {
  11225. MAP: 'tag:yaml.org,2002:map',
  11226. SEQ: 'tag:yaml.org,2002:seq',
  11227. STR: 'tag:yaml.org,2002:str'
  11228. };
  11229. function findLineStarts(src) {
  11230. const ls = [0];
  11231. let offset = src.indexOf('\n');
  11232. while (offset !== -1) {
  11233. offset += 1;
  11234. ls.push(offset);
  11235. offset = src.indexOf('\n', offset);
  11236. }
  11237. return ls;
  11238. }
  11239. function getSrcInfo(cst) {
  11240. let lineStarts, src;
  11241. if (typeof cst === 'string') {
  11242. lineStarts = findLineStarts(cst);
  11243. src = cst;
  11244. } else {
  11245. if (Array.isArray(cst)) cst = cst[0];
  11246. if (cst && cst.context) {
  11247. if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src);
  11248. lineStarts = cst.lineStarts;
  11249. src = cst.context.src;
  11250. }
  11251. }
  11252. return {
  11253. lineStarts,
  11254. src
  11255. };
  11256. }
  11257. /**
  11258. * @typedef {Object} LinePos - One-indexed position in the source
  11259. * @property {number} line
  11260. * @property {number} col
  11261. */
  11262. /**
  11263. * Determine the line/col position matching a character offset.
  11264. *
  11265. * Accepts a source string or a CST document as the second parameter. With
  11266. * the latter, starting indices for lines are cached in the document as
  11267. * `lineStarts: number[]`.
  11268. *
  11269. * Returns a one-indexed `{ line, col }` location if found, or
  11270. * `undefined` otherwise.
  11271. *
  11272. * @param {number} offset
  11273. * @param {string|Document|Document[]} cst
  11274. * @returns {?LinePos}
  11275. */
  11276. function getLinePos(offset, cst) {
  11277. if (typeof offset !== 'number' || offset < 0) return null;
  11278. const {
  11279. lineStarts,
  11280. src
  11281. } = getSrcInfo(cst);
  11282. if (!lineStarts || !src || offset > src.length) return null;
  11283. for (let i = 0; i < lineStarts.length; ++i) {
  11284. const start = lineStarts[i];
  11285. if (offset < start) {
  11286. return {
  11287. line: i,
  11288. col: offset - lineStarts[i - 1] + 1
  11289. };
  11290. }
  11291. if (offset === start) return {
  11292. line: i + 1,
  11293. col: 1
  11294. };
  11295. }
  11296. const line = lineStarts.length;
  11297. return {
  11298. line,
  11299. col: offset - lineStarts[line - 1] + 1
  11300. };
  11301. }
  11302. /**
  11303. * Get a specified line from the source.
  11304. *
  11305. * Accepts a source string or a CST document as the second parameter. With
  11306. * the latter, starting indices for lines are cached in the document as
  11307. * `lineStarts: number[]`.
  11308. *
  11309. * Returns the line as a string if found, or `null` otherwise.
  11310. *
  11311. * @param {number} line One-indexed line number
  11312. * @param {string|Document|Document[]} cst
  11313. * @returns {?string}
  11314. */
  11315. function getLine(line, cst) {
  11316. const {
  11317. lineStarts,
  11318. src
  11319. } = getSrcInfo(cst);
  11320. if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null;
  11321. const start = lineStarts[line - 1];
  11322. let end = lineStarts[line]; // undefined for last line; that's ok for slice()
  11323. while (end && end > start && src[end - 1] === '\n') --end;
  11324. return src.slice(start, end);
  11325. }
  11326. /**
  11327. * Pretty-print the starting line from the source indicated by the range `pos`
  11328. *
  11329. * Trims output to `maxWidth` chars while keeping the starting column visible,
  11330. * using `…` at either end to indicate dropped characters.
  11331. *
  11332. * Returns a two-line string (or `null`) with `\n` as separator; the second line
  11333. * will hold appropriately indented `^` marks indicating the column range.
  11334. *
  11335. * @param {Object} pos
  11336. * @param {LinePos} pos.start
  11337. * @param {LinePos} [pos.end]
  11338. * @param {string|Document|Document[]*} cst
  11339. * @param {number} [maxWidth=80]
  11340. * @returns {?string}
  11341. */
  11342. function getPrettyContext({
  11343. start,
  11344. end
  11345. }, cst, maxWidth = 80) {
  11346. let src = getLine(start.line, cst);
  11347. if (!src) return null;
  11348. let {
  11349. col
  11350. } = start;
  11351. if (src.length > maxWidth) {
  11352. if (col <= maxWidth - 10) {
  11353. src = src.substr(0, maxWidth - 1) + '…';
  11354. } else {
  11355. const halfWidth = Math.round(maxWidth / 2);
  11356. if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…';
  11357. col -= src.length - maxWidth;
  11358. src = '…' + src.substr(1 - maxWidth);
  11359. }
  11360. }
  11361. let errLen = 1;
  11362. let errEnd = '';
  11363. if (end) {
  11364. if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) {
  11365. errLen = end.col - start.col;
  11366. } else {
  11367. errLen = Math.min(src.length + 1, maxWidth) - col;
  11368. errEnd = '…';
  11369. }
  11370. }
  11371. const offset = col > 1 ? ' '.repeat(col - 1) : '';
  11372. const err = '^'.repeat(errLen);
  11373. return `${src}\n${offset}${err}${errEnd}`;
  11374. }
  11375. class Range {
  11376. static copy(orig) {
  11377. return new Range(orig.start, orig.end);
  11378. }
  11379. constructor(start, end) {
  11380. this.start = start;
  11381. this.end = end || start;
  11382. }
  11383. isEmpty() {
  11384. return typeof this.start !== 'number' || !this.end || this.end <= this.start;
  11385. }
  11386. /**
  11387. * Set `origStart` and `origEnd` to point to the original source range for
  11388. * this node, which may differ due to dropped CR characters.
  11389. *
  11390. * @param {number[]} cr - Positions of dropped CR characters
  11391. * @param {number} offset - Starting index of `cr` from the last call
  11392. * @returns {number} - The next offset, matching the one found for `origStart`
  11393. */
  11394. setOrigRange(cr, offset) {
  11395. const {
  11396. start,
  11397. end
  11398. } = this;
  11399. if (cr.length === 0 || end <= cr[0]) {
  11400. this.origStart = start;
  11401. this.origEnd = end;
  11402. return offset;
  11403. }
  11404. let i = offset;
  11405. while (i < cr.length) {
  11406. if (cr[i] > start) break;else ++i;
  11407. }
  11408. this.origStart = start + i;
  11409. const nextOffset = i;
  11410. while (i < cr.length) {
  11411. // if end was at \n, it should now be at \r
  11412. if (cr[i] >= end) break;else ++i;
  11413. }
  11414. this.origEnd = end + i;
  11415. return nextOffset;
  11416. }
  11417. }
  11418. /** Root class of all nodes */
  11419. class Node$2 {
  11420. static addStringTerminator(src, offset, str) {
  11421. if (str[str.length - 1] === '\n') return str;
  11422. const next = Node$2.endOfWhiteSpace(src, offset);
  11423. return next >= src.length || src[next] === '\n' ? str + '\n' : str;
  11424. } // ^(---|...)
  11425. static atDocumentBoundary(src, offset, sep) {
  11426. const ch0 = src[offset];
  11427. if (!ch0) return true;
  11428. const prev = src[offset - 1];
  11429. if (prev && prev !== '\n') return false;
  11430. if (sep) {
  11431. if (ch0 !== sep) return false;
  11432. } else {
  11433. if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false;
  11434. }
  11435. const ch1 = src[offset + 1];
  11436. const ch2 = src[offset + 2];
  11437. if (ch1 !== ch0 || ch2 !== ch0) return false;
  11438. const ch3 = src[offset + 3];
  11439. return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' ';
  11440. }
  11441. static endOfIdentifier(src, offset) {
  11442. let ch = src[offset];
  11443. const isVerbatim = ch === '<';
  11444. const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ','];
  11445. while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1];
  11446. if (isVerbatim && ch === '>') offset += 1;
  11447. return offset;
  11448. }
  11449. static endOfIndent(src, offset) {
  11450. let ch = src[offset];
  11451. while (ch === ' ') ch = src[offset += 1];
  11452. return offset;
  11453. }
  11454. static endOfLine(src, offset) {
  11455. let ch = src[offset];
  11456. while (ch && ch !== '\n') ch = src[offset += 1];
  11457. return offset;
  11458. }
  11459. static endOfWhiteSpace(src, offset) {
  11460. let ch = src[offset];
  11461. while (ch === '\t' || ch === ' ') ch = src[offset += 1];
  11462. return offset;
  11463. }
  11464. static startOfLine(src, offset) {
  11465. let ch = src[offset - 1];
  11466. if (ch === '\n') return offset;
  11467. while (ch && ch !== '\n') ch = src[offset -= 1];
  11468. return offset + 1;
  11469. }
  11470. /**
  11471. * End of indentation, or null if the line's indent level is not more
  11472. * than `indent`
  11473. *
  11474. * @param {string} src
  11475. * @param {number} indent
  11476. * @param {number} lineStart
  11477. * @returns {?number}
  11478. */
  11479. static endOfBlockIndent(src, indent, lineStart) {
  11480. const inEnd = Node$2.endOfIndent(src, lineStart);
  11481. if (inEnd > lineStart + indent) {
  11482. return inEnd;
  11483. } else {
  11484. const wsEnd = Node$2.endOfWhiteSpace(src, inEnd);
  11485. const ch = src[wsEnd];
  11486. if (!ch || ch === '\n') return wsEnd;
  11487. }
  11488. return null;
  11489. }
  11490. static atBlank(src, offset, endAsBlank) {
  11491. const ch = src[offset];
  11492. return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch;
  11493. }
  11494. static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) {
  11495. if (!ch || indentDiff < 0) return false;
  11496. if (indentDiff > 0) return true;
  11497. return indicatorAsIndent && ch === '-';
  11498. } // should be at line or string end, or at next non-whitespace char
  11499. static normalizeOffset(src, offset) {
  11500. const ch = src[offset];
  11501. return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node$2.endOfWhiteSpace(src, offset);
  11502. } // fold single newline into space, multiple newlines to N - 1 newlines
  11503. // presumes src[offset] === '\n'
  11504. static foldNewline(src, offset, indent) {
  11505. let inCount = 0;
  11506. let error = false;
  11507. let fold = '';
  11508. let ch = src[offset + 1];
  11509. while (ch === ' ' || ch === '\t' || ch === '\n') {
  11510. switch (ch) {
  11511. case '\n':
  11512. inCount = 0;
  11513. offset += 1;
  11514. fold += '\n';
  11515. break;
  11516. case '\t':
  11517. if (inCount <= indent) error = true;
  11518. offset = Node$2.endOfWhiteSpace(src, offset + 2) - 1;
  11519. break;
  11520. case ' ':
  11521. inCount += 1;
  11522. offset += 1;
  11523. break;
  11524. }
  11525. ch = src[offset + 1];
  11526. }
  11527. if (!fold) fold = ' ';
  11528. if (ch && inCount <= indent) error = true;
  11529. return {
  11530. fold,
  11531. offset,
  11532. error
  11533. };
  11534. }
  11535. constructor(type, props, context) {
  11536. Object.defineProperty(this, 'context', {
  11537. value: context || null,
  11538. writable: true
  11539. });
  11540. this.error = null;
  11541. this.range = null;
  11542. this.valueRange = null;
  11543. this.props = props || [];
  11544. this.type = type;
  11545. this.value = null;
  11546. }
  11547. getPropValue(idx, key, skipKey) {
  11548. if (!this.context) return null;
  11549. const {
  11550. src
  11551. } = this.context;
  11552. const prop = this.props[idx];
  11553. return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null;
  11554. }
  11555. get anchor() {
  11556. for (let i = 0; i < this.props.length; ++i) {
  11557. const anchor = this.getPropValue(i, Char.ANCHOR, true);
  11558. if (anchor != null) return anchor;
  11559. }
  11560. return null;
  11561. }
  11562. get comment() {
  11563. const comments = [];
  11564. for (let i = 0; i < this.props.length; ++i) {
  11565. const comment = this.getPropValue(i, Char.COMMENT, true);
  11566. if (comment != null) comments.push(comment);
  11567. }
  11568. return comments.length > 0 ? comments.join('\n') : null;
  11569. }
  11570. commentHasRequiredWhitespace(start) {
  11571. const {
  11572. src
  11573. } = this.context;
  11574. if (this.header && start === this.header.end) return false;
  11575. if (!this.valueRange) return false;
  11576. const {
  11577. end
  11578. } = this.valueRange;
  11579. return start !== end || Node$2.atBlank(src, end - 1);
  11580. }
  11581. get hasComment() {
  11582. if (this.context) {
  11583. const {
  11584. src
  11585. } = this.context;
  11586. for (let i = 0; i < this.props.length; ++i) {
  11587. if (src[this.props[i].start] === Char.COMMENT) return true;
  11588. }
  11589. }
  11590. return false;
  11591. }
  11592. get hasProps() {
  11593. if (this.context) {
  11594. const {
  11595. src
  11596. } = this.context;
  11597. for (let i = 0; i < this.props.length; ++i) {
  11598. if (src[this.props[i].start] !== Char.COMMENT) return true;
  11599. }
  11600. }
  11601. return false;
  11602. }
  11603. get includesTrailingLines() {
  11604. return false;
  11605. }
  11606. get jsonLike() {
  11607. const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE];
  11608. return jsonLikeTypes.indexOf(this.type) !== -1;
  11609. }
  11610. get rangeAsLinePos() {
  11611. if (!this.range || !this.context) return undefined;
  11612. const start = getLinePos(this.range.start, this.context.root);
  11613. if (!start) return undefined;
  11614. const end = getLinePos(this.range.end, this.context.root);
  11615. return {
  11616. start,
  11617. end
  11618. };
  11619. }
  11620. get rawValue() {
  11621. if (!this.valueRange || !this.context) return null;
  11622. const {
  11623. start,
  11624. end
  11625. } = this.valueRange;
  11626. return this.context.src.slice(start, end);
  11627. }
  11628. get tag() {
  11629. for (let i = 0; i < this.props.length; ++i) {
  11630. const tag = this.getPropValue(i, Char.TAG, false);
  11631. if (tag != null) {
  11632. if (tag[1] === '<') {
  11633. return {
  11634. verbatim: tag.slice(2, -1)
  11635. };
  11636. } else {
  11637. // eslint-disable-next-line no-unused-vars
  11638. const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/);
  11639. return {
  11640. handle,
  11641. suffix
  11642. };
  11643. }
  11644. }
  11645. }
  11646. return null;
  11647. }
  11648. get valueRangeContainsNewline() {
  11649. if (!this.valueRange || !this.context) return false;
  11650. const {
  11651. start,
  11652. end
  11653. } = this.valueRange;
  11654. const {
  11655. src
  11656. } = this.context;
  11657. for (let i = start; i < end; ++i) {
  11658. if (src[i] === '\n') return true;
  11659. }
  11660. return false;
  11661. }
  11662. parseComment(start) {
  11663. const {
  11664. src
  11665. } = this.context;
  11666. if (src[start] === Char.COMMENT) {
  11667. const end = Node$2.endOfLine(src, start + 1);
  11668. const commentRange = new Range(start, end);
  11669. this.props.push(commentRange);
  11670. return end;
  11671. }
  11672. return start;
  11673. }
  11674. /**
  11675. * Populates the `origStart` and `origEnd` values of all ranges for this
  11676. * node. Extended by child classes to handle descendant nodes.
  11677. *
  11678. * @param {number[]} cr - Positions of dropped CR characters
  11679. * @param {number} offset - Starting index of `cr` from the last call
  11680. * @returns {number} - The next offset, matching the one found for `origStart`
  11681. */
  11682. setOrigRanges(cr, offset) {
  11683. if (this.range) offset = this.range.setOrigRange(cr, offset);
  11684. if (this.valueRange) this.valueRange.setOrigRange(cr, offset);
  11685. this.props.forEach(prop => prop.setOrigRange(cr, offset));
  11686. return offset;
  11687. }
  11688. toString() {
  11689. const {
  11690. context: {
  11691. src
  11692. },
  11693. range,
  11694. value
  11695. } = this;
  11696. if (value != null) return value;
  11697. const str = src.slice(range.start, range.end);
  11698. return Node$2.addStringTerminator(src, range.end, str);
  11699. }
  11700. }
  11701. class YAMLError extends Error {
  11702. constructor(name, source, message) {
  11703. if (!message || !(source instanceof Node$2)) throw new Error(`Invalid arguments for new ${name}`);
  11704. super();
  11705. this.name = name;
  11706. this.message = message;
  11707. this.source = source;
  11708. }
  11709. makePretty() {
  11710. if (!this.source) return;
  11711. this.nodeType = this.source.type;
  11712. const cst = this.source.context && this.source.context.root;
  11713. if (typeof this.offset === 'number') {
  11714. this.range = new Range(this.offset, this.offset + 1);
  11715. const start = cst && getLinePos(this.offset, cst);
  11716. if (start) {
  11717. const end = {
  11718. line: start.line,
  11719. col: start.col + 1
  11720. };
  11721. this.linePos = {
  11722. start,
  11723. end
  11724. };
  11725. }
  11726. delete this.offset;
  11727. } else {
  11728. this.range = this.source.range;
  11729. this.linePos = this.source.rangeAsLinePos;
  11730. }
  11731. if (this.linePos) {
  11732. const {
  11733. line,
  11734. col
  11735. } = this.linePos.start;
  11736. this.message += ` at line ${line}, column ${col}`;
  11737. const ctx = cst && getPrettyContext(this.linePos, cst);
  11738. if (ctx) this.message += `:\n\n${ctx}\n`;
  11739. }
  11740. delete this.source;
  11741. }
  11742. }
  11743. class YAMLReferenceError extends YAMLError {
  11744. constructor(source, message) {
  11745. super('YAMLReferenceError', source, message);
  11746. }
  11747. }
  11748. class YAMLSemanticError extends YAMLError {
  11749. constructor(source, message) {
  11750. super('YAMLSemanticError', source, message);
  11751. }
  11752. }
  11753. class YAMLSyntaxError extends YAMLError {
  11754. constructor(source, message) {
  11755. super('YAMLSyntaxError', source, message);
  11756. }
  11757. }
  11758. class YAMLWarning extends YAMLError {
  11759. constructor(source, message) {
  11760. super('YAMLWarning', source, message);
  11761. }
  11762. }
  11763. function _defineProperty(obj, key, value) {
  11764. if (key in obj) {
  11765. Object.defineProperty(obj, key, {
  11766. value: value,
  11767. enumerable: true,
  11768. configurable: true,
  11769. writable: true
  11770. });
  11771. } else {
  11772. obj[key] = value;
  11773. }
  11774. return obj;
  11775. }
  11776. class PlainValue$6 extends Node$2 {
  11777. static endOfLine(src, start, inFlow) {
  11778. let ch = src[start];
  11779. let offset = start;
  11780. while (ch && ch !== '\n') {
  11781. if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break;
  11782. const next = src[offset + 1];
  11783. if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break;
  11784. if ((ch === ' ' || ch === '\t') && next === '#') break;
  11785. offset += 1;
  11786. ch = next;
  11787. }
  11788. return offset;
  11789. }
  11790. get strValue() {
  11791. if (!this.valueRange || !this.context) return null;
  11792. let {
  11793. start,
  11794. end
  11795. } = this.valueRange;
  11796. const {
  11797. src
  11798. } = this.context;
  11799. let ch = src[end - 1];
  11800. while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1];
  11801. let str = '';
  11802. for (let i = start; i < end; ++i) {
  11803. const ch = src[i];
  11804. if (ch === '\n') {
  11805. const {
  11806. fold,
  11807. offset
  11808. } = Node$2.foldNewline(src, i, -1);
  11809. str += fold;
  11810. i = offset;
  11811. } else if (ch === ' ' || ch === '\t') {
  11812. // trim trailing whitespace
  11813. const wsStart = i;
  11814. let next = src[i + 1];
  11815. while (i < end && (next === ' ' || next === '\t')) {
  11816. i += 1;
  11817. next = src[i + 1];
  11818. }
  11819. if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
  11820. } else {
  11821. str += ch;
  11822. }
  11823. }
  11824. const ch0 = src[start];
  11825. switch (ch0) {
  11826. case '\t':
  11827. {
  11828. const msg = 'Plain value cannot start with a tab character';
  11829. const errors = [new YAMLSemanticError(this, msg)];
  11830. return {
  11831. errors,
  11832. str
  11833. };
  11834. }
  11835. case '@':
  11836. case '`':
  11837. {
  11838. const msg = `Plain value cannot start with reserved character ${ch0}`;
  11839. const errors = [new YAMLSemanticError(this, msg)];
  11840. return {
  11841. errors,
  11842. str
  11843. };
  11844. }
  11845. default:
  11846. return str;
  11847. }
  11848. }
  11849. parseBlockValue(start) {
  11850. const {
  11851. indent,
  11852. inFlow,
  11853. src
  11854. } = this.context;
  11855. let offset = start;
  11856. let valueEnd = start;
  11857. for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
  11858. if (Node$2.atDocumentBoundary(src, offset + 1)) break;
  11859. const end = Node$2.endOfBlockIndent(src, indent, offset + 1);
  11860. if (end === null || src[end] === '#') break;
  11861. if (src[end] === '\n') {
  11862. offset = end;
  11863. } else {
  11864. valueEnd = PlainValue$6.endOfLine(src, end, inFlow);
  11865. offset = valueEnd;
  11866. }
  11867. }
  11868. if (this.valueRange.isEmpty()) this.valueRange.start = start;
  11869. this.valueRange.end = valueEnd;
  11870. return valueEnd;
  11871. }
  11872. /**
  11873. * Parses a plain value from the source
  11874. *
  11875. * Accepted forms are:
  11876. * ```
  11877. * #comment
  11878. *
  11879. * first line
  11880. *
  11881. * first line #comment
  11882. *
  11883. * first line
  11884. * block
  11885. * lines
  11886. *
  11887. * #comment
  11888. * block
  11889. * lines
  11890. * ```
  11891. * where block lines are empty or have an indent level greater than `indent`.
  11892. *
  11893. * @param {ParseContext} context
  11894. * @param {number} start - Index of first character
  11895. * @returns {number} - Index of the character after this scalar, may be `\n`
  11896. */
  11897. parse(context, start) {
  11898. this.context = context;
  11899. const {
  11900. inFlow,
  11901. src
  11902. } = context;
  11903. let offset = start;
  11904. const ch = src[offset];
  11905. if (ch && ch !== '#' && ch !== '\n') {
  11906. offset = PlainValue$6.endOfLine(src, start, inFlow);
  11907. }
  11908. this.valueRange = new Range(start, offset);
  11909. offset = Node$2.endOfWhiteSpace(src, offset);
  11910. offset = this.parseComment(offset);
  11911. if (!this.hasComment || this.valueRange.isEmpty()) {
  11912. offset = this.parseBlockValue(offset);
  11913. }
  11914. return offset;
  11915. }
  11916. }
  11917. PlainValueEc8e588e.Char = Char;
  11918. PlainValueEc8e588e.Node = Node$2;
  11919. PlainValueEc8e588e.PlainValue = PlainValue$6;
  11920. PlainValueEc8e588e.Range = Range;
  11921. PlainValueEc8e588e.Type = Type;
  11922. PlainValueEc8e588e.YAMLError = YAMLError;
  11923. PlainValueEc8e588e.YAMLReferenceError = YAMLReferenceError;
  11924. PlainValueEc8e588e.YAMLSemanticError = YAMLSemanticError;
  11925. PlainValueEc8e588e.YAMLSyntaxError = YAMLSyntaxError;
  11926. PlainValueEc8e588e.YAMLWarning = YAMLWarning;
  11927. PlainValueEc8e588e._defineProperty = _defineProperty;
  11928. PlainValueEc8e588e.defaultTagPrefix = defaultTagPrefix;
  11929. PlainValueEc8e588e.defaultTags = defaultTags;
  11930. var PlainValue$5 = PlainValueEc8e588e;
  11931. class BlankLine extends PlainValue$5.Node {
  11932. constructor() {
  11933. super(PlainValue$5.Type.BLANK_LINE);
  11934. }
  11935. /* istanbul ignore next */
  11936. get includesTrailingLines() {
  11937. // This is never called from anywhere, but if it were,
  11938. // this is the value it should return.
  11939. return true;
  11940. }
  11941. /**
  11942. * Parses a blank line from the source
  11943. *
  11944. * @param {ParseContext} context
  11945. * @param {number} start - Index of first \n character
  11946. * @returns {number} - Index of the character after this
  11947. */
  11948. parse(context, start) {
  11949. this.context = context;
  11950. this.range = new PlainValue$5.Range(start, start + 1);
  11951. return start + 1;
  11952. }
  11953. }
  11954. class CollectionItem extends PlainValue$5.Node {
  11955. constructor(type, props) {
  11956. super(type, props);
  11957. this.node = null;
  11958. }
  11959. get includesTrailingLines() {
  11960. return !!this.node && this.node.includesTrailingLines;
  11961. }
  11962. /**
  11963. * @param {ParseContext} context
  11964. * @param {number} start - Index of first character
  11965. * @returns {number} - Index of the character after this
  11966. */
  11967. parse(context, start) {
  11968. this.context = context;
  11969. const {
  11970. parseNode,
  11971. src
  11972. } = context;
  11973. let {
  11974. atLineStart,
  11975. lineStart
  11976. } = context;
  11977. if (!atLineStart && this.type === PlainValue$5.Type.SEQ_ITEM) this.error = new PlainValue$5.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line');
  11978. const indent = atLineStart ? start - lineStart : context.indent;
  11979. let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1);
  11980. let ch = src[offset];
  11981. const inlineComment = ch === '#';
  11982. const comments = [];
  11983. let blankLine = null;
  11984. while (ch === '\n' || ch === '#') {
  11985. if (ch === '#') {
  11986. const end = PlainValue$5.Node.endOfLine(src, offset + 1);
  11987. comments.push(new PlainValue$5.Range(offset, end));
  11988. offset = end;
  11989. } else {
  11990. atLineStart = true;
  11991. lineStart = offset + 1;
  11992. const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
  11993. if (src[wsEnd] === '\n' && comments.length === 0) {
  11994. blankLine = new BlankLine();
  11995. lineStart = blankLine.parse({
  11996. src
  11997. }, lineStart);
  11998. }
  11999. offset = PlainValue$5.Node.endOfIndent(src, lineStart);
  12000. }
  12001. ch = src[offset];
  12002. }
  12003. if (PlainValue$5.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue$5.Type.SEQ_ITEM)) {
  12004. this.node = parseNode({
  12005. atLineStart,
  12006. inCollection: false,
  12007. indent,
  12008. lineStart,
  12009. parent: this
  12010. }, offset);
  12011. } else if (ch && lineStart > start + 1) {
  12012. offset = lineStart - 1;
  12013. }
  12014. if (this.node) {
  12015. if (blankLine) {
  12016. // Only blank lines preceding non-empty nodes are captured. Note that
  12017. // this means that collection item range start indices do not always
  12018. // increase monotonically. -- eemeli/yaml#126
  12019. const items = context.parent.items || context.parent.contents;
  12020. if (items) items.push(blankLine);
  12021. }
  12022. if (comments.length) Array.prototype.push.apply(this.props, comments);
  12023. offset = this.node.range.end;
  12024. } else {
  12025. if (inlineComment) {
  12026. const c = comments[0];
  12027. this.props.push(c);
  12028. offset = c.end;
  12029. } else {
  12030. offset = PlainValue$5.Node.endOfLine(src, start + 1);
  12031. }
  12032. }
  12033. const end = this.node ? this.node.valueRange.end : offset;
  12034. this.valueRange = new PlainValue$5.Range(start, end);
  12035. return offset;
  12036. }
  12037. setOrigRanges(cr, offset) {
  12038. offset = super.setOrigRanges(cr, offset);
  12039. return this.node ? this.node.setOrigRanges(cr, offset) : offset;
  12040. }
  12041. toString() {
  12042. const {
  12043. context: {
  12044. src
  12045. },
  12046. node,
  12047. range,
  12048. value
  12049. } = this;
  12050. if (value != null) return value;
  12051. const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end);
  12052. return PlainValue$5.Node.addStringTerminator(src, range.end, str);
  12053. }
  12054. }
  12055. class Comment extends PlainValue$5.Node {
  12056. constructor() {
  12057. super(PlainValue$5.Type.COMMENT);
  12058. }
  12059. /**
  12060. * Parses a comment line from the source
  12061. *
  12062. * @param {ParseContext} context
  12063. * @param {number} start - Index of first character
  12064. * @returns {number} - Index of the character after this scalar
  12065. */
  12066. parse(context, start) {
  12067. this.context = context;
  12068. const offset = this.parseComment(start);
  12069. this.range = new PlainValue$5.Range(start, offset);
  12070. return offset;
  12071. }
  12072. }
  12073. function grabCollectionEndComments(node) {
  12074. let cnode = node;
  12075. while (cnode instanceof CollectionItem) cnode = cnode.node;
  12076. if (!(cnode instanceof Collection$1)) return null;
  12077. const len = cnode.items.length;
  12078. let ci = -1;
  12079. for (let i = len - 1; i >= 0; --i) {
  12080. const n = cnode.items[i];
  12081. if (n.type === PlainValue$5.Type.COMMENT) {
  12082. // Keep sufficiently indented comments with preceding node
  12083. const {
  12084. indent,
  12085. lineStart
  12086. } = n.context;
  12087. if (indent > 0 && n.range.start >= lineStart + indent) break;
  12088. ci = i;
  12089. } else if (n.type === PlainValue$5.Type.BLANK_LINE) ci = i;else break;
  12090. }
  12091. if (ci === -1) return null;
  12092. const ca = cnode.items.splice(ci, len - ci);
  12093. const prevEnd = ca[0].range.start;
  12094. while (true) {
  12095. cnode.range.end = prevEnd;
  12096. if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd;
  12097. if (cnode === node) break;
  12098. cnode = cnode.context.parent;
  12099. }
  12100. return ca;
  12101. }
  12102. class Collection$1 extends PlainValue$5.Node {
  12103. static nextContentHasIndent(src, offset, indent) {
  12104. const lineStart = PlainValue$5.Node.endOfLine(src, offset) + 1;
  12105. offset = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
  12106. const ch = src[offset];
  12107. if (!ch) return false;
  12108. if (offset >= lineStart + indent) return true;
  12109. if (ch !== '#' && ch !== '\n') return false;
  12110. return Collection$1.nextContentHasIndent(src, offset, indent);
  12111. }
  12112. constructor(firstItem) {
  12113. super(firstItem.type === PlainValue$5.Type.SEQ_ITEM ? PlainValue$5.Type.SEQ : PlainValue$5.Type.MAP);
  12114. for (let i = firstItem.props.length - 1; i >= 0; --i) {
  12115. if (firstItem.props[i].start < firstItem.context.lineStart) {
  12116. // props on previous line are assumed by the collection
  12117. this.props = firstItem.props.slice(0, i + 1);
  12118. firstItem.props = firstItem.props.slice(i + 1);
  12119. const itemRange = firstItem.props[0] || firstItem.valueRange;
  12120. firstItem.range.start = itemRange.start;
  12121. break;
  12122. }
  12123. }
  12124. this.items = [firstItem];
  12125. const ec = grabCollectionEndComments(firstItem);
  12126. if (ec) Array.prototype.push.apply(this.items, ec);
  12127. }
  12128. get includesTrailingLines() {
  12129. return this.items.length > 0;
  12130. }
  12131. /**
  12132. * @param {ParseContext} context
  12133. * @param {number} start - Index of first character
  12134. * @returns {number} - Index of the character after this
  12135. */
  12136. parse(context, start) {
  12137. this.context = context;
  12138. const {
  12139. parseNode,
  12140. src
  12141. } = context; // It's easier to recalculate lineStart here rather than tracking down the
  12142. // last context from which to read it -- eemeli/yaml#2
  12143. let lineStart = PlainValue$5.Node.startOfLine(src, start);
  12144. const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling
  12145. // -- eemeli/yaml#17
  12146. firstItem.context.parent = this;
  12147. this.valueRange = PlainValue$5.Range.copy(firstItem.valueRange);
  12148. const indent = firstItem.range.start - firstItem.context.lineStart;
  12149. let offset = start;
  12150. offset = PlainValue$5.Node.normalizeOffset(src, offset);
  12151. let ch = src[offset];
  12152. let atLineStart = PlainValue$5.Node.endOfWhiteSpace(src, lineStart) === offset;
  12153. let prevIncludesTrailingLines = false;
  12154. while (ch) {
  12155. while (ch === '\n' || ch === '#') {
  12156. if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) {
  12157. const blankLine = new BlankLine();
  12158. offset = blankLine.parse({
  12159. src
  12160. }, offset);
  12161. this.valueRange.end = offset;
  12162. if (offset >= src.length) {
  12163. ch = null;
  12164. break;
  12165. }
  12166. this.items.push(blankLine);
  12167. offset -= 1; // blankLine.parse() consumes terminal newline
  12168. } else if (ch === '#') {
  12169. if (offset < lineStart + indent && !Collection$1.nextContentHasIndent(src, offset, indent)) {
  12170. return offset;
  12171. }
  12172. const comment = new Comment();
  12173. offset = comment.parse({
  12174. indent,
  12175. lineStart,
  12176. src
  12177. }, offset);
  12178. this.items.push(comment);
  12179. this.valueRange.end = offset;
  12180. if (offset >= src.length) {
  12181. ch = null;
  12182. break;
  12183. }
  12184. }
  12185. lineStart = offset + 1;
  12186. offset = PlainValue$5.Node.endOfIndent(src, lineStart);
  12187. if (PlainValue$5.Node.atBlank(src, offset)) {
  12188. const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  12189. const next = src[wsEnd];
  12190. if (!next || next === '\n' || next === '#') {
  12191. offset = wsEnd;
  12192. }
  12193. }
  12194. ch = src[offset];
  12195. atLineStart = true;
  12196. }
  12197. if (!ch) {
  12198. break;
  12199. }
  12200. if (offset !== lineStart + indent && (atLineStart || ch !== ':')) {
  12201. if (offset < lineStart + indent) {
  12202. if (lineStart > start) offset = lineStart;
  12203. break;
  12204. } else if (!this.error) {
  12205. const msg = 'All collection items must start at the same column';
  12206. this.error = new PlainValue$5.YAMLSyntaxError(this, msg);
  12207. }
  12208. }
  12209. if (firstItem.type === PlainValue$5.Type.SEQ_ITEM) {
  12210. if (ch !== '-') {
  12211. if (lineStart > start) offset = lineStart;
  12212. break;
  12213. }
  12214. } else if (ch === '-' && !this.error) {
  12215. // map key may start with -, as long as it's followed by a non-whitespace char
  12216. const next = src[offset + 1];
  12217. if (!next || next === '\n' || next === '\t' || next === ' ') {
  12218. const msg = 'A collection cannot be both a mapping and a sequence';
  12219. this.error = new PlainValue$5.YAMLSyntaxError(this, msg);
  12220. }
  12221. }
  12222. const node = parseNode({
  12223. atLineStart,
  12224. inCollection: true,
  12225. indent,
  12226. lineStart,
  12227. parent: this
  12228. }, offset);
  12229. if (!node) return offset; // at next document start
  12230. this.items.push(node);
  12231. this.valueRange.end = node.valueRange.end;
  12232. offset = PlainValue$5.Node.normalizeOffset(src, node.range.end);
  12233. ch = src[offset];
  12234. atLineStart = false;
  12235. prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range
  12236. // has advanced to check the current line's indentation level
  12237. // -- eemeli/yaml#10 & eemeli/yaml#38
  12238. if (ch) {
  12239. let ls = offset - 1;
  12240. let prev = src[ls];
  12241. while (prev === ' ' || prev === '\t') prev = src[--ls];
  12242. if (prev === '\n') {
  12243. lineStart = ls + 1;
  12244. atLineStart = true;
  12245. }
  12246. }
  12247. const ec = grabCollectionEndComments(node);
  12248. if (ec) Array.prototype.push.apply(this.items, ec);
  12249. }
  12250. return offset;
  12251. }
  12252. setOrigRanges(cr, offset) {
  12253. offset = super.setOrigRanges(cr, offset);
  12254. this.items.forEach(node => {
  12255. offset = node.setOrigRanges(cr, offset);
  12256. });
  12257. return offset;
  12258. }
  12259. toString() {
  12260. const {
  12261. context: {
  12262. src
  12263. },
  12264. items,
  12265. range,
  12266. value
  12267. } = this;
  12268. if (value != null) return value;
  12269. let str = src.slice(range.start, items[0].range.start) + String(items[0]);
  12270. for (let i = 1; i < items.length; ++i) {
  12271. const item = items[i];
  12272. const {
  12273. atLineStart,
  12274. indent
  12275. } = item.context;
  12276. if (atLineStart) for (let i = 0; i < indent; ++i) str += ' ';
  12277. str += String(item);
  12278. }
  12279. return PlainValue$5.Node.addStringTerminator(src, range.end, str);
  12280. }
  12281. }
  12282. class Directive extends PlainValue$5.Node {
  12283. constructor() {
  12284. super(PlainValue$5.Type.DIRECTIVE);
  12285. this.name = null;
  12286. }
  12287. get parameters() {
  12288. const raw = this.rawValue;
  12289. return raw ? raw.trim().split(/[ \t]+/) : [];
  12290. }
  12291. parseName(start) {
  12292. const {
  12293. src
  12294. } = this.context;
  12295. let offset = start;
  12296. let ch = src[offset];
  12297. while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1];
  12298. this.name = src.slice(start, offset);
  12299. return offset;
  12300. }
  12301. parseParameters(start) {
  12302. const {
  12303. src
  12304. } = this.context;
  12305. let offset = start;
  12306. let ch = src[offset];
  12307. while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1];
  12308. this.valueRange = new PlainValue$5.Range(start, offset);
  12309. return offset;
  12310. }
  12311. parse(context, start) {
  12312. this.context = context;
  12313. let offset = this.parseName(start + 1);
  12314. offset = this.parseParameters(offset);
  12315. offset = this.parseComment(offset);
  12316. this.range = new PlainValue$5.Range(start, offset);
  12317. return offset;
  12318. }
  12319. }
  12320. class Document$3 extends PlainValue$5.Node {
  12321. static startCommentOrEndBlankLine(src, start) {
  12322. const offset = PlainValue$5.Node.endOfWhiteSpace(src, start);
  12323. const ch = src[offset];
  12324. return ch === '#' || ch === '\n' ? offset : start;
  12325. }
  12326. constructor() {
  12327. super(PlainValue$5.Type.DOCUMENT);
  12328. this.directives = null;
  12329. this.contents = null;
  12330. this.directivesEndMarker = null;
  12331. this.documentEndMarker = null;
  12332. }
  12333. parseDirectives(start) {
  12334. const {
  12335. src
  12336. } = this.context;
  12337. this.directives = [];
  12338. let atLineStart = true;
  12339. let hasDirectives = false;
  12340. let offset = start;
  12341. while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DIRECTIVES_END)) {
  12342. offset = Document$3.startCommentOrEndBlankLine(src, offset);
  12343. switch (src[offset]) {
  12344. case '\n':
  12345. if (atLineStart) {
  12346. const blankLine = new BlankLine();
  12347. offset = blankLine.parse({
  12348. src
  12349. }, offset);
  12350. if (offset < src.length) {
  12351. this.directives.push(blankLine);
  12352. }
  12353. } else {
  12354. offset += 1;
  12355. atLineStart = true;
  12356. }
  12357. break;
  12358. case '#':
  12359. {
  12360. const comment = new Comment();
  12361. offset = comment.parse({
  12362. src
  12363. }, offset);
  12364. this.directives.push(comment);
  12365. atLineStart = false;
  12366. }
  12367. break;
  12368. case '%':
  12369. {
  12370. const directive = new Directive();
  12371. offset = directive.parse({
  12372. parent: this,
  12373. src
  12374. }, offset);
  12375. this.directives.push(directive);
  12376. hasDirectives = true;
  12377. atLineStart = false;
  12378. }
  12379. break;
  12380. default:
  12381. if (hasDirectives) {
  12382. this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line');
  12383. } else if (this.directives.length > 0) {
  12384. this.contents = this.directives;
  12385. this.directives = [];
  12386. }
  12387. return offset;
  12388. }
  12389. }
  12390. if (src[offset]) {
  12391. this.directivesEndMarker = new PlainValue$5.Range(offset, offset + 3);
  12392. return offset + 3;
  12393. }
  12394. if (hasDirectives) {
  12395. this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line');
  12396. } else if (this.directives.length > 0) {
  12397. this.contents = this.directives;
  12398. this.directives = [];
  12399. }
  12400. return offset;
  12401. }
  12402. parseContents(start) {
  12403. const {
  12404. parseNode,
  12405. src
  12406. } = this.context;
  12407. if (!this.contents) this.contents = [];
  12408. let lineStart = start;
  12409. while (src[lineStart - 1] === '-') lineStart -= 1;
  12410. let offset = PlainValue$5.Node.endOfWhiteSpace(src, start);
  12411. let atLineStart = lineStart === start;
  12412. this.valueRange = new PlainValue$5.Range(offset);
  12413. while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DOCUMENT_END)) {
  12414. switch (src[offset]) {
  12415. case '\n':
  12416. if (atLineStart) {
  12417. const blankLine = new BlankLine();
  12418. offset = blankLine.parse({
  12419. src
  12420. }, offset);
  12421. if (offset < src.length) {
  12422. this.contents.push(blankLine);
  12423. }
  12424. } else {
  12425. offset += 1;
  12426. atLineStart = true;
  12427. }
  12428. lineStart = offset;
  12429. break;
  12430. case '#':
  12431. {
  12432. const comment = new Comment();
  12433. offset = comment.parse({
  12434. src
  12435. }, offset);
  12436. this.contents.push(comment);
  12437. atLineStart = false;
  12438. }
  12439. break;
  12440. default:
  12441. {
  12442. const iEnd = PlainValue$5.Node.endOfIndent(src, offset);
  12443. const context = {
  12444. atLineStart,
  12445. indent: -1,
  12446. inFlow: false,
  12447. inCollection: false,
  12448. lineStart,
  12449. parent: this
  12450. };
  12451. const node = parseNode(context, iEnd);
  12452. if (!node) return this.valueRange.end = iEnd; // at next document start
  12453. this.contents.push(node);
  12454. offset = node.range.end;
  12455. atLineStart = false;
  12456. const ec = grabCollectionEndComments(node);
  12457. if (ec) Array.prototype.push.apply(this.contents, ec);
  12458. }
  12459. }
  12460. offset = Document$3.startCommentOrEndBlankLine(src, offset);
  12461. }
  12462. this.valueRange.end = offset;
  12463. if (src[offset]) {
  12464. this.documentEndMarker = new PlainValue$5.Range(offset, offset + 3);
  12465. offset += 3;
  12466. if (src[offset]) {
  12467. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  12468. if (src[offset] === '#') {
  12469. const comment = new Comment();
  12470. offset = comment.parse({
  12471. src
  12472. }, offset);
  12473. this.contents.push(comment);
  12474. }
  12475. switch (src[offset]) {
  12476. case '\n':
  12477. offset += 1;
  12478. break;
  12479. case undefined:
  12480. break;
  12481. default:
  12482. this.error = new PlainValue$5.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix');
  12483. }
  12484. }
  12485. }
  12486. return offset;
  12487. }
  12488. /**
  12489. * @param {ParseContext} context
  12490. * @param {number} start - Index of first character
  12491. * @returns {number} - Index of the character after this
  12492. */
  12493. parse(context, start) {
  12494. context.root = this;
  12495. this.context = context;
  12496. const {
  12497. src
  12498. } = context;
  12499. let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM
  12500. offset = this.parseDirectives(offset);
  12501. offset = this.parseContents(offset);
  12502. return offset;
  12503. }
  12504. setOrigRanges(cr, offset) {
  12505. offset = super.setOrigRanges(cr, offset);
  12506. this.directives.forEach(node => {
  12507. offset = node.setOrigRanges(cr, offset);
  12508. });
  12509. if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset);
  12510. this.contents.forEach(node => {
  12511. offset = node.setOrigRanges(cr, offset);
  12512. });
  12513. if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset);
  12514. return offset;
  12515. }
  12516. toString() {
  12517. const {
  12518. contents,
  12519. directives,
  12520. value
  12521. } = this;
  12522. if (value != null) return value;
  12523. let str = directives.join('');
  12524. if (contents.length > 0) {
  12525. if (directives.length > 0 || contents[0].type === PlainValue$5.Type.COMMENT) str += '---\n';
  12526. str += contents.join('');
  12527. }
  12528. if (str[str.length - 1] !== '\n') str += '\n';
  12529. return str;
  12530. }
  12531. }
  12532. class Alias$1 extends PlainValue$5.Node {
  12533. /**
  12534. * Parses an *alias from the source
  12535. *
  12536. * @param {ParseContext} context
  12537. * @param {number} start - Index of first character
  12538. * @returns {number} - Index of the character after this scalar
  12539. */
  12540. parse(context, start) {
  12541. this.context = context;
  12542. const {
  12543. src
  12544. } = context;
  12545. let offset = PlainValue$5.Node.endOfIdentifier(src, start + 1);
  12546. this.valueRange = new PlainValue$5.Range(start + 1, offset);
  12547. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  12548. offset = this.parseComment(offset);
  12549. return offset;
  12550. }
  12551. }
  12552. const Chomp = {
  12553. CLIP: 'CLIP',
  12554. KEEP: 'KEEP',
  12555. STRIP: 'STRIP'
  12556. };
  12557. class BlockValue extends PlainValue$5.Node {
  12558. constructor(type, props) {
  12559. super(type, props);
  12560. this.blockIndent = null;
  12561. this.chomping = Chomp.CLIP;
  12562. this.header = null;
  12563. }
  12564. get includesTrailingLines() {
  12565. return this.chomping === Chomp.KEEP;
  12566. }
  12567. get strValue() {
  12568. if (!this.valueRange || !this.context) return null;
  12569. let {
  12570. start,
  12571. end
  12572. } = this.valueRange;
  12573. const {
  12574. indent,
  12575. src
  12576. } = this.context;
  12577. if (this.valueRange.isEmpty()) return '';
  12578. let lastNewLine = null;
  12579. let ch = src[end - 1];
  12580. while (ch === '\n' || ch === '\t' || ch === ' ') {
  12581. end -= 1;
  12582. if (end <= start) {
  12583. if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens
  12584. }
  12585. if (ch === '\n') lastNewLine = end;
  12586. ch = src[end - 1];
  12587. }
  12588. let keepStart = end + 1;
  12589. if (lastNewLine) {
  12590. if (this.chomping === Chomp.KEEP) {
  12591. keepStart = lastNewLine;
  12592. end = this.valueRange.end;
  12593. } else {
  12594. end = lastNewLine;
  12595. }
  12596. }
  12597. const bi = indent + this.blockIndent;
  12598. const folded = this.type === PlainValue$5.Type.BLOCK_FOLDED;
  12599. let atStart = true;
  12600. let str = '';
  12601. let sep = '';
  12602. let prevMoreIndented = false;
  12603. for (let i = start; i < end; ++i) {
  12604. for (let j = 0; j < bi; ++j) {
  12605. if (src[i] !== ' ') break;
  12606. i += 1;
  12607. }
  12608. const ch = src[i];
  12609. if (ch === '\n') {
  12610. if (sep === '\n') str += '\n';else sep = '\n';
  12611. } else {
  12612. const lineEnd = PlainValue$5.Node.endOfLine(src, i);
  12613. const line = src.slice(i, lineEnd);
  12614. i = lineEnd;
  12615. if (folded && (ch === ' ' || ch === '\t') && i < keepStart) {
  12616. if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n';
  12617. str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '')
  12618. sep = lineEnd < end && src[lineEnd] || '';
  12619. prevMoreIndented = true;
  12620. } else {
  12621. str += sep + line;
  12622. sep = folded && i < keepStart ? ' ' : '\n';
  12623. prevMoreIndented = false;
  12624. }
  12625. if (atStart && line !== '') atStart = false;
  12626. }
  12627. }
  12628. return this.chomping === Chomp.STRIP ? str : str + '\n';
  12629. }
  12630. parseBlockHeader(start) {
  12631. const {
  12632. src
  12633. } = this.context;
  12634. let offset = start + 1;
  12635. let bi = '';
  12636. while (true) {
  12637. const ch = src[offset];
  12638. switch (ch) {
  12639. case '-':
  12640. this.chomping = Chomp.STRIP;
  12641. break;
  12642. case '+':
  12643. this.chomping = Chomp.KEEP;
  12644. break;
  12645. case '0':
  12646. case '1':
  12647. case '2':
  12648. case '3':
  12649. case '4':
  12650. case '5':
  12651. case '6':
  12652. case '7':
  12653. case '8':
  12654. case '9':
  12655. bi += ch;
  12656. break;
  12657. default:
  12658. this.blockIndent = Number(bi) || null;
  12659. this.header = new PlainValue$5.Range(start, offset);
  12660. return offset;
  12661. }
  12662. offset += 1;
  12663. }
  12664. }
  12665. parseBlockValue(start) {
  12666. const {
  12667. indent,
  12668. src
  12669. } = this.context;
  12670. const explicit = !!this.blockIndent;
  12671. let offset = start;
  12672. let valueEnd = start;
  12673. let minBlockIndent = 1;
  12674. for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
  12675. offset += 1;
  12676. if (PlainValue$5.Node.atDocumentBoundary(src, offset)) break;
  12677. const end = PlainValue$5.Node.endOfBlockIndent(src, indent, offset); // should not include tab?
  12678. if (end === null) break;
  12679. const ch = src[end];
  12680. const lineIndent = end - (offset + indent);
  12681. if (!this.blockIndent) {
  12682. // no explicit block indent, none yet detected
  12683. if (src[end] !== '\n') {
  12684. // first line with non-whitespace content
  12685. if (lineIndent < minBlockIndent) {
  12686. const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
  12687. this.error = new PlainValue$5.YAMLSemanticError(this, msg);
  12688. }
  12689. this.blockIndent = lineIndent;
  12690. } else if (lineIndent > minBlockIndent) {
  12691. // empty line with more whitespace
  12692. minBlockIndent = lineIndent;
  12693. }
  12694. } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) {
  12695. if (src[end] === '#') break;
  12696. if (!this.error) {
  12697. const src = explicit ? 'explicit indentation indicator' : 'first line';
  12698. const msg = `Block scalars must not be less indented than their ${src}`;
  12699. this.error = new PlainValue$5.YAMLSemanticError(this, msg);
  12700. }
  12701. }
  12702. if (src[end] === '\n') {
  12703. offset = end;
  12704. } else {
  12705. offset = valueEnd = PlainValue$5.Node.endOfLine(src, end);
  12706. }
  12707. }
  12708. if (this.chomping !== Chomp.KEEP) {
  12709. offset = src[valueEnd] ? valueEnd + 1 : valueEnd;
  12710. }
  12711. this.valueRange = new PlainValue$5.Range(start + 1, offset);
  12712. return offset;
  12713. }
  12714. /**
  12715. * Parses a block value from the source
  12716. *
  12717. * Accepted forms are:
  12718. * ```
  12719. * BS
  12720. * block
  12721. * lines
  12722. *
  12723. * BS #comment
  12724. * block
  12725. * lines
  12726. * ```
  12727. * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines
  12728. * are empty or have an indent level greater than `indent`.
  12729. *
  12730. * @param {ParseContext} context
  12731. * @param {number} start - Index of first character
  12732. * @returns {number} - Index of the character after this block
  12733. */
  12734. parse(context, start) {
  12735. this.context = context;
  12736. const {
  12737. src
  12738. } = context;
  12739. let offset = this.parseBlockHeader(start);
  12740. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  12741. offset = this.parseComment(offset);
  12742. offset = this.parseBlockValue(offset);
  12743. return offset;
  12744. }
  12745. setOrigRanges(cr, offset) {
  12746. offset = super.setOrigRanges(cr, offset);
  12747. return this.header ? this.header.setOrigRange(cr, offset) : offset;
  12748. }
  12749. }
  12750. class FlowCollection extends PlainValue$5.Node {
  12751. constructor(type, props) {
  12752. super(type, props);
  12753. this.items = null;
  12754. }
  12755. prevNodeIsJsonLike(idx = this.items.length) {
  12756. const node = this.items[idx - 1];
  12757. return !!node && (node.jsonLike || node.type === PlainValue$5.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1));
  12758. }
  12759. /**
  12760. * @param {ParseContext} context
  12761. * @param {number} start - Index of first character
  12762. * @returns {number} - Index of the character after this
  12763. */
  12764. parse(context, start) {
  12765. this.context = context;
  12766. const {
  12767. parseNode,
  12768. src
  12769. } = context;
  12770. let {
  12771. indent,
  12772. lineStart
  12773. } = context;
  12774. let char = src[start]; // { or [
  12775. this.items = [{
  12776. char,
  12777. offset: start
  12778. }];
  12779. let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1);
  12780. char = src[offset];
  12781. while (char && char !== ']' && char !== '}') {
  12782. switch (char) {
  12783. case '\n':
  12784. {
  12785. lineStart = offset + 1;
  12786. const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
  12787. if (src[wsEnd] === '\n') {
  12788. const blankLine = new BlankLine();
  12789. lineStart = blankLine.parse({
  12790. src
  12791. }, lineStart);
  12792. this.items.push(blankLine);
  12793. }
  12794. offset = PlainValue$5.Node.endOfIndent(src, lineStart);
  12795. if (offset <= lineStart + indent) {
  12796. char = src[offset];
  12797. if (offset < lineStart + indent || char !== ']' && char !== '}') {
  12798. const msg = 'Insufficient indentation in flow collection';
  12799. this.error = new PlainValue$5.YAMLSemanticError(this, msg);
  12800. }
  12801. }
  12802. }
  12803. break;
  12804. case ',':
  12805. {
  12806. this.items.push({
  12807. char,
  12808. offset
  12809. });
  12810. offset += 1;
  12811. }
  12812. break;
  12813. case '#':
  12814. {
  12815. const comment = new Comment();
  12816. offset = comment.parse({
  12817. src
  12818. }, offset);
  12819. this.items.push(comment);
  12820. }
  12821. break;
  12822. case '?':
  12823. case ':':
  12824. {
  12825. const next = src[offset + 1];
  12826. if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace
  12827. char === ':' && this.prevNodeIsJsonLike()) {
  12828. this.items.push({
  12829. char,
  12830. offset
  12831. });
  12832. offset += 1;
  12833. break;
  12834. }
  12835. }
  12836. // fallthrough
  12837. default:
  12838. {
  12839. const node = parseNode({
  12840. atLineStart: false,
  12841. inCollection: false,
  12842. inFlow: true,
  12843. indent: -1,
  12844. lineStart,
  12845. parent: this
  12846. }, offset);
  12847. if (!node) {
  12848. // at next document start
  12849. this.valueRange = new PlainValue$5.Range(start, offset);
  12850. return offset;
  12851. }
  12852. this.items.push(node);
  12853. offset = PlainValue$5.Node.normalizeOffset(src, node.range.end);
  12854. }
  12855. }
  12856. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  12857. char = src[offset];
  12858. }
  12859. this.valueRange = new PlainValue$5.Range(start, offset + 1);
  12860. if (char) {
  12861. this.items.push({
  12862. char,
  12863. offset
  12864. });
  12865. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset + 1);
  12866. offset = this.parseComment(offset);
  12867. }
  12868. return offset;
  12869. }
  12870. setOrigRanges(cr, offset) {
  12871. offset = super.setOrigRanges(cr, offset);
  12872. this.items.forEach(node => {
  12873. if (node instanceof PlainValue$5.Node) {
  12874. offset = node.setOrigRanges(cr, offset);
  12875. } else if (cr.length === 0) {
  12876. node.origOffset = node.offset;
  12877. } else {
  12878. let i = offset;
  12879. while (i < cr.length) {
  12880. if (cr[i] > node.offset) break;else ++i;
  12881. }
  12882. node.origOffset = node.offset + i;
  12883. offset = i;
  12884. }
  12885. });
  12886. return offset;
  12887. }
  12888. toString() {
  12889. const {
  12890. context: {
  12891. src
  12892. },
  12893. items,
  12894. range,
  12895. value
  12896. } = this;
  12897. if (value != null) return value;
  12898. const nodes = items.filter(item => item instanceof PlainValue$5.Node);
  12899. let str = '';
  12900. let prevEnd = range.start;
  12901. nodes.forEach(node => {
  12902. const prefix = src.slice(prevEnd, node.range.start);
  12903. prevEnd = node.range.end;
  12904. str += prefix + String(node);
  12905. if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') {
  12906. // Comment range does not include the terminal newline, but its
  12907. // stringified value does. Without this fix, newlines at comment ends
  12908. // get duplicated.
  12909. prevEnd += 1;
  12910. }
  12911. });
  12912. str += src.slice(prevEnd, range.end);
  12913. return PlainValue$5.Node.addStringTerminator(src, range.end, str);
  12914. }
  12915. }
  12916. class QuoteDouble extends PlainValue$5.Node {
  12917. static endOfQuote(src, offset) {
  12918. let ch = src[offset];
  12919. while (ch && ch !== '"') {
  12920. offset += ch === '\\' ? 2 : 1;
  12921. ch = src[offset];
  12922. }
  12923. return offset + 1;
  12924. }
  12925. /**
  12926. * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
  12927. */
  12928. get strValue() {
  12929. if (!this.valueRange || !this.context) return null;
  12930. const errors = [];
  12931. const {
  12932. start,
  12933. end
  12934. } = this.valueRange;
  12935. const {
  12936. indent,
  12937. src
  12938. } = this.context;
  12939. if (src[end - 1] !== '"') errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by
  12940. // escaped backslashes; also, this should be faster.
  12941. let str = '';
  12942. for (let i = start + 1; i < end - 1; ++i) {
  12943. const ch = src[i];
  12944. if (ch === '\n') {
  12945. if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
  12946. const {
  12947. fold,
  12948. offset,
  12949. error
  12950. } = PlainValue$5.Node.foldNewline(src, i, indent);
  12951. str += fold;
  12952. i = offset;
  12953. if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented'));
  12954. } else if (ch === '\\') {
  12955. i += 1;
  12956. switch (src[i]) {
  12957. case '0':
  12958. str += '\0';
  12959. break;
  12960. // null character
  12961. case 'a':
  12962. str += '\x07';
  12963. break;
  12964. // bell character
  12965. case 'b':
  12966. str += '\b';
  12967. break;
  12968. // backspace
  12969. case 'e':
  12970. str += '\x1b';
  12971. break;
  12972. // escape character
  12973. case 'f':
  12974. str += '\f';
  12975. break;
  12976. // form feed
  12977. case 'n':
  12978. str += '\n';
  12979. break;
  12980. // line feed
  12981. case 'r':
  12982. str += '\r';
  12983. break;
  12984. // carriage return
  12985. case 't':
  12986. str += '\t';
  12987. break;
  12988. // horizontal tab
  12989. case 'v':
  12990. str += '\v';
  12991. break;
  12992. // vertical tab
  12993. case 'N':
  12994. str += '\u0085';
  12995. break;
  12996. // Unicode next line
  12997. case '_':
  12998. str += '\u00a0';
  12999. break;
  13000. // Unicode non-breaking space
  13001. case 'L':
  13002. str += '\u2028';
  13003. break;
  13004. // Unicode line separator
  13005. case 'P':
  13006. str += '\u2029';
  13007. break;
  13008. // Unicode paragraph separator
  13009. case ' ':
  13010. str += ' ';
  13011. break;
  13012. case '"':
  13013. str += '"';
  13014. break;
  13015. case '/':
  13016. str += '/';
  13017. break;
  13018. case '\\':
  13019. str += '\\';
  13020. break;
  13021. case '\t':
  13022. str += '\t';
  13023. break;
  13024. case 'x':
  13025. str += this.parseCharCode(i + 1, 2, errors);
  13026. i += 2;
  13027. break;
  13028. case 'u':
  13029. str += this.parseCharCode(i + 1, 4, errors);
  13030. i += 4;
  13031. break;
  13032. case 'U':
  13033. str += this.parseCharCode(i + 1, 8, errors);
  13034. i += 8;
  13035. break;
  13036. case '\n':
  13037. // skip escaped newlines, but still trim the following line
  13038. while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1;
  13039. break;
  13040. default:
  13041. errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`));
  13042. str += '\\' + src[i];
  13043. }
  13044. } else if (ch === ' ' || ch === '\t') {
  13045. // trim trailing whitespace
  13046. const wsStart = i;
  13047. let next = src[i + 1];
  13048. while (next === ' ' || next === '\t') {
  13049. i += 1;
  13050. next = src[i + 1];
  13051. }
  13052. if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
  13053. } else {
  13054. str += ch;
  13055. }
  13056. }
  13057. return errors.length > 0 ? {
  13058. errors,
  13059. str
  13060. } : str;
  13061. }
  13062. parseCharCode(offset, length, errors) {
  13063. const {
  13064. src
  13065. } = this.context;
  13066. const cc = src.substr(offset, length);
  13067. const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
  13068. const code = ok ? parseInt(cc, 16) : NaN;
  13069. if (isNaN(code)) {
  13070. errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`));
  13071. return src.substr(offset - 2, length + 2);
  13072. }
  13073. return String.fromCodePoint(code);
  13074. }
  13075. /**
  13076. * Parses a "double quoted" value from the source
  13077. *
  13078. * @param {ParseContext} context
  13079. * @param {number} start - Index of first character
  13080. * @returns {number} - Index of the character after this scalar
  13081. */
  13082. parse(context, start) {
  13083. this.context = context;
  13084. const {
  13085. src
  13086. } = context;
  13087. let offset = QuoteDouble.endOfQuote(src, start + 1);
  13088. this.valueRange = new PlainValue$5.Range(start, offset);
  13089. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  13090. offset = this.parseComment(offset);
  13091. return offset;
  13092. }
  13093. }
  13094. class QuoteSingle extends PlainValue$5.Node {
  13095. static endOfQuote(src, offset) {
  13096. let ch = src[offset];
  13097. while (ch) {
  13098. if (ch === "'") {
  13099. if (src[offset + 1] !== "'") break;
  13100. ch = src[offset += 2];
  13101. } else {
  13102. ch = src[offset += 1];
  13103. }
  13104. }
  13105. return offset + 1;
  13106. }
  13107. /**
  13108. * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
  13109. */
  13110. get strValue() {
  13111. if (!this.valueRange || !this.context) return null;
  13112. const errors = [];
  13113. const {
  13114. start,
  13115. end
  13116. } = this.valueRange;
  13117. const {
  13118. indent,
  13119. src
  13120. } = this.context;
  13121. if (src[end - 1] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, "Missing closing 'quote"));
  13122. let str = '';
  13123. for (let i = start + 1; i < end - 1; ++i) {
  13124. const ch = src[i];
  13125. if (ch === '\n') {
  13126. if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
  13127. const {
  13128. fold,
  13129. offset,
  13130. error
  13131. } = PlainValue$5.Node.foldNewline(src, i, indent);
  13132. str += fold;
  13133. i = offset;
  13134. if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented'));
  13135. } else if (ch === "'") {
  13136. str += ch;
  13137. i += 1;
  13138. if (src[i] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.'));
  13139. } else if (ch === ' ' || ch === '\t') {
  13140. // trim trailing whitespace
  13141. const wsStart = i;
  13142. let next = src[i + 1];
  13143. while (next === ' ' || next === '\t') {
  13144. i += 1;
  13145. next = src[i + 1];
  13146. }
  13147. if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
  13148. } else {
  13149. str += ch;
  13150. }
  13151. }
  13152. return errors.length > 0 ? {
  13153. errors,
  13154. str
  13155. } : str;
  13156. }
  13157. /**
  13158. * Parses a 'single quoted' value from the source
  13159. *
  13160. * @param {ParseContext} context
  13161. * @param {number} start - Index of first character
  13162. * @returns {number} - Index of the character after this scalar
  13163. */
  13164. parse(context, start) {
  13165. this.context = context;
  13166. const {
  13167. src
  13168. } = context;
  13169. let offset = QuoteSingle.endOfQuote(src, start + 1);
  13170. this.valueRange = new PlainValue$5.Range(start, offset);
  13171. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  13172. offset = this.parseComment(offset);
  13173. return offset;
  13174. }
  13175. }
  13176. function createNewNode(type, props) {
  13177. switch (type) {
  13178. case PlainValue$5.Type.ALIAS:
  13179. return new Alias$1(type, props);
  13180. case PlainValue$5.Type.BLOCK_FOLDED:
  13181. case PlainValue$5.Type.BLOCK_LITERAL:
  13182. return new BlockValue(type, props);
  13183. case PlainValue$5.Type.FLOW_MAP:
  13184. case PlainValue$5.Type.FLOW_SEQ:
  13185. return new FlowCollection(type, props);
  13186. case PlainValue$5.Type.MAP_KEY:
  13187. case PlainValue$5.Type.MAP_VALUE:
  13188. case PlainValue$5.Type.SEQ_ITEM:
  13189. return new CollectionItem(type, props);
  13190. case PlainValue$5.Type.COMMENT:
  13191. case PlainValue$5.Type.PLAIN:
  13192. return new PlainValue$5.PlainValue(type, props);
  13193. case PlainValue$5.Type.QUOTE_DOUBLE:
  13194. return new QuoteDouble(type, props);
  13195. case PlainValue$5.Type.QUOTE_SINGLE:
  13196. return new QuoteSingle(type, props);
  13197. /* istanbul ignore next */
  13198. default:
  13199. return null;
  13200. // should never happen
  13201. }
  13202. }
  13203. /**
  13204. * @param {boolean} atLineStart - Node starts at beginning of line
  13205. * @param {boolean} inFlow - true if currently in a flow context
  13206. * @param {boolean} inCollection - true if currently in a collection context
  13207. * @param {number} indent - Current level of indentation
  13208. * @param {number} lineStart - Start of the current line
  13209. * @param {Node} parent - The parent of the node
  13210. * @param {string} src - Source of the YAML document
  13211. */
  13212. class ParseContext {
  13213. static parseType(src, offset, inFlow) {
  13214. switch (src[offset]) {
  13215. case '*':
  13216. return PlainValue$5.Type.ALIAS;
  13217. case '>':
  13218. return PlainValue$5.Type.BLOCK_FOLDED;
  13219. case '|':
  13220. return PlainValue$5.Type.BLOCK_LITERAL;
  13221. case '{':
  13222. return PlainValue$5.Type.FLOW_MAP;
  13223. case '[':
  13224. return PlainValue$5.Type.FLOW_SEQ;
  13225. case '?':
  13226. return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_KEY : PlainValue$5.Type.PLAIN;
  13227. case ':':
  13228. return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_VALUE : PlainValue$5.Type.PLAIN;
  13229. case '-':
  13230. return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.SEQ_ITEM : PlainValue$5.Type.PLAIN;
  13231. case '"':
  13232. return PlainValue$5.Type.QUOTE_DOUBLE;
  13233. case "'":
  13234. return PlainValue$5.Type.QUOTE_SINGLE;
  13235. default:
  13236. return PlainValue$5.Type.PLAIN;
  13237. }
  13238. }
  13239. constructor(orig = {}, {
  13240. atLineStart,
  13241. inCollection,
  13242. inFlow,
  13243. indent,
  13244. lineStart,
  13245. parent
  13246. } = {}) {
  13247. PlainValue$5._defineProperty(this, "parseNode", (overlay, start) => {
  13248. if (PlainValue$5.Node.atDocumentBoundary(this.src, start)) return null;
  13249. const context = new ParseContext(this, overlay);
  13250. const {
  13251. props,
  13252. type,
  13253. valueStart
  13254. } = context.parseProps(start);
  13255. const node = createNewNode(type, props);
  13256. let offset = node.parse(context, valueStart);
  13257. node.range = new PlainValue$5.Range(start, offset);
  13258. /* istanbul ignore if */
  13259. if (offset <= start) {
  13260. // This should never happen, but if it does, let's make sure to at least
  13261. // step one character forward to avoid a busy loop.
  13262. node.error = new Error(`Node#parse consumed no characters`);
  13263. node.error.parseEnd = offset;
  13264. node.error.source = node;
  13265. node.range.end = start + 1;
  13266. }
  13267. if (context.nodeStartsCollection(node)) {
  13268. if (!node.error && !context.atLineStart && context.parent.type === PlainValue$5.Type.DOCUMENT) {
  13269. node.error = new PlainValue$5.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)');
  13270. }
  13271. const collection = new Collection$1(node);
  13272. offset = collection.parse(new ParseContext(context), offset);
  13273. collection.range = new PlainValue$5.Range(start, offset);
  13274. return collection;
  13275. }
  13276. return node;
  13277. });
  13278. this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false;
  13279. this.inCollection = inCollection != null ? inCollection : orig.inCollection || false;
  13280. this.inFlow = inFlow != null ? inFlow : orig.inFlow || false;
  13281. this.indent = indent != null ? indent : orig.indent;
  13282. this.lineStart = lineStart != null ? lineStart : orig.lineStart;
  13283. this.parent = parent != null ? parent : orig.parent || {};
  13284. this.root = orig.root;
  13285. this.src = orig.src;
  13286. }
  13287. nodeStartsCollection(node) {
  13288. const {
  13289. inCollection,
  13290. inFlow,
  13291. src
  13292. } = this;
  13293. if (inCollection || inFlow) return false;
  13294. if (node instanceof CollectionItem) return true; // check for implicit key
  13295. let offset = node.range.end;
  13296. if (src[offset] === '\n' || src[offset - 1] === '\n') return false;
  13297. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  13298. return src[offset] === ':';
  13299. } // Anchor and tag are before type, which determines the node implementation
  13300. // class; hence this intermediate step.
  13301. parseProps(offset) {
  13302. const {
  13303. inFlow,
  13304. parent,
  13305. src
  13306. } = this;
  13307. const props = [];
  13308. let lineHasProps = false;
  13309. offset = this.atLineStart ? PlainValue$5.Node.endOfIndent(src, offset) : PlainValue$5.Node.endOfWhiteSpace(src, offset);
  13310. let ch = src[offset];
  13311. while (ch === PlainValue$5.Char.ANCHOR || ch === PlainValue$5.Char.COMMENT || ch === PlainValue$5.Char.TAG || ch === '\n') {
  13312. if (ch === '\n') {
  13313. let inEnd = offset;
  13314. let lineStart;
  13315. do {
  13316. lineStart = inEnd + 1;
  13317. inEnd = PlainValue$5.Node.endOfIndent(src, lineStart);
  13318. } while (src[inEnd] === '\n');
  13319. const indentDiff = inEnd - (lineStart + this.indent);
  13320. const noIndicatorAsIndent = parent.type === PlainValue$5.Type.SEQ_ITEM && parent.context.atLineStart;
  13321. if (src[inEnd] !== '#' && !PlainValue$5.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break;
  13322. this.atLineStart = true;
  13323. this.lineStart = lineStart;
  13324. lineHasProps = false;
  13325. offset = inEnd;
  13326. } else if (ch === PlainValue$5.Char.COMMENT) {
  13327. const end = PlainValue$5.Node.endOfLine(src, offset + 1);
  13328. props.push(new PlainValue$5.Range(offset, end));
  13329. offset = end;
  13330. } else {
  13331. let end = PlainValue$5.Node.endOfIdentifier(src, offset + 1);
  13332. if (ch === PlainValue$5.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) {
  13333. // Let's presume we're dealing with a YAML 1.0 domain tag here, rather
  13334. // than an empty but 'foo.bar' private-tagged node in a flow collection
  13335. // followed without whitespace by a plain string starting with a year
  13336. // or date divided by something.
  13337. end = PlainValue$5.Node.endOfIdentifier(src, end + 5);
  13338. }
  13339. props.push(new PlainValue$5.Range(offset, end));
  13340. lineHasProps = true;
  13341. offset = PlainValue$5.Node.endOfWhiteSpace(src, end);
  13342. }
  13343. ch = src[offset];
  13344. } // '- &a : b' has an anchor on an empty node
  13345. if (lineHasProps && ch === ':' && PlainValue$5.Node.atBlank(src, offset + 1, true)) offset -= 1;
  13346. const type = ParseContext.parseType(src, offset, inFlow);
  13347. return {
  13348. props,
  13349. type,
  13350. valueStart: offset
  13351. };
  13352. }
  13353. /**
  13354. * Parses a node from the source
  13355. * @param {ParseContext} overlay
  13356. * @param {number} start - Index of first non-whitespace character for the node
  13357. * @returns {?Node} - null if at a document boundary
  13358. */
  13359. }
  13360. // Published as 'yaml/parse-cst'
  13361. function parse$g(src) {
  13362. const cr = [];
  13363. if (src.indexOf('\r') !== -1) {
  13364. src = src.replace(/\r\n?/g, (match, offset) => {
  13365. if (match.length > 1) cr.push(offset);
  13366. return '\n';
  13367. });
  13368. }
  13369. const documents = [];
  13370. let offset = 0;
  13371. do {
  13372. const doc = new Document$3();
  13373. const context = new ParseContext({
  13374. src
  13375. });
  13376. offset = doc.parse(context, offset);
  13377. documents.push(doc);
  13378. } while (offset < src.length);
  13379. documents.setOrigRanges = () => {
  13380. if (cr.length === 0) return false;
  13381. for (let i = 1; i < cr.length; ++i) cr[i] -= i;
  13382. let crOffset = 0;
  13383. for (let i = 0; i < documents.length; ++i) {
  13384. crOffset = documents[i].setOrigRanges(cr, crOffset);
  13385. }
  13386. cr.splice(0, cr.length);
  13387. return true;
  13388. };
  13389. documents.toString = () => documents.join('...\n');
  13390. return documents;
  13391. }
  13392. parseCst$1.parse = parse$g;
  13393. var Document9b4560a1 = {};
  13394. var resolveSeqD03cb037 = {};
  13395. var PlainValue$4 = PlainValueEc8e588e;
  13396. function addCommentBefore(str, indent, comment) {
  13397. if (!comment) return str;
  13398. const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`);
  13399. return `#${cc}\n${indent}${str}`;
  13400. }
  13401. function addComment(str, indent, comment) {
  13402. return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`);
  13403. }
  13404. class Node$1 {}
  13405. function toJSON(value, arg, ctx) {
  13406. if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx));
  13407. if (value && typeof value.toJSON === 'function') {
  13408. const anchor = ctx && ctx.anchors && ctx.anchors.get(value);
  13409. if (anchor) ctx.onCreate = res => {
  13410. anchor.res = res;
  13411. delete ctx.onCreate;
  13412. };
  13413. const res = value.toJSON(arg, ctx);
  13414. if (anchor && ctx.onCreate) ctx.onCreate(res);
  13415. return res;
  13416. }
  13417. if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value);
  13418. return value;
  13419. }
  13420. class Scalar extends Node$1 {
  13421. constructor(value) {
  13422. super();
  13423. this.value = value;
  13424. }
  13425. toJSON(arg, ctx) {
  13426. return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx);
  13427. }
  13428. toString() {
  13429. return String(this.value);
  13430. }
  13431. }
  13432. function collectionFromPath(schema, path, value) {
  13433. let v = value;
  13434. for (let i = path.length - 1; i >= 0; --i) {
  13435. const k = path[i];
  13436. if (Number.isInteger(k) && k >= 0) {
  13437. const a = [];
  13438. a[k] = v;
  13439. v = a;
  13440. } else {
  13441. const o = {};
  13442. Object.defineProperty(o, k, {
  13443. value: v,
  13444. writable: true,
  13445. enumerable: true,
  13446. configurable: true
  13447. });
  13448. v = o;
  13449. }
  13450. }
  13451. return schema.createNode(v, false);
  13452. } // null, undefined, or an empty non-string iterable (e.g. [])
  13453. const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done;
  13454. class Collection extends Node$1 {
  13455. constructor(schema) {
  13456. super();
  13457. PlainValue$4._defineProperty(this, "items", []);
  13458. this.schema = schema;
  13459. }
  13460. addIn(path, value) {
  13461. if (isEmptyPath(path)) this.add(value);else {
  13462. const [key, ...rest] = path;
  13463. const node = this.get(key, true);
  13464. if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  13465. }
  13466. }
  13467. deleteIn([key, ...rest]) {
  13468. if (rest.length === 0) return this.delete(key);
  13469. const node = this.get(key, true);
  13470. if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  13471. }
  13472. getIn([key, ...rest], keepScalar) {
  13473. const node = this.get(key, true);
  13474. if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined;
  13475. }
  13476. hasAllNullValues() {
  13477. return this.items.every(node => {
  13478. if (!node || node.type !== 'PAIR') return false;
  13479. const n = node.value;
  13480. return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag;
  13481. });
  13482. }
  13483. hasIn([key, ...rest]) {
  13484. if (rest.length === 0) return this.has(key);
  13485. const node = this.get(key, true);
  13486. return node instanceof Collection ? node.hasIn(rest) : false;
  13487. }
  13488. setIn([key, ...rest], value) {
  13489. if (rest.length === 0) {
  13490. this.set(key, value);
  13491. } else {
  13492. const node = this.get(key, true);
  13493. if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  13494. }
  13495. } // overridden in implementations
  13496. /* istanbul ignore next */
  13497. toJSON() {
  13498. return null;
  13499. }
  13500. toString(ctx, {
  13501. blockItem,
  13502. flowChars,
  13503. isMap,
  13504. itemIndent
  13505. }, onComment, onChompKeep) {
  13506. const {
  13507. indent,
  13508. indentStep,
  13509. stringify
  13510. } = ctx;
  13511. const inFlow = this.type === PlainValue$4.Type.FLOW_MAP || this.type === PlainValue$4.Type.FLOW_SEQ || ctx.inFlow;
  13512. if (inFlow) itemIndent += indentStep;
  13513. const allNullValues = isMap && this.hasAllNullValues();
  13514. ctx = Object.assign({}, ctx, {
  13515. allNullValues,
  13516. indent: itemIndent,
  13517. inFlow,
  13518. type: null
  13519. });
  13520. let chompKeep = false;
  13521. let hasItemWithNewLine = false;
  13522. const nodes = this.items.reduce((nodes, item, i) => {
  13523. let comment;
  13524. if (item) {
  13525. if (!chompKeep && item.spaceBefore) nodes.push({
  13526. type: 'comment',
  13527. str: ''
  13528. });
  13529. if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => {
  13530. nodes.push({
  13531. type: 'comment',
  13532. str: `#${line}`
  13533. });
  13534. });
  13535. if (item.comment) comment = item.comment;
  13536. if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true;
  13537. }
  13538. chompKeep = false;
  13539. let str = stringify(item, ctx, () => comment = null, () => chompKeep = true);
  13540. if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true;
  13541. if (inFlow && i < this.items.length - 1) str += ',';
  13542. str = addComment(str, itemIndent, comment);
  13543. if (chompKeep && (comment || inFlow)) chompKeep = false;
  13544. nodes.push({
  13545. type: 'item',
  13546. str
  13547. });
  13548. return nodes;
  13549. }, []);
  13550. let str;
  13551. if (nodes.length === 0) {
  13552. str = flowChars.start + flowChars.end;
  13553. } else if (inFlow) {
  13554. const {
  13555. start,
  13556. end
  13557. } = flowChars;
  13558. const strings = nodes.map(n => n.str);
  13559. if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) {
  13560. str = start;
  13561. for (const s of strings) {
  13562. str += s ? `\n${indentStep}${indent}${s}` : '\n';
  13563. }
  13564. str += `\n${indent}${end}`;
  13565. } else {
  13566. str = `${start} ${strings.join(' ')} ${end}`;
  13567. }
  13568. } else {
  13569. const strings = nodes.map(blockItem);
  13570. str = strings.shift();
  13571. for (const s of strings) str += s ? `\n${indent}${s}` : '\n';
  13572. }
  13573. if (this.comment) {
  13574. str += '\n' + this.comment.replace(/^/gm, `${indent}#`);
  13575. if (onComment) onComment();
  13576. } else if (chompKeep && onChompKeep) onChompKeep();
  13577. return str;
  13578. }
  13579. }
  13580. PlainValue$4._defineProperty(Collection, "maxFlowStringSingleLineLength", 60);
  13581. function asItemIndex(key) {
  13582. let idx = key instanceof Scalar ? key.value : key;
  13583. if (idx && typeof idx === 'string') idx = Number(idx);
  13584. return Number.isInteger(idx) && idx >= 0 ? idx : null;
  13585. }
  13586. class YAMLSeq extends Collection {
  13587. add(value) {
  13588. this.items.push(value);
  13589. }
  13590. delete(key) {
  13591. const idx = asItemIndex(key);
  13592. if (typeof idx !== 'number') return false;
  13593. const del = this.items.splice(idx, 1);
  13594. return del.length > 0;
  13595. }
  13596. get(key, keepScalar) {
  13597. const idx = asItemIndex(key);
  13598. if (typeof idx !== 'number') return undefined;
  13599. const it = this.items[idx];
  13600. return !keepScalar && it instanceof Scalar ? it.value : it;
  13601. }
  13602. has(key) {
  13603. const idx = asItemIndex(key);
  13604. return typeof idx === 'number' && idx < this.items.length;
  13605. }
  13606. set(key, value) {
  13607. const idx = asItemIndex(key);
  13608. if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`);
  13609. this.items[idx] = value;
  13610. }
  13611. toJSON(_, ctx) {
  13612. const seq = [];
  13613. if (ctx && ctx.onCreate) ctx.onCreate(seq);
  13614. let i = 0;
  13615. for (const item of this.items) seq.push(toJSON(item, String(i++), ctx));
  13616. return seq;
  13617. }
  13618. toString(ctx, onComment, onChompKeep) {
  13619. if (!ctx) return JSON.stringify(this);
  13620. return super.toString(ctx, {
  13621. blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`,
  13622. flowChars: {
  13623. start: '[',
  13624. end: ']'
  13625. },
  13626. isMap: false,
  13627. itemIndent: (ctx.indent || '') + ' '
  13628. }, onComment, onChompKeep);
  13629. }
  13630. }
  13631. const stringifyKey = (key, jsKey, ctx) => {
  13632. if (jsKey === null) return '';
  13633. if (typeof jsKey !== 'object') return String(jsKey);
  13634. if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({
  13635. anchors: Object.create(null),
  13636. doc: ctx.doc,
  13637. indent: '',
  13638. indentStep: ctx.indentStep,
  13639. inFlow: true,
  13640. inStringifyKey: true,
  13641. stringify: ctx.stringify
  13642. });
  13643. return JSON.stringify(jsKey);
  13644. };
  13645. class Pair extends Node$1 {
  13646. constructor(key, value = null) {
  13647. super();
  13648. this.key = key;
  13649. this.value = value;
  13650. this.type = Pair.Type.PAIR;
  13651. }
  13652. get commentBefore() {
  13653. return this.key instanceof Node$1 ? this.key.commentBefore : undefined;
  13654. }
  13655. set commentBefore(cb) {
  13656. if (this.key == null) this.key = new Scalar(null);
  13657. if (this.key instanceof Node$1) this.key.commentBefore = cb;else {
  13658. const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.';
  13659. throw new Error(msg);
  13660. }
  13661. }
  13662. addToJSMap(ctx, map) {
  13663. const key = toJSON(this.key, '', ctx);
  13664. if (map instanceof Map) {
  13665. const value = toJSON(this.value, key, ctx);
  13666. map.set(key, value);
  13667. } else if (map instanceof Set) {
  13668. map.add(key);
  13669. } else {
  13670. const stringKey = stringifyKey(this.key, key, ctx);
  13671. const value = toJSON(this.value, stringKey, ctx);
  13672. if (stringKey in map) Object.defineProperty(map, stringKey, {
  13673. value,
  13674. writable: true,
  13675. enumerable: true,
  13676. configurable: true
  13677. });else map[stringKey] = value;
  13678. }
  13679. return map;
  13680. }
  13681. toJSON(_, ctx) {
  13682. const pair = ctx && ctx.mapAsMap ? new Map() : {};
  13683. return this.addToJSMap(ctx, pair);
  13684. }
  13685. toString(ctx, onComment, onChompKeep) {
  13686. if (!ctx || !ctx.doc) return JSON.stringify(this);
  13687. const {
  13688. indent: indentSize,
  13689. indentSeq,
  13690. simpleKeys
  13691. } = ctx.doc.options;
  13692. let {
  13693. key,
  13694. value
  13695. } = this;
  13696. let keyComment = key instanceof Node$1 && key.comment;
  13697. if (simpleKeys) {
  13698. if (keyComment) {
  13699. throw new Error('With simple keys, key nodes cannot have comments');
  13700. }
  13701. if (key instanceof Collection) {
  13702. const msg = 'With simple keys, collection cannot be used as a key value';
  13703. throw new Error(msg);
  13704. }
  13705. }
  13706. let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node$1 ? key instanceof Collection || key.type === PlainValue$4.Type.BLOCK_FOLDED || key.type === PlainValue$4.Type.BLOCK_LITERAL : typeof key === 'object'));
  13707. const {
  13708. doc,
  13709. indent,
  13710. indentStep,
  13711. stringify
  13712. } = ctx;
  13713. ctx = Object.assign({}, ctx, {
  13714. implicitKey: !explicitKey,
  13715. indent: indent + indentStep
  13716. });
  13717. let chompKeep = false;
  13718. let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true);
  13719. str = addComment(str, ctx.indent, keyComment);
  13720. if (!explicitKey && str.length > 1024) {
  13721. if (simpleKeys) throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
  13722. explicitKey = true;
  13723. }
  13724. if (ctx.allNullValues && !simpleKeys) {
  13725. if (this.comment) {
  13726. str = addComment(str, ctx.indent, this.comment);
  13727. if (onComment) onComment();
  13728. } else if (chompKeep && !keyComment && onChompKeep) onChompKeep();
  13729. return ctx.inFlow && !explicitKey ? str : `? ${str}`;
  13730. }
  13731. str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`;
  13732. if (this.comment) {
  13733. // expected (but not strictly required) to be a single-line comment
  13734. str = addComment(str, ctx.indent, this.comment);
  13735. if (onComment) onComment();
  13736. }
  13737. let vcb = '';
  13738. let valueComment = null;
  13739. if (value instanceof Node$1) {
  13740. if (value.spaceBefore) vcb = '\n';
  13741. if (value.commentBefore) {
  13742. const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`);
  13743. vcb += `\n${cs}`;
  13744. }
  13745. valueComment = value.comment;
  13746. } else if (value && typeof value === 'object') {
  13747. value = doc.schema.createNode(value, true);
  13748. }
  13749. ctx.implicitKey = false;
  13750. if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1;
  13751. chompKeep = false;
  13752. if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue$4.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) {
  13753. // If indentSeq === false, consider '- ' as part of indentation where possible
  13754. ctx.indent = ctx.indent.substr(2);
  13755. }
  13756. const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true);
  13757. let ws = ' ';
  13758. if (vcb || this.comment) {
  13759. ws = `${vcb}\n${ctx.indent}`;
  13760. } else if (!explicitKey && value instanceof Collection) {
  13761. const flow = valueStr[0] === '[' || valueStr[0] === '{';
  13762. if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`;
  13763. } else if (valueStr[0] === '\n') ws = '';
  13764. if (chompKeep && !valueComment && onChompKeep) onChompKeep();
  13765. return addComment(str + ws + valueStr, ctx.indent, valueComment);
  13766. }
  13767. }
  13768. PlainValue$4._defineProperty(Pair, "Type", {
  13769. PAIR: 'PAIR',
  13770. MERGE_PAIR: 'MERGE_PAIR'
  13771. });
  13772. const getAliasCount = (node, anchors) => {
  13773. if (node instanceof Alias) {
  13774. const anchor = anchors.get(node.source);
  13775. return anchor.count * anchor.aliasCount;
  13776. } else if (node instanceof Collection) {
  13777. let count = 0;
  13778. for (const item of node.items) {
  13779. const c = getAliasCount(item, anchors);
  13780. if (c > count) count = c;
  13781. }
  13782. return count;
  13783. } else if (node instanceof Pair) {
  13784. const kc = getAliasCount(node.key, anchors);
  13785. const vc = getAliasCount(node.value, anchors);
  13786. return Math.max(kc, vc);
  13787. }
  13788. return 1;
  13789. };
  13790. class Alias extends Node$1 {
  13791. static stringify({
  13792. range,
  13793. source
  13794. }, {
  13795. anchors,
  13796. doc,
  13797. implicitKey,
  13798. inStringifyKey
  13799. }) {
  13800. let anchor = Object.keys(anchors).find(a => anchors[a] === source);
  13801. if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName();
  13802. if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`;
  13803. const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node';
  13804. throw new Error(`${msg} [${range}]`);
  13805. }
  13806. constructor(source) {
  13807. super();
  13808. this.source = source;
  13809. this.type = PlainValue$4.Type.ALIAS;
  13810. }
  13811. set tag(t) {
  13812. throw new Error('Alias nodes cannot have tags');
  13813. }
  13814. toJSON(arg, ctx) {
  13815. if (!ctx) return toJSON(this.source, arg, ctx);
  13816. const {
  13817. anchors,
  13818. maxAliasCount
  13819. } = ctx;
  13820. const anchor = anchors.get(this.source);
  13821. /* istanbul ignore if */
  13822. if (!anchor || anchor.res === undefined) {
  13823. const msg = 'This should not happen: Alias anchor was not resolved?';
  13824. if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
  13825. }
  13826. if (maxAliasCount >= 0) {
  13827. anchor.count += 1;
  13828. if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors);
  13829. if (anchor.count * anchor.aliasCount > maxAliasCount) {
  13830. const msg = 'Excessive alias count indicates a resource exhaustion attack';
  13831. if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
  13832. }
  13833. }
  13834. return anchor.res;
  13835. } // Only called when stringifying an alias mapping key while constructing
  13836. // Object output.
  13837. toString(ctx) {
  13838. return Alias.stringify(this, ctx);
  13839. }
  13840. }
  13841. PlainValue$4._defineProperty(Alias, "default", true);
  13842. function findPair(items, key) {
  13843. const k = key instanceof Scalar ? key.value : key;
  13844. for (const it of items) {
  13845. if (it instanceof Pair) {
  13846. if (it.key === key || it.key === k) return it;
  13847. if (it.key && it.key.value === k) return it;
  13848. }
  13849. }
  13850. return undefined;
  13851. }
  13852. class YAMLMap extends Collection {
  13853. add(pair, overwrite) {
  13854. if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value);
  13855. const prev = findPair(this.items, pair.key);
  13856. const sortEntries = this.schema && this.schema.sortMapEntries;
  13857. if (prev) {
  13858. if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`);
  13859. } else if (sortEntries) {
  13860. const i = this.items.findIndex(item => sortEntries(pair, item) < 0);
  13861. if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair);
  13862. } else {
  13863. this.items.push(pair);
  13864. }
  13865. }
  13866. delete(key) {
  13867. const it = findPair(this.items, key);
  13868. if (!it) return false;
  13869. const del = this.items.splice(this.items.indexOf(it), 1);
  13870. return del.length > 0;
  13871. }
  13872. get(key, keepScalar) {
  13873. const it = findPair(this.items, key);
  13874. const node = it && it.value;
  13875. return !keepScalar && node instanceof Scalar ? node.value : node;
  13876. }
  13877. has(key) {
  13878. return !!findPair(this.items, key);
  13879. }
  13880. set(key, value) {
  13881. this.add(new Pair(key, value), true);
  13882. }
  13883. /**
  13884. * @param {*} arg ignored
  13885. * @param {*} ctx Conversion context, originally set in Document#toJSON()
  13886. * @param {Class} Type If set, forces the returned collection type
  13887. * @returns {*} Instance of Type, Map, or Object
  13888. */
  13889. toJSON(_, ctx, Type) {
  13890. const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {};
  13891. if (ctx && ctx.onCreate) ctx.onCreate(map);
  13892. for (const item of this.items) item.addToJSMap(ctx, map);
  13893. return map;
  13894. }
  13895. toString(ctx, onComment, onChompKeep) {
  13896. if (!ctx) return JSON.stringify(this);
  13897. for (const item of this.items) {
  13898. if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
  13899. }
  13900. return super.toString(ctx, {
  13901. blockItem: n => n.str,
  13902. flowChars: {
  13903. start: '{',
  13904. end: '}'
  13905. },
  13906. isMap: true,
  13907. itemIndent: ctx.indent || ''
  13908. }, onComment, onChompKeep);
  13909. }
  13910. }
  13911. const MERGE_KEY = '<<';
  13912. class Merge extends Pair {
  13913. constructor(pair) {
  13914. if (pair instanceof Pair) {
  13915. let seq = pair.value;
  13916. if (!(seq instanceof YAMLSeq)) {
  13917. seq = new YAMLSeq();
  13918. seq.items.push(pair.value);
  13919. seq.range = pair.value.range;
  13920. }
  13921. super(pair.key, seq);
  13922. this.range = pair.range;
  13923. } else {
  13924. super(new Scalar(MERGE_KEY), new YAMLSeq());
  13925. }
  13926. this.type = Pair.Type.MERGE_PAIR;
  13927. } // If the value associated with a merge key is a single mapping node, each of
  13928. // its key/value pairs is inserted into the current mapping, unless the key
  13929. // already exists in it. If the value associated with the merge key is a
  13930. // sequence, then this sequence is expected to contain mapping nodes and each
  13931. // of these nodes is merged in turn according to its order in the sequence.
  13932. // Keys in mapping nodes earlier in the sequence override keys specified in
  13933. // later mapping nodes. -- http://yaml.org/type/merge.html
  13934. addToJSMap(ctx, map) {
  13935. for (const {
  13936. source
  13937. } of this.value.items) {
  13938. if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps');
  13939. const srcMap = source.toJSON(null, ctx, Map);
  13940. for (const [key, value] of srcMap) {
  13941. if (map instanceof Map) {
  13942. if (!map.has(key)) map.set(key, value);
  13943. } else if (map instanceof Set) {
  13944. map.add(key);
  13945. } else if (!Object.prototype.hasOwnProperty.call(map, key)) {
  13946. Object.defineProperty(map, key, {
  13947. value,
  13948. writable: true,
  13949. enumerable: true,
  13950. configurable: true
  13951. });
  13952. }
  13953. }
  13954. }
  13955. return map;
  13956. }
  13957. toString(ctx, onComment) {
  13958. const seq = this.value;
  13959. if (seq.items.length > 1) return super.toString(ctx, onComment);
  13960. this.value = seq.items[0];
  13961. const str = super.toString(ctx, onComment);
  13962. this.value = seq;
  13963. return str;
  13964. }
  13965. }
  13966. const binaryOptions = {
  13967. defaultType: PlainValue$4.Type.BLOCK_LITERAL,
  13968. lineWidth: 76
  13969. };
  13970. const boolOptions = {
  13971. trueStr: 'true',
  13972. falseStr: 'false'
  13973. };
  13974. const intOptions = {
  13975. asBigInt: false
  13976. };
  13977. const nullOptions = {
  13978. nullStr: 'null'
  13979. };
  13980. const strOptions = {
  13981. defaultType: PlainValue$4.Type.PLAIN,
  13982. doubleQuoted: {
  13983. jsonEncoding: false,
  13984. minMultiLineLength: 40
  13985. },
  13986. fold: {
  13987. lineWidth: 80,
  13988. minContentWidth: 20
  13989. }
  13990. };
  13991. function resolveScalar(str, tags, scalarFallback) {
  13992. for (const {
  13993. format,
  13994. test,
  13995. resolve
  13996. } of tags) {
  13997. if (test) {
  13998. const match = str.match(test);
  13999. if (match) {
  14000. let res = resolve.apply(null, match);
  14001. if (!(res instanceof Scalar)) res = new Scalar(res);
  14002. if (format) res.format = format;
  14003. return res;
  14004. }
  14005. }
  14006. }
  14007. if (scalarFallback) str = scalarFallback(str);
  14008. return new Scalar(str);
  14009. }
  14010. const FOLD_FLOW = 'flow';
  14011. const FOLD_BLOCK = 'block';
  14012. const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line
  14013. // returns index of last newline in more-indented block
  14014. const consumeMoreIndentedLines = (text, i) => {
  14015. let ch = text[i + 1];
  14016. while (ch === ' ' || ch === '\t') {
  14017. do {
  14018. ch = text[i += 1];
  14019. } while (ch && ch !== '\n');
  14020. ch = text[i + 1];
  14021. }
  14022. return i;
  14023. };
  14024. /**
  14025. * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
  14026. * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
  14027. * terminated with `\n` and started with `indent`.
  14028. *
  14029. * @param {string} text
  14030. * @param {string} indent
  14031. * @param {string} [mode='flow'] `'block'` prevents more-indented lines
  14032. * from being folded; `'quoted'` allows for `\` escapes, including escaped
  14033. * newlines
  14034. * @param {Object} options
  14035. * @param {number} [options.indentAtStart] Accounts for leading contents on
  14036. * the first line, defaulting to `indent.length`
  14037. * @param {number} [options.lineWidth=80]
  14038. * @param {number} [options.minContentWidth=20] Allow highly indented lines to
  14039. * stretch the line width or indent content from the start
  14040. * @param {function} options.onFold Called once if the text is folded
  14041. * @param {function} options.onFold Called once if any line of text exceeds
  14042. * lineWidth characters
  14043. */
  14044. function foldFlowLines(text, indent, mode, {
  14045. indentAtStart,
  14046. lineWidth = 80,
  14047. minContentWidth = 20,
  14048. onFold,
  14049. onOverflow
  14050. }) {
  14051. if (!lineWidth || lineWidth < 0) return text;
  14052. const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
  14053. if (text.length <= endStep) return text;
  14054. const folds = [];
  14055. const escapedFolds = {};
  14056. let end = lineWidth - indent.length;
  14057. if (typeof indentAtStart === 'number') {
  14058. if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart;
  14059. }
  14060. let split = undefined;
  14061. let prev = undefined;
  14062. let overflow = false;
  14063. let i = -1;
  14064. let escStart = -1;
  14065. let escEnd = -1;
  14066. if (mode === FOLD_BLOCK) {
  14067. i = consumeMoreIndentedLines(text, i);
  14068. if (i !== -1) end = i + endStep;
  14069. }
  14070. for (let ch; ch = text[i += 1];) {
  14071. if (mode === FOLD_QUOTED && ch === '\\') {
  14072. escStart = i;
  14073. switch (text[i + 1]) {
  14074. case 'x':
  14075. i += 3;
  14076. break;
  14077. case 'u':
  14078. i += 5;
  14079. break;
  14080. case 'U':
  14081. i += 9;
  14082. break;
  14083. default:
  14084. i += 1;
  14085. }
  14086. escEnd = i;
  14087. }
  14088. if (ch === '\n') {
  14089. if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i);
  14090. end = i + endStep;
  14091. split = undefined;
  14092. } else {
  14093. if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') {
  14094. // space surrounded by non-space can be replaced with newline + indent
  14095. const next = text[i + 1];
  14096. if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i;
  14097. }
  14098. if (i >= end) {
  14099. if (split) {
  14100. folds.push(split);
  14101. end = split + endStep;
  14102. split = undefined;
  14103. } else if (mode === FOLD_QUOTED) {
  14104. // white-space collected at end may stretch past lineWidth
  14105. while (prev === ' ' || prev === '\t') {
  14106. prev = ch;
  14107. ch = text[i += 1];
  14108. overflow = true;
  14109. } // Account for newline escape, but don't break preceding escape
  14110. const j = i > escEnd + 1 ? i - 2 : escStart - 1; // Bail out if lineWidth & minContentWidth are shorter than an escape string
  14111. if (escapedFolds[j]) return text;
  14112. folds.push(j);
  14113. escapedFolds[j] = true;
  14114. end = j + endStep;
  14115. split = undefined;
  14116. } else {
  14117. overflow = true;
  14118. }
  14119. }
  14120. }
  14121. prev = ch;
  14122. }
  14123. if (overflow && onOverflow) onOverflow();
  14124. if (folds.length === 0) return text;
  14125. if (onFold) onFold();
  14126. let res = text.slice(0, folds[0]);
  14127. for (let i = 0; i < folds.length; ++i) {
  14128. const fold = folds[i];
  14129. const end = folds[i + 1] || text.length;
  14130. if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else {
  14131. if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`;
  14132. res += `\n${indent}${text.slice(fold + 1, end)}`;
  14133. }
  14134. }
  14135. return res;
  14136. }
  14137. const getFoldOptions = ({
  14138. indentAtStart
  14139. }) => indentAtStart ? Object.assign({
  14140. indentAtStart
  14141. }, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will
  14142. // presume that's starting a new document.
  14143. const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str);
  14144. function lineLengthOverLimit(str, lineWidth, indentLength) {
  14145. if (!lineWidth || lineWidth < 0) return false;
  14146. const limit = lineWidth - indentLength;
  14147. const strLen = str.length;
  14148. if (strLen <= limit) return false;
  14149. for (let i = 0, start = 0; i < strLen; ++i) {
  14150. if (str[i] === '\n') {
  14151. if (i - start > limit) return true;
  14152. start = i + 1;
  14153. if (strLen - start <= limit) return false;
  14154. }
  14155. }
  14156. return true;
  14157. }
  14158. function doubleQuotedString(value, ctx) {
  14159. const {
  14160. implicitKey
  14161. } = ctx;
  14162. const {
  14163. jsonEncoding,
  14164. minMultiLineLength
  14165. } = strOptions.doubleQuoted;
  14166. const json = JSON.stringify(value);
  14167. if (jsonEncoding) return json;
  14168. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  14169. let str = '';
  14170. let start = 0;
  14171. for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
  14172. if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
  14173. // space before newline needs to be escaped to not be folded
  14174. str += json.slice(start, i) + '\\ ';
  14175. i += 1;
  14176. start = i;
  14177. ch = '\\';
  14178. }
  14179. if (ch === '\\') switch (json[i + 1]) {
  14180. case 'u':
  14181. {
  14182. str += json.slice(start, i);
  14183. const code = json.substr(i + 2, 4);
  14184. switch (code) {
  14185. case '0000':
  14186. str += '\\0';
  14187. break;
  14188. case '0007':
  14189. str += '\\a';
  14190. break;
  14191. case '000b':
  14192. str += '\\v';
  14193. break;
  14194. case '001b':
  14195. str += '\\e';
  14196. break;
  14197. case '0085':
  14198. str += '\\N';
  14199. break;
  14200. case '00a0':
  14201. str += '\\_';
  14202. break;
  14203. case '2028':
  14204. str += '\\L';
  14205. break;
  14206. case '2029':
  14207. str += '\\P';
  14208. break;
  14209. default:
  14210. if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6);
  14211. }
  14212. i += 5;
  14213. start = i + 1;
  14214. }
  14215. break;
  14216. case 'n':
  14217. if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
  14218. i += 1;
  14219. } else {
  14220. // folding will eat first newline
  14221. str += json.slice(start, i) + '\n\n';
  14222. while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') {
  14223. str += '\n';
  14224. i += 2;
  14225. }
  14226. str += indent; // space after newline needs to be escaped to not be folded
  14227. if (json[i + 2] === ' ') str += '\\';
  14228. i += 1;
  14229. start = i + 1;
  14230. }
  14231. break;
  14232. default:
  14233. i += 1;
  14234. }
  14235. }
  14236. str = start ? str + json.slice(start) : json;
  14237. return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
  14238. }
  14239. function singleQuotedString(value, ctx) {
  14240. if (ctx.implicitKey) {
  14241. if (/\n/.test(value)) return doubleQuotedString(value, ctx);
  14242. } else {
  14243. // single quoted string can't have leading or trailing whitespace around newline
  14244. if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx);
  14245. }
  14246. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  14247. const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
  14248. return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
  14249. }
  14250. function blockString({
  14251. comment,
  14252. type,
  14253. value
  14254. }, ctx, onComment, onChompKeep) {
  14255. // 1. Block can't end in whitespace unless the last line is non-empty.
  14256. // 2. Strings consisting of only whitespace are best rendered explicitly.
  14257. if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
  14258. return doubleQuotedString(value, ctx);
  14259. }
  14260. const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
  14261. const indentSize = indent ? '2' : '1'; // root is at -1
  14262. const literal = type === PlainValue$4.Type.BLOCK_FOLDED ? false : type === PlainValue$4.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length);
  14263. let header = literal ? '|' : '>';
  14264. if (!value) return header + '\n';
  14265. let wsStart = '';
  14266. let wsEnd = '';
  14267. value = value.replace(/[\n\t ]*$/, ws => {
  14268. const n = ws.indexOf('\n');
  14269. if (n === -1) {
  14270. header += '-'; // strip
  14271. } else if (value === ws || n !== ws.length - 1) {
  14272. header += '+'; // keep
  14273. if (onChompKeep) onChompKeep();
  14274. }
  14275. wsEnd = ws.replace(/\n$/, '');
  14276. return '';
  14277. }).replace(/^[\n ]*/, ws => {
  14278. if (ws.indexOf(' ') !== -1) header += indentSize;
  14279. const m = ws.match(/ +$/);
  14280. if (m) {
  14281. wsStart = ws.slice(0, -m[0].length);
  14282. return m[0];
  14283. } else {
  14284. wsStart = ws;
  14285. return '';
  14286. }
  14287. });
  14288. if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`);
  14289. if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`);
  14290. if (comment) {
  14291. header += ' #' + comment.replace(/ ?[\r\n]+/g, ' ');
  14292. if (onComment) onComment();
  14293. }
  14294. if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`;
  14295. if (literal) {
  14296. value = value.replace(/\n+/g, `$&${indent}`);
  14297. return `${header}\n${indent}${wsStart}${value}${wsEnd}`;
  14298. }
  14299. value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
  14300. // ^ ind.line ^ empty ^ capture next empty lines only at end of indent
  14301. .replace(/\n+/g, `$&${indent}`);
  14302. const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold);
  14303. return `${header}\n${indent}${body}`;
  14304. }
  14305. function plainString(item, ctx, onComment, onChompKeep) {
  14306. const {
  14307. comment,
  14308. type,
  14309. value
  14310. } = item;
  14311. const {
  14312. actualString,
  14313. implicitKey,
  14314. indent,
  14315. inFlow
  14316. } = ctx;
  14317. if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) {
  14318. return doubleQuotedString(value, ctx);
  14319. }
  14320. if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
  14321. // not allowed:
  14322. // - empty string, '-' or '?'
  14323. // - start with an indicator character (except [?:-]) or /[?-] /
  14324. // - '\n ', ': ' or ' \n' anywhere
  14325. // - '#' not preceded by a non-space char
  14326. // - end with ' ' or ':'
  14327. return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
  14328. }
  14329. if (!implicitKey && !inFlow && type !== PlainValue$4.Type.PLAIN && value.indexOf('\n') !== -1) {
  14330. // Where allowed & type not set explicitly, prefer block style for multiline strings
  14331. return blockString(item, ctx, onComment, onChompKeep);
  14332. }
  14333. if (indent === '' && containsDocumentMarker(value)) {
  14334. ctx.forceBlockIndent = true;
  14335. return blockString(item, ctx, onComment, onChompKeep);
  14336. }
  14337. const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and
  14338. // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
  14339. // and others in v1.1.
  14340. if (actualString) {
  14341. const {
  14342. tags
  14343. } = ctx.doc.schema;
  14344. const resolved = resolveScalar(str, tags, tags.scalarFallback).value;
  14345. if (typeof resolved !== 'string') return doubleQuotedString(value, ctx);
  14346. }
  14347. const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
  14348. if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) {
  14349. if (onComment) onComment();
  14350. return addCommentBefore(body, indent, comment);
  14351. }
  14352. return body;
  14353. }
  14354. function stringifyString(item, ctx, onComment, onChompKeep) {
  14355. const {
  14356. defaultType
  14357. } = strOptions;
  14358. const {
  14359. implicitKey,
  14360. inFlow
  14361. } = ctx;
  14362. let {
  14363. type,
  14364. value
  14365. } = item;
  14366. if (typeof value !== 'string') {
  14367. value = String(value);
  14368. item = Object.assign({}, item, {
  14369. value
  14370. });
  14371. }
  14372. const _stringify = _type => {
  14373. switch (_type) {
  14374. case PlainValue$4.Type.BLOCK_FOLDED:
  14375. case PlainValue$4.Type.BLOCK_LITERAL:
  14376. return blockString(item, ctx, onComment, onChompKeep);
  14377. case PlainValue$4.Type.QUOTE_DOUBLE:
  14378. return doubleQuotedString(value, ctx);
  14379. case PlainValue$4.Type.QUOTE_SINGLE:
  14380. return singleQuotedString(value, ctx);
  14381. case PlainValue$4.Type.PLAIN:
  14382. return plainString(item, ctx, onComment, onChompKeep);
  14383. default:
  14384. return null;
  14385. }
  14386. };
  14387. if (type !== PlainValue$4.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) {
  14388. // force double quotes on control characters
  14389. type = PlainValue$4.Type.QUOTE_DOUBLE;
  14390. } else if ((implicitKey || inFlow) && (type === PlainValue$4.Type.BLOCK_FOLDED || type === PlainValue$4.Type.BLOCK_LITERAL)) {
  14391. // should not happen; blocks are not valid inside flow containers
  14392. type = PlainValue$4.Type.QUOTE_DOUBLE;
  14393. }
  14394. let res = _stringify(type);
  14395. if (res === null) {
  14396. res = _stringify(defaultType);
  14397. if (res === null) throw new Error(`Unsupported default string type ${defaultType}`);
  14398. }
  14399. return res;
  14400. }
  14401. function stringifyNumber({
  14402. format,
  14403. minFractionDigits,
  14404. tag,
  14405. value
  14406. }) {
  14407. if (typeof value === 'bigint') return String(value);
  14408. if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf';
  14409. let n = JSON.stringify(value);
  14410. if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) {
  14411. let i = n.indexOf('.');
  14412. if (i < 0) {
  14413. i = n.length;
  14414. n += '.';
  14415. }
  14416. let d = minFractionDigits - (n.length - i - 1);
  14417. while (d-- > 0) n += '0';
  14418. }
  14419. return n;
  14420. }
  14421. function checkFlowCollectionEnd(errors, cst) {
  14422. let char, name;
  14423. switch (cst.type) {
  14424. case PlainValue$4.Type.FLOW_MAP:
  14425. char = '}';
  14426. name = 'flow map';
  14427. break;
  14428. case PlainValue$4.Type.FLOW_SEQ:
  14429. char = ']';
  14430. name = 'flow sequence';
  14431. break;
  14432. default:
  14433. errors.push(new PlainValue$4.YAMLSemanticError(cst, 'Not a flow collection!?'));
  14434. return;
  14435. }
  14436. let lastItem;
  14437. for (let i = cst.items.length - 1; i >= 0; --i) {
  14438. const item = cst.items[i];
  14439. if (!item || item.type !== PlainValue$4.Type.COMMENT) {
  14440. lastItem = item;
  14441. break;
  14442. }
  14443. }
  14444. if (lastItem && lastItem.char !== char) {
  14445. const msg = `Expected ${name} to end with ${char}`;
  14446. let err;
  14447. if (typeof lastItem.offset === 'number') {
  14448. err = new PlainValue$4.YAMLSemanticError(cst, msg);
  14449. err.offset = lastItem.offset + 1;
  14450. } else {
  14451. err = new PlainValue$4.YAMLSemanticError(lastItem, msg);
  14452. if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start;
  14453. }
  14454. errors.push(err);
  14455. }
  14456. }
  14457. function checkFlowCommentSpace(errors, comment) {
  14458. const prev = comment.context.src[comment.range.start - 1];
  14459. if (prev !== '\n' && prev !== '\t' && prev !== ' ') {
  14460. const msg = 'Comments must be separated from other tokens by white space characters';
  14461. errors.push(new PlainValue$4.YAMLSemanticError(comment, msg));
  14462. }
  14463. }
  14464. function getLongKeyError(source, key) {
  14465. const sk = String(key);
  14466. const k = sk.substr(0, 8) + '...' + sk.substr(-8);
  14467. return new PlainValue$4.YAMLSemanticError(source, `The "${k}" key is too long`);
  14468. }
  14469. function resolveComments(collection, comments) {
  14470. for (const {
  14471. afterKey,
  14472. before,
  14473. comment
  14474. } of comments) {
  14475. let item = collection.items[before];
  14476. if (!item) {
  14477. if (comment !== undefined) {
  14478. if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment;
  14479. }
  14480. } else {
  14481. if (afterKey && item.value) item = item.value;
  14482. if (comment === undefined) {
  14483. if (afterKey || !item.commentBefore) item.spaceBefore = true;
  14484. } else {
  14485. if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment;
  14486. }
  14487. }
  14488. }
  14489. }
  14490. // on error, will return { str: string, errors: Error[] }
  14491. function resolveString(doc, node) {
  14492. const res = node.strValue;
  14493. if (!res) return '';
  14494. if (typeof res === 'string') return res;
  14495. res.errors.forEach(error => {
  14496. if (!error.source) error.source = node;
  14497. doc.errors.push(error);
  14498. });
  14499. return res.str;
  14500. }
  14501. function resolveTagHandle(doc, node) {
  14502. const {
  14503. handle,
  14504. suffix
  14505. } = node.tag;
  14506. let prefix = doc.tagPrefixes.find(p => p.handle === handle);
  14507. if (!prefix) {
  14508. const dtp = doc.getDefaults().tagPrefixes;
  14509. if (dtp) prefix = dtp.find(p => p.handle === handle);
  14510. if (!prefix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`);
  14511. }
  14512. if (!suffix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag has no suffix.`);
  14513. if (handle === '!' && (doc.version || doc.options.version) === '1.0') {
  14514. if (suffix[0] === '^') {
  14515. doc.warnings.push(new PlainValue$4.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported'));
  14516. return suffix;
  14517. }
  14518. if (/[:/]/.test(suffix)) {
  14519. // word/foo -> tag:word.yaml.org,2002:foo
  14520. const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i);
  14521. return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`;
  14522. }
  14523. }
  14524. return prefix.prefix + decodeURIComponent(suffix);
  14525. }
  14526. function resolveTagName(doc, node) {
  14527. const {
  14528. tag,
  14529. type
  14530. } = node;
  14531. let nonSpecific = false;
  14532. if (tag) {
  14533. const {
  14534. handle,
  14535. suffix,
  14536. verbatim
  14537. } = tag;
  14538. if (verbatim) {
  14539. if (verbatim !== '!' && verbatim !== '!!') return verbatim;
  14540. const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`;
  14541. doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  14542. } else if (handle === '!' && !suffix) {
  14543. nonSpecific = true;
  14544. } else {
  14545. try {
  14546. return resolveTagHandle(doc, node);
  14547. } catch (error) {
  14548. doc.errors.push(error);
  14549. }
  14550. }
  14551. }
  14552. switch (type) {
  14553. case PlainValue$4.Type.BLOCK_FOLDED:
  14554. case PlainValue$4.Type.BLOCK_LITERAL:
  14555. case PlainValue$4.Type.QUOTE_DOUBLE:
  14556. case PlainValue$4.Type.QUOTE_SINGLE:
  14557. return PlainValue$4.defaultTags.STR;
  14558. case PlainValue$4.Type.FLOW_MAP:
  14559. case PlainValue$4.Type.MAP:
  14560. return PlainValue$4.defaultTags.MAP;
  14561. case PlainValue$4.Type.FLOW_SEQ:
  14562. case PlainValue$4.Type.SEQ:
  14563. return PlainValue$4.defaultTags.SEQ;
  14564. case PlainValue$4.Type.PLAIN:
  14565. return nonSpecific ? PlainValue$4.defaultTags.STR : null;
  14566. default:
  14567. return null;
  14568. }
  14569. }
  14570. function resolveByTagName(doc, node, tagName) {
  14571. const {
  14572. tags
  14573. } = doc.schema;
  14574. const matchWithTest = [];
  14575. for (const tag of tags) {
  14576. if (tag.tag === tagName) {
  14577. if (tag.test) matchWithTest.push(tag);else {
  14578. const res = tag.resolve(doc, node);
  14579. return res instanceof Collection ? res : new Scalar(res);
  14580. }
  14581. }
  14582. }
  14583. const str = resolveString(doc, node);
  14584. if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback);
  14585. return null;
  14586. }
  14587. function getFallbackTagName({
  14588. type
  14589. }) {
  14590. switch (type) {
  14591. case PlainValue$4.Type.FLOW_MAP:
  14592. case PlainValue$4.Type.MAP:
  14593. return PlainValue$4.defaultTags.MAP;
  14594. case PlainValue$4.Type.FLOW_SEQ:
  14595. case PlainValue$4.Type.SEQ:
  14596. return PlainValue$4.defaultTags.SEQ;
  14597. default:
  14598. return PlainValue$4.defaultTags.STR;
  14599. }
  14600. }
  14601. function resolveTag(doc, node, tagName) {
  14602. try {
  14603. const res = resolveByTagName(doc, node, tagName);
  14604. if (res) {
  14605. if (tagName && node.tag) res.tag = tagName;
  14606. return res;
  14607. }
  14608. } catch (error) {
  14609. /* istanbul ignore if */
  14610. if (!error.source) error.source = node;
  14611. doc.errors.push(error);
  14612. return null;
  14613. }
  14614. try {
  14615. const fallback = getFallbackTagName(node);
  14616. if (!fallback) throw new Error(`The tag ${tagName} is unavailable`);
  14617. const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`;
  14618. doc.warnings.push(new PlainValue$4.YAMLWarning(node, msg));
  14619. const res = resolveByTagName(doc, node, fallback);
  14620. res.tag = tagName;
  14621. return res;
  14622. } catch (error) {
  14623. const refError = new PlainValue$4.YAMLReferenceError(node, error.message);
  14624. refError.stack = error.stack;
  14625. doc.errors.push(refError);
  14626. return null;
  14627. }
  14628. }
  14629. const isCollectionItem = node => {
  14630. if (!node) return false;
  14631. const {
  14632. type
  14633. } = node;
  14634. return type === PlainValue$4.Type.MAP_KEY || type === PlainValue$4.Type.MAP_VALUE || type === PlainValue$4.Type.SEQ_ITEM;
  14635. };
  14636. function resolveNodeProps(errors, node) {
  14637. const comments = {
  14638. before: [],
  14639. after: []
  14640. };
  14641. let hasAnchor = false;
  14642. let hasTag = false;
  14643. const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props;
  14644. for (const {
  14645. start,
  14646. end
  14647. } of props) {
  14648. switch (node.context.src[start]) {
  14649. case PlainValue$4.Char.COMMENT:
  14650. {
  14651. if (!node.commentHasRequiredWhitespace(start)) {
  14652. const msg = 'Comments must be separated from other tokens by white space characters';
  14653. errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  14654. }
  14655. const {
  14656. header,
  14657. valueRange
  14658. } = node;
  14659. const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before;
  14660. cc.push(node.context.src.slice(start + 1, end));
  14661. break;
  14662. }
  14663. // Actual anchor & tag resolution is handled by schema, here we just complain
  14664. case PlainValue$4.Char.ANCHOR:
  14665. if (hasAnchor) {
  14666. const msg = 'A node can have at most one anchor';
  14667. errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  14668. }
  14669. hasAnchor = true;
  14670. break;
  14671. case PlainValue$4.Char.TAG:
  14672. if (hasTag) {
  14673. const msg = 'A node can have at most one tag';
  14674. errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  14675. }
  14676. hasTag = true;
  14677. break;
  14678. }
  14679. }
  14680. return {
  14681. comments,
  14682. hasAnchor,
  14683. hasTag
  14684. };
  14685. }
  14686. function resolveNodeValue(doc, node) {
  14687. const {
  14688. anchors,
  14689. errors,
  14690. schema
  14691. } = doc;
  14692. if (node.type === PlainValue$4.Type.ALIAS) {
  14693. const name = node.rawValue;
  14694. const src = anchors.getNode(name);
  14695. if (!src) {
  14696. const msg = `Aliased anchor not found: ${name}`;
  14697. errors.push(new PlainValue$4.YAMLReferenceError(node, msg));
  14698. return null;
  14699. } // Lazy resolution for circular references
  14700. const res = new Alias(src);
  14701. anchors._cstAliases.push(res);
  14702. return res;
  14703. }
  14704. const tagName = resolveTagName(doc, node);
  14705. if (tagName) return resolveTag(doc, node, tagName);
  14706. if (node.type !== PlainValue$4.Type.PLAIN) {
  14707. const msg = `Failed to resolve ${node.type} node here`;
  14708. errors.push(new PlainValue$4.YAMLSyntaxError(node, msg));
  14709. return null;
  14710. }
  14711. try {
  14712. const str = resolveString(doc, node);
  14713. return resolveScalar(str, schema.tags, schema.tags.scalarFallback);
  14714. } catch (error) {
  14715. if (!error.source) error.source = node;
  14716. errors.push(error);
  14717. return null;
  14718. }
  14719. } // sets node.resolved on success
  14720. function resolveNode(doc, node) {
  14721. if (!node) return null;
  14722. if (node.error) doc.errors.push(node.error);
  14723. const {
  14724. comments,
  14725. hasAnchor,
  14726. hasTag
  14727. } = resolveNodeProps(doc.errors, node);
  14728. if (hasAnchor) {
  14729. const {
  14730. anchors
  14731. } = doc;
  14732. const name = node.anchor;
  14733. const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor
  14734. // name have already been resolved, so it may safely be renamed.
  14735. if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as
  14736. // anchors need to be available during resolution to allow for
  14737. // circular references.
  14738. anchors.map[name] = node;
  14739. }
  14740. if (node.type === PlainValue$4.Type.ALIAS && (hasAnchor || hasTag)) {
  14741. const msg = 'An alias node must not specify any properties';
  14742. doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  14743. }
  14744. const res = resolveNodeValue(doc, node);
  14745. if (res) {
  14746. res.range = [node.range.start, node.range.end];
  14747. if (doc.options.keepCstNodes) res.cstNode = node;
  14748. if (doc.options.keepNodeTypes) res.type = node.type;
  14749. const cb = comments.before.join('\n');
  14750. if (cb) {
  14751. res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb;
  14752. }
  14753. const ca = comments.after.join('\n');
  14754. if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca;
  14755. }
  14756. return node.resolved = res;
  14757. }
  14758. function resolveMap(doc, cst) {
  14759. if (cst.type !== PlainValue$4.Type.MAP && cst.type !== PlainValue$4.Type.FLOW_MAP) {
  14760. const msg = `A ${cst.type} node cannot be resolved as a mapping`;
  14761. doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg));
  14762. return null;
  14763. }
  14764. const {
  14765. comments,
  14766. items
  14767. } = cst.type === PlainValue$4.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst);
  14768. const map = new YAMLMap();
  14769. map.items = items;
  14770. resolveComments(map, comments);
  14771. let hasCollectionKey = false;
  14772. for (let i = 0; i < items.length; ++i) {
  14773. const {
  14774. key: iKey
  14775. } = items[i];
  14776. if (iKey instanceof Collection) hasCollectionKey = true;
  14777. if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) {
  14778. items[i] = new Merge(items[i]);
  14779. const sources = items[i].value.items;
  14780. let error = null;
  14781. sources.some(node => {
  14782. if (node instanceof Alias) {
  14783. // During parsing, alias sources are CST nodes; to account for
  14784. // circular references their resolved values can't be used here.
  14785. const {
  14786. type
  14787. } = node.source;
  14788. if (type === PlainValue$4.Type.MAP || type === PlainValue$4.Type.FLOW_MAP) return false;
  14789. return error = 'Merge nodes aliases can only point to maps';
  14790. }
  14791. return error = 'Merge nodes can only have Alias nodes as values';
  14792. });
  14793. if (error) doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, error));
  14794. } else {
  14795. for (let j = i + 1; j < items.length; ++j) {
  14796. const {
  14797. key: jKey
  14798. } = items[j];
  14799. if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) {
  14800. const msg = `Map keys must be unique; "${iKey}" is repeated`;
  14801. doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, msg));
  14802. break;
  14803. }
  14804. }
  14805. }
  14806. }
  14807. if (hasCollectionKey && !doc.options.mapAsMap) {
  14808. const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
  14809. doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn));
  14810. }
  14811. cst.resolved = map;
  14812. return map;
  14813. }
  14814. const valueHasPairComment = ({
  14815. context: {
  14816. lineStart,
  14817. node,
  14818. src
  14819. },
  14820. props
  14821. }) => {
  14822. if (props.length === 0) return false;
  14823. const {
  14824. start
  14825. } = props[0];
  14826. if (node && start > node.valueRange.start) return false;
  14827. if (src[start] !== PlainValue$4.Char.COMMENT) return false;
  14828. for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false;
  14829. return true;
  14830. };
  14831. function resolvePairComment(item, pair) {
  14832. if (!valueHasPairComment(item)) return;
  14833. const comment = item.getPropValue(0, PlainValue$4.Char.COMMENT, true);
  14834. let found = false;
  14835. const cb = pair.value.commentBefore;
  14836. if (cb && cb.startsWith(comment)) {
  14837. pair.value.commentBefore = cb.substr(comment.length + 1);
  14838. found = true;
  14839. } else {
  14840. const cc = pair.value.comment;
  14841. if (!item.node && cc && cc.startsWith(comment)) {
  14842. pair.value.comment = cc.substr(comment.length + 1);
  14843. found = true;
  14844. }
  14845. }
  14846. if (found) pair.comment = comment;
  14847. }
  14848. function resolveBlockMapItems(doc, cst) {
  14849. const comments = [];
  14850. const items = [];
  14851. let key = undefined;
  14852. let keyStart = null;
  14853. for (let i = 0; i < cst.items.length; ++i) {
  14854. const item = cst.items[i];
  14855. switch (item.type) {
  14856. case PlainValue$4.Type.BLANK_LINE:
  14857. comments.push({
  14858. afterKey: !!key,
  14859. before: items.length
  14860. });
  14861. break;
  14862. case PlainValue$4.Type.COMMENT:
  14863. comments.push({
  14864. afterKey: !!key,
  14865. before: items.length,
  14866. comment: item.comment
  14867. });
  14868. break;
  14869. case PlainValue$4.Type.MAP_KEY:
  14870. if (key !== undefined) items.push(new Pair(key));
  14871. if (item.error) doc.errors.push(item.error);
  14872. key = resolveNode(doc, item.node);
  14873. keyStart = null;
  14874. break;
  14875. case PlainValue$4.Type.MAP_VALUE:
  14876. {
  14877. if (key === undefined) key = null;
  14878. if (item.error) doc.errors.push(item.error);
  14879. if (!item.context.atLineStart && item.node && item.node.type === PlainValue$4.Type.MAP && !item.node.context.atLineStart) {
  14880. const msg = 'Nested mappings are not allowed in compact mappings';
  14881. doc.errors.push(new PlainValue$4.YAMLSemanticError(item.node, msg));
  14882. }
  14883. let valueNode = item.node;
  14884. if (!valueNode && item.props.length > 0) {
  14885. // Comments on an empty mapping value need to be preserved, so we
  14886. // need to construct a minimal empty node here to use instead of the
  14887. // missing `item.node`. -- eemeli/yaml#19
  14888. valueNode = new PlainValue$4.PlainValue(PlainValue$4.Type.PLAIN, []);
  14889. valueNode.context = {
  14890. parent: item,
  14891. src: item.context.src
  14892. };
  14893. const pos = item.range.start + 1;
  14894. valueNode.range = {
  14895. start: pos,
  14896. end: pos
  14897. };
  14898. valueNode.valueRange = {
  14899. start: pos,
  14900. end: pos
  14901. };
  14902. if (typeof item.range.origStart === 'number') {
  14903. const origPos = item.range.origStart + 1;
  14904. valueNode.range.origStart = valueNode.range.origEnd = origPos;
  14905. valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos;
  14906. }
  14907. }
  14908. const pair = new Pair(key, resolveNode(doc, valueNode));
  14909. resolvePairComment(item, pair);
  14910. items.push(pair);
  14911. if (key && typeof keyStart === 'number') {
  14912. if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
  14913. }
  14914. key = undefined;
  14915. keyStart = null;
  14916. }
  14917. break;
  14918. default:
  14919. if (key !== undefined) items.push(new Pair(key));
  14920. key = resolveNode(doc, item);
  14921. keyStart = item.range.start;
  14922. if (item.error) doc.errors.push(item.error);
  14923. next: for (let j = i + 1;; ++j) {
  14924. const nextItem = cst.items[j];
  14925. switch (nextItem && nextItem.type) {
  14926. case PlainValue$4.Type.BLANK_LINE:
  14927. case PlainValue$4.Type.COMMENT:
  14928. continue next;
  14929. case PlainValue$4.Type.MAP_VALUE:
  14930. break next;
  14931. default:
  14932. {
  14933. const msg = 'Implicit map keys need to be followed by map values';
  14934. doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
  14935. break next;
  14936. }
  14937. }
  14938. }
  14939. if (item.valueRangeContainsNewline) {
  14940. const msg = 'Implicit map keys need to be on a single line';
  14941. doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
  14942. }
  14943. }
  14944. }
  14945. if (key !== undefined) items.push(new Pair(key));
  14946. return {
  14947. comments,
  14948. items
  14949. };
  14950. }
  14951. function resolveFlowMapItems(doc, cst) {
  14952. const comments = [];
  14953. const items = [];
  14954. let key = undefined;
  14955. let explicitKey = false;
  14956. let next = '{';
  14957. for (let i = 0; i < cst.items.length; ++i) {
  14958. const item = cst.items[i];
  14959. if (typeof item.char === 'string') {
  14960. const {
  14961. char,
  14962. offset
  14963. } = item;
  14964. if (char === '?' && key === undefined && !explicitKey) {
  14965. explicitKey = true;
  14966. next = ':';
  14967. continue;
  14968. }
  14969. if (char === ':') {
  14970. if (key === undefined) key = null;
  14971. if (next === ':') {
  14972. next = ',';
  14973. continue;
  14974. }
  14975. } else {
  14976. if (explicitKey) {
  14977. if (key === undefined && char !== ',') key = null;
  14978. explicitKey = false;
  14979. }
  14980. if (key !== undefined) {
  14981. items.push(new Pair(key));
  14982. key = undefined;
  14983. if (char === ',') {
  14984. next = ':';
  14985. continue;
  14986. }
  14987. }
  14988. }
  14989. if (char === '}') {
  14990. if (i === cst.items.length - 1) continue;
  14991. } else if (char === next) {
  14992. next = ':';
  14993. continue;
  14994. }
  14995. const msg = `Flow map contains an unexpected ${char}`;
  14996. const err = new PlainValue$4.YAMLSyntaxError(cst, msg);
  14997. err.offset = offset;
  14998. doc.errors.push(err);
  14999. } else if (item.type === PlainValue$4.Type.BLANK_LINE) {
  15000. comments.push({
  15001. afterKey: !!key,
  15002. before: items.length
  15003. });
  15004. } else if (item.type === PlainValue$4.Type.COMMENT) {
  15005. checkFlowCommentSpace(doc.errors, item);
  15006. comments.push({
  15007. afterKey: !!key,
  15008. before: items.length,
  15009. comment: item.comment
  15010. });
  15011. } else if (key === undefined) {
  15012. if (next === ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Separator , missing in flow map'));
  15013. key = resolveNode(doc, item);
  15014. } else {
  15015. if (next !== ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Indicator : missing in flow map entry'));
  15016. items.push(new Pair(key, resolveNode(doc, item)));
  15017. key = undefined;
  15018. explicitKey = false;
  15019. }
  15020. }
  15021. checkFlowCollectionEnd(doc.errors, cst);
  15022. if (key !== undefined) items.push(new Pair(key));
  15023. return {
  15024. comments,
  15025. items
  15026. };
  15027. }
  15028. function resolveSeq$3(doc, cst) {
  15029. if (cst.type !== PlainValue$4.Type.SEQ && cst.type !== PlainValue$4.Type.FLOW_SEQ) {
  15030. const msg = `A ${cst.type} node cannot be resolved as a sequence`;
  15031. doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg));
  15032. return null;
  15033. }
  15034. const {
  15035. comments,
  15036. items
  15037. } = cst.type === PlainValue$4.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst);
  15038. const seq = new YAMLSeq();
  15039. seq.items = items;
  15040. resolveComments(seq, comments);
  15041. if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) {
  15042. const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
  15043. doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn));
  15044. }
  15045. cst.resolved = seq;
  15046. return seq;
  15047. }
  15048. function resolveBlockSeqItems(doc, cst) {
  15049. const comments = [];
  15050. const items = [];
  15051. for (let i = 0; i < cst.items.length; ++i) {
  15052. const item = cst.items[i];
  15053. switch (item.type) {
  15054. case PlainValue$4.Type.BLANK_LINE:
  15055. comments.push({
  15056. before: items.length
  15057. });
  15058. break;
  15059. case PlainValue$4.Type.COMMENT:
  15060. comments.push({
  15061. comment: item.comment,
  15062. before: items.length
  15063. });
  15064. break;
  15065. case PlainValue$4.Type.SEQ_ITEM:
  15066. if (item.error) doc.errors.push(item.error);
  15067. items.push(resolveNode(doc, item.node));
  15068. if (item.hasProps) {
  15069. const msg = 'Sequence items cannot have tags or anchors before the - indicator';
  15070. doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
  15071. }
  15072. break;
  15073. default:
  15074. if (item.error) doc.errors.push(item.error);
  15075. doc.errors.push(new PlainValue$4.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`));
  15076. }
  15077. }
  15078. return {
  15079. comments,
  15080. items
  15081. };
  15082. }
  15083. function resolveFlowSeqItems(doc, cst) {
  15084. const comments = [];
  15085. const items = [];
  15086. let explicitKey = false;
  15087. let key = undefined;
  15088. let keyStart = null;
  15089. let next = '[';
  15090. let prevItem = null;
  15091. for (let i = 0; i < cst.items.length; ++i) {
  15092. const item = cst.items[i];
  15093. if (typeof item.char === 'string') {
  15094. const {
  15095. char,
  15096. offset
  15097. } = item;
  15098. if (char !== ':' && (explicitKey || key !== undefined)) {
  15099. if (explicitKey && key === undefined) key = next ? items.pop() : null;
  15100. items.push(new Pair(key));
  15101. explicitKey = false;
  15102. key = undefined;
  15103. keyStart = null;
  15104. }
  15105. if (char === next) {
  15106. next = null;
  15107. } else if (!next && char === '?') {
  15108. explicitKey = true;
  15109. } else if (next !== '[' && char === ':' && key === undefined) {
  15110. if (next === ',') {
  15111. key = items.pop();
  15112. if (key instanceof Pair) {
  15113. const msg = 'Chaining flow sequence pairs is invalid';
  15114. const err = new PlainValue$4.YAMLSemanticError(cst, msg);
  15115. err.offset = offset;
  15116. doc.errors.push(err);
  15117. }
  15118. if (!explicitKey && typeof keyStart === 'number') {
  15119. const keyEnd = item.range ? item.range.start : item.offset;
  15120. if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
  15121. const {
  15122. src
  15123. } = prevItem.context;
  15124. for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') {
  15125. const msg = 'Implicit keys of flow sequence pairs need to be on a single line';
  15126. doc.errors.push(new PlainValue$4.YAMLSemanticError(prevItem, msg));
  15127. break;
  15128. }
  15129. }
  15130. } else {
  15131. key = null;
  15132. }
  15133. keyStart = null;
  15134. explicitKey = false;
  15135. next = null;
  15136. } else if (next === '[' || char !== ']' || i < cst.items.length - 1) {
  15137. const msg = `Flow sequence contains an unexpected ${char}`;
  15138. const err = new PlainValue$4.YAMLSyntaxError(cst, msg);
  15139. err.offset = offset;
  15140. doc.errors.push(err);
  15141. }
  15142. } else if (item.type === PlainValue$4.Type.BLANK_LINE) {
  15143. comments.push({
  15144. before: items.length
  15145. });
  15146. } else if (item.type === PlainValue$4.Type.COMMENT) {
  15147. checkFlowCommentSpace(doc.errors, item);
  15148. comments.push({
  15149. comment: item.comment,
  15150. before: items.length
  15151. });
  15152. } else {
  15153. if (next) {
  15154. const msg = `Expected a ${next} in flow sequence`;
  15155. doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
  15156. }
  15157. const value = resolveNode(doc, item);
  15158. if (key === undefined) {
  15159. items.push(value);
  15160. prevItem = item;
  15161. } else {
  15162. items.push(new Pair(key, value));
  15163. key = undefined;
  15164. }
  15165. keyStart = item.range.start;
  15166. next = ',';
  15167. }
  15168. }
  15169. checkFlowCollectionEnd(doc.errors, cst);
  15170. if (key !== undefined) items.push(new Pair(key));
  15171. return {
  15172. comments,
  15173. items
  15174. };
  15175. }
  15176. resolveSeqD03cb037.Alias = Alias;
  15177. resolveSeqD03cb037.Collection = Collection;
  15178. resolveSeqD03cb037.Merge = Merge;
  15179. resolveSeqD03cb037.Node = Node$1;
  15180. resolveSeqD03cb037.Pair = Pair;
  15181. resolveSeqD03cb037.Scalar = Scalar;
  15182. resolveSeqD03cb037.YAMLMap = YAMLMap;
  15183. resolveSeqD03cb037.YAMLSeq = YAMLSeq;
  15184. resolveSeqD03cb037.addComment = addComment;
  15185. resolveSeqD03cb037.binaryOptions = binaryOptions;
  15186. resolveSeqD03cb037.boolOptions = boolOptions;
  15187. resolveSeqD03cb037.findPair = findPair;
  15188. resolveSeqD03cb037.intOptions = intOptions;
  15189. resolveSeqD03cb037.isEmptyPath = isEmptyPath;
  15190. resolveSeqD03cb037.nullOptions = nullOptions;
  15191. resolveSeqD03cb037.resolveMap = resolveMap;
  15192. resolveSeqD03cb037.resolveNode = resolveNode;
  15193. resolveSeqD03cb037.resolveSeq = resolveSeq$3;
  15194. resolveSeqD03cb037.resolveString = resolveString;
  15195. resolveSeqD03cb037.strOptions = strOptions;
  15196. resolveSeqD03cb037.stringifyNumber = stringifyNumber;
  15197. resolveSeqD03cb037.stringifyString = stringifyString;
  15198. resolveSeqD03cb037.toJSON = toJSON;
  15199. var Schema88e323a7 = {};
  15200. var warnings1000a372 = {};
  15201. var PlainValue$3 = PlainValueEc8e588e;
  15202. var resolveSeq$2 = resolveSeqD03cb037;
  15203. /* global atob, btoa, Buffer */
  15204. const binary = {
  15205. identify: value => value instanceof Uint8Array,
  15206. // Buffer inherits from Uint8Array
  15207. default: false,
  15208. tag: 'tag:yaml.org,2002:binary',
  15209. /**
  15210. * Returns a Buffer in node and an Uint8Array in browsers
  15211. *
  15212. * To use the resulting buffer as an image, you'll want to do something like:
  15213. *
  15214. * const blob = new Blob([buffer], { type: 'image/jpeg' })
  15215. * document.querySelector('#photo').src = URL.createObjectURL(blob)
  15216. */
  15217. resolve: (doc, node) => {
  15218. const src = resolveSeq$2.resolveString(doc, node);
  15219. if (typeof Buffer === 'function') {
  15220. return Buffer.from(src, 'base64');
  15221. } else if (typeof atob === 'function') {
  15222. // On IE 11, atob() can't handle newlines
  15223. const str = atob(src.replace(/[\n\r]/g, ''));
  15224. const buffer = new Uint8Array(str.length);
  15225. for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i);
  15226. return buffer;
  15227. } else {
  15228. const msg = 'This environment does not support reading binary tags; either Buffer or atob is required';
  15229. doc.errors.push(new PlainValue$3.YAMLReferenceError(node, msg));
  15230. return null;
  15231. }
  15232. },
  15233. options: resolveSeq$2.binaryOptions,
  15234. stringify: ({
  15235. comment,
  15236. type,
  15237. value
  15238. }, ctx, onComment, onChompKeep) => {
  15239. let src;
  15240. if (typeof Buffer === 'function') {
  15241. src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64');
  15242. } else if (typeof btoa === 'function') {
  15243. let s = '';
  15244. for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]);
  15245. src = btoa(s);
  15246. } else {
  15247. throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
  15248. }
  15249. if (!type) type = resolveSeq$2.binaryOptions.defaultType;
  15250. if (type === PlainValue$3.Type.QUOTE_DOUBLE) {
  15251. value = src;
  15252. } else {
  15253. const {
  15254. lineWidth
  15255. } = resolveSeq$2.binaryOptions;
  15256. const n = Math.ceil(src.length / lineWidth);
  15257. const lines = new Array(n);
  15258. for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
  15259. lines[i] = src.substr(o, lineWidth);
  15260. }
  15261. value = lines.join(type === PlainValue$3.Type.BLOCK_LITERAL ? '\n' : ' ');
  15262. }
  15263. return resolveSeq$2.stringifyString({
  15264. comment,
  15265. type,
  15266. value
  15267. }, ctx, onComment, onChompKeep);
  15268. }
  15269. };
  15270. function parsePairs(doc, cst) {
  15271. const seq = resolveSeq$2.resolveSeq(doc, cst);
  15272. for (let i = 0; i < seq.items.length; ++i) {
  15273. let item = seq.items[i];
  15274. if (item instanceof resolveSeq$2.Pair) continue;else if (item instanceof resolveSeq$2.YAMLMap) {
  15275. if (item.items.length > 1) {
  15276. const msg = 'Each pair must have its own sequence indicator';
  15277. throw new PlainValue$3.YAMLSemanticError(cst, msg);
  15278. }
  15279. const pair = item.items[0] || new resolveSeq$2.Pair();
  15280. if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore;
  15281. if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment;
  15282. item = pair;
  15283. }
  15284. seq.items[i] = item instanceof resolveSeq$2.Pair ? item : new resolveSeq$2.Pair(item);
  15285. }
  15286. return seq;
  15287. }
  15288. function createPairs(schema, iterable, ctx) {
  15289. const pairs = new resolveSeq$2.YAMLSeq(schema);
  15290. pairs.tag = 'tag:yaml.org,2002:pairs';
  15291. for (const it of iterable) {
  15292. let key, value;
  15293. if (Array.isArray(it)) {
  15294. if (it.length === 2) {
  15295. key = it[0];
  15296. value = it[1];
  15297. } else throw new TypeError(`Expected [key, value] tuple: ${it}`);
  15298. } else if (it && it instanceof Object) {
  15299. const keys = Object.keys(it);
  15300. if (keys.length === 1) {
  15301. key = keys[0];
  15302. value = it[key];
  15303. } else throw new TypeError(`Expected { key: value } tuple: ${it}`);
  15304. } else {
  15305. key = it;
  15306. }
  15307. const pair = schema.createPair(key, value, ctx);
  15308. pairs.items.push(pair);
  15309. }
  15310. return pairs;
  15311. }
  15312. const pairs = {
  15313. default: false,
  15314. tag: 'tag:yaml.org,2002:pairs',
  15315. resolve: parsePairs,
  15316. createNode: createPairs
  15317. };
  15318. class YAMLOMap extends resolveSeq$2.YAMLSeq {
  15319. constructor() {
  15320. super();
  15321. PlainValue$3._defineProperty(this, "add", resolveSeq$2.YAMLMap.prototype.add.bind(this));
  15322. PlainValue$3._defineProperty(this, "delete", resolveSeq$2.YAMLMap.prototype.delete.bind(this));
  15323. PlainValue$3._defineProperty(this, "get", resolveSeq$2.YAMLMap.prototype.get.bind(this));
  15324. PlainValue$3._defineProperty(this, "has", resolveSeq$2.YAMLMap.prototype.has.bind(this));
  15325. PlainValue$3._defineProperty(this, "set", resolveSeq$2.YAMLMap.prototype.set.bind(this));
  15326. this.tag = YAMLOMap.tag;
  15327. }
  15328. toJSON(_, ctx) {
  15329. const map = new Map();
  15330. if (ctx && ctx.onCreate) ctx.onCreate(map);
  15331. for (const pair of this.items) {
  15332. let key, value;
  15333. if (pair instanceof resolveSeq$2.Pair) {
  15334. key = resolveSeq$2.toJSON(pair.key, '', ctx);
  15335. value = resolveSeq$2.toJSON(pair.value, key, ctx);
  15336. } else {
  15337. key = resolveSeq$2.toJSON(pair, '', ctx);
  15338. }
  15339. if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys');
  15340. map.set(key, value);
  15341. }
  15342. return map;
  15343. }
  15344. }
  15345. PlainValue$3._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap');
  15346. function parseOMap(doc, cst) {
  15347. const pairs = parsePairs(doc, cst);
  15348. const seenKeys = [];
  15349. for (const {
  15350. key
  15351. } of pairs.items) {
  15352. if (key instanceof resolveSeq$2.Scalar) {
  15353. if (seenKeys.includes(key.value)) {
  15354. const msg = 'Ordered maps must not include duplicate keys';
  15355. throw new PlainValue$3.YAMLSemanticError(cst, msg);
  15356. } else {
  15357. seenKeys.push(key.value);
  15358. }
  15359. }
  15360. }
  15361. return Object.assign(new YAMLOMap(), pairs);
  15362. }
  15363. function createOMap(schema, iterable, ctx) {
  15364. const pairs = createPairs(schema, iterable, ctx);
  15365. const omap = new YAMLOMap();
  15366. omap.items = pairs.items;
  15367. return omap;
  15368. }
  15369. const omap = {
  15370. identify: value => value instanceof Map,
  15371. nodeClass: YAMLOMap,
  15372. default: false,
  15373. tag: 'tag:yaml.org,2002:omap',
  15374. resolve: parseOMap,
  15375. createNode: createOMap
  15376. };
  15377. class YAMLSet extends resolveSeq$2.YAMLMap {
  15378. constructor() {
  15379. super();
  15380. this.tag = YAMLSet.tag;
  15381. }
  15382. add(key) {
  15383. const pair = key instanceof resolveSeq$2.Pair ? key : new resolveSeq$2.Pair(key);
  15384. const prev = resolveSeq$2.findPair(this.items, pair.key);
  15385. if (!prev) this.items.push(pair);
  15386. }
  15387. get(key, keepPair) {
  15388. const pair = resolveSeq$2.findPair(this.items, key);
  15389. return !keepPair && pair instanceof resolveSeq$2.Pair ? pair.key instanceof resolveSeq$2.Scalar ? pair.key.value : pair.key : pair;
  15390. }
  15391. set(key, value) {
  15392. if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
  15393. const prev = resolveSeq$2.findPair(this.items, key);
  15394. if (prev && !value) {
  15395. this.items.splice(this.items.indexOf(prev), 1);
  15396. } else if (!prev && value) {
  15397. this.items.push(new resolveSeq$2.Pair(key));
  15398. }
  15399. }
  15400. toJSON(_, ctx) {
  15401. return super.toJSON(_, ctx, Set);
  15402. }
  15403. toString(ctx, onComment, onChompKeep) {
  15404. if (!ctx) return JSON.stringify(this);
  15405. if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values');
  15406. }
  15407. }
  15408. PlainValue$3._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set');
  15409. function parseSet(doc, cst) {
  15410. const map = resolveSeq$2.resolveMap(doc, cst);
  15411. if (!map.hasAllNullValues()) throw new PlainValue$3.YAMLSemanticError(cst, 'Set items must all have null values');
  15412. return Object.assign(new YAMLSet(), map);
  15413. }
  15414. function createSet(schema, iterable, ctx) {
  15415. const set = new YAMLSet();
  15416. for (const value of iterable) set.items.push(schema.createPair(value, null, ctx));
  15417. return set;
  15418. }
  15419. const set = {
  15420. identify: value => value instanceof Set,
  15421. nodeClass: YAMLSet,
  15422. default: false,
  15423. tag: 'tag:yaml.org,2002:set',
  15424. resolve: parseSet,
  15425. createNode: createSet
  15426. };
  15427. const parseSexagesimal = (sign, parts) => {
  15428. const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0);
  15429. return sign === '-' ? -n : n;
  15430. }; // hhhh:mm:ss.sss
  15431. const stringifySexagesimal = ({
  15432. value
  15433. }) => {
  15434. if (isNaN(value) || !isFinite(value)) return resolveSeq$2.stringifyNumber(value);
  15435. let sign = '';
  15436. if (value < 0) {
  15437. sign = '-';
  15438. value = Math.abs(value);
  15439. }
  15440. const parts = [value % 60]; // seconds, including ms
  15441. if (value < 60) {
  15442. parts.unshift(0); // at least one : is required
  15443. } else {
  15444. value = Math.round((value - parts[0]) / 60);
  15445. parts.unshift(value % 60); // minutes
  15446. if (value >= 60) {
  15447. value = Math.round((value - parts[0]) / 60);
  15448. parts.unshift(value); // hours
  15449. }
  15450. }
  15451. return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error
  15452. ;
  15453. };
  15454. const intTime = {
  15455. identify: value => typeof value === 'number',
  15456. default: true,
  15457. tag: 'tag:yaml.org,2002:int',
  15458. format: 'TIME',
  15459. test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,
  15460. resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
  15461. stringify: stringifySexagesimal
  15462. };
  15463. const floatTime = {
  15464. identify: value => typeof value === 'number',
  15465. default: true,
  15466. tag: 'tag:yaml.org,2002:float',
  15467. format: 'TIME',
  15468. test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,
  15469. resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
  15470. stringify: stringifySexagesimal
  15471. };
  15472. const timestamp = {
  15473. identify: value => value instanceof Date,
  15474. default: true,
  15475. tag: 'tag:yaml.org,2002:timestamp',
  15476. // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
  15477. // may be omitted altogether, resulting in a date format. In such a case, the time part is
  15478. // assumed to be 00:00:00Z (start of day, UTC).
  15479. test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
  15480. '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace
  15481. '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
  15482. '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
  15483. ')?' + ')$'),
  15484. resolve: (str, year, month, day, hour, minute, second, millisec, tz) => {
  15485. if (millisec) millisec = (millisec + '00').substr(1, 3);
  15486. let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0);
  15487. if (tz && tz !== 'Z') {
  15488. let d = parseSexagesimal(tz[0], tz.slice(1));
  15489. if (Math.abs(d) < 30) d *= 60;
  15490. date -= 60000 * d;
  15491. }
  15492. return new Date(date);
  15493. },
  15494. stringify: ({
  15495. value
  15496. }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
  15497. };
  15498. /* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */
  15499. function shouldWarn(deprecation) {
  15500. const env = typeof process !== 'undefined' && process.env || {};
  15501. if (deprecation) {
  15502. if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS;
  15503. return !env.YAML_SILENCE_DEPRECATION_WARNINGS;
  15504. }
  15505. if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS;
  15506. return !env.YAML_SILENCE_WARNINGS;
  15507. }
  15508. function warn(warning, type) {
  15509. if (shouldWarn(false)) {
  15510. const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to
  15511. // https://github.com/facebook/jest/issues/2549
  15512. if (emit) emit(warning, type);else {
  15513. // eslint-disable-next-line no-console
  15514. console.warn(type ? `${type}: ${warning}` : warning);
  15515. }
  15516. }
  15517. }
  15518. function warnFileDeprecation(filename) {
  15519. if (shouldWarn(true)) {
  15520. const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/');
  15521. warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning');
  15522. }
  15523. }
  15524. const warned = {};
  15525. function warnOptionDeprecation(name, alternative) {
  15526. if (!warned[name] && shouldWarn(true)) {
  15527. warned[name] = true;
  15528. let msg = `The option '${name}' will be removed in a future release`;
  15529. msg += alternative ? `, use '${alternative}' instead.` : '.';
  15530. warn(msg, 'DeprecationWarning');
  15531. }
  15532. }
  15533. warnings1000a372.binary = binary;
  15534. warnings1000a372.floatTime = floatTime;
  15535. warnings1000a372.intTime = intTime;
  15536. warnings1000a372.omap = omap;
  15537. warnings1000a372.pairs = pairs;
  15538. warnings1000a372.set = set;
  15539. warnings1000a372.timestamp = timestamp;
  15540. warnings1000a372.warn = warn;
  15541. warnings1000a372.warnFileDeprecation = warnFileDeprecation;
  15542. warnings1000a372.warnOptionDeprecation = warnOptionDeprecation;
  15543. var PlainValue$2 = PlainValueEc8e588e;
  15544. var resolveSeq$1 = resolveSeqD03cb037;
  15545. var warnings$1 = warnings1000a372;
  15546. function createMap(schema, obj, ctx) {
  15547. const map = new resolveSeq$1.YAMLMap(schema);
  15548. if (obj instanceof Map) {
  15549. for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx));
  15550. } else if (obj && typeof obj === 'object') {
  15551. for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx));
  15552. }
  15553. if (typeof schema.sortMapEntries === 'function') {
  15554. map.items.sort(schema.sortMapEntries);
  15555. }
  15556. return map;
  15557. }
  15558. const map = {
  15559. createNode: createMap,
  15560. default: true,
  15561. nodeClass: resolveSeq$1.YAMLMap,
  15562. tag: 'tag:yaml.org,2002:map',
  15563. resolve: resolveSeq$1.resolveMap
  15564. };
  15565. function createSeq(schema, obj, ctx) {
  15566. const seq = new resolveSeq$1.YAMLSeq(schema);
  15567. if (obj && obj[Symbol.iterator]) {
  15568. for (const it of obj) {
  15569. const v = schema.createNode(it, ctx.wrapScalars, null, ctx);
  15570. seq.items.push(v);
  15571. }
  15572. }
  15573. return seq;
  15574. }
  15575. const seq = {
  15576. createNode: createSeq,
  15577. default: true,
  15578. nodeClass: resolveSeq$1.YAMLSeq,
  15579. tag: 'tag:yaml.org,2002:seq',
  15580. resolve: resolveSeq$1.resolveSeq
  15581. };
  15582. const string = {
  15583. identify: value => typeof value === 'string',
  15584. default: true,
  15585. tag: 'tag:yaml.org,2002:str',
  15586. resolve: resolveSeq$1.resolveString,
  15587. stringify(item, ctx, onComment, onChompKeep) {
  15588. ctx = Object.assign({
  15589. actualString: true
  15590. }, ctx);
  15591. return resolveSeq$1.stringifyString(item, ctx, onComment, onChompKeep);
  15592. },
  15593. options: resolveSeq$1.strOptions
  15594. };
  15595. const failsafe = [map, seq, string];
  15596. /* global BigInt */
  15597. const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value);
  15598. const intResolve$1 = (src, part, radix) => resolveSeq$1.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix);
  15599. function intStringify$1(node, radix, prefix) {
  15600. const {
  15601. value
  15602. } = node;
  15603. if (intIdentify$2(value) && value >= 0) return prefix + value.toString(radix);
  15604. return resolveSeq$1.stringifyNumber(node);
  15605. }
  15606. const nullObj = {
  15607. identify: value => value == null,
  15608. createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
  15609. default: true,
  15610. tag: 'tag:yaml.org,2002:null',
  15611. test: /^(?:~|[Nn]ull|NULL)?$/,
  15612. resolve: () => null,
  15613. options: resolveSeq$1.nullOptions,
  15614. stringify: () => resolveSeq$1.nullOptions.nullStr
  15615. };
  15616. const boolObj = {
  15617. identify: value => typeof value === 'boolean',
  15618. default: true,
  15619. tag: 'tag:yaml.org,2002:bool',
  15620. test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
  15621. resolve: str => str[0] === 't' || str[0] === 'T',
  15622. options: resolveSeq$1.boolOptions,
  15623. stringify: ({
  15624. value
  15625. }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr
  15626. };
  15627. const octObj = {
  15628. identify: value => intIdentify$2(value) && value >= 0,
  15629. default: true,
  15630. tag: 'tag:yaml.org,2002:int',
  15631. format: 'OCT',
  15632. test: /^0o([0-7]+)$/,
  15633. resolve: (str, oct) => intResolve$1(str, oct, 8),
  15634. options: resolveSeq$1.intOptions,
  15635. stringify: node => intStringify$1(node, 8, '0o')
  15636. };
  15637. const intObj = {
  15638. identify: intIdentify$2,
  15639. default: true,
  15640. tag: 'tag:yaml.org,2002:int',
  15641. test: /^[-+]?[0-9]+$/,
  15642. resolve: str => intResolve$1(str, str, 10),
  15643. options: resolveSeq$1.intOptions,
  15644. stringify: resolveSeq$1.stringifyNumber
  15645. };
  15646. const hexObj = {
  15647. identify: value => intIdentify$2(value) && value >= 0,
  15648. default: true,
  15649. tag: 'tag:yaml.org,2002:int',
  15650. format: 'HEX',
  15651. test: /^0x([0-9a-fA-F]+)$/,
  15652. resolve: (str, hex) => intResolve$1(str, hex, 16),
  15653. options: resolveSeq$1.intOptions,
  15654. stringify: node => intStringify$1(node, 16, '0x')
  15655. };
  15656. const nanObj = {
  15657. identify: value => typeof value === 'number',
  15658. default: true,
  15659. tag: 'tag:yaml.org,2002:float',
  15660. test: /^(?:[-+]?\.inf|(\.nan))$/i,
  15661. resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  15662. stringify: resolveSeq$1.stringifyNumber
  15663. };
  15664. const expObj = {
  15665. identify: value => typeof value === 'number',
  15666. default: true,
  15667. tag: 'tag:yaml.org,2002:float',
  15668. format: 'EXP',
  15669. test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
  15670. resolve: str => parseFloat(str),
  15671. stringify: ({
  15672. value
  15673. }) => Number(value).toExponential()
  15674. };
  15675. const floatObj = {
  15676. identify: value => typeof value === 'number',
  15677. default: true,
  15678. tag: 'tag:yaml.org,2002:float',
  15679. test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,
  15680. resolve(str, frac1, frac2) {
  15681. const frac = frac1 || frac2;
  15682. const node = new resolveSeq$1.Scalar(parseFloat(str));
  15683. if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length;
  15684. return node;
  15685. },
  15686. stringify: resolveSeq$1.stringifyNumber
  15687. };
  15688. const core$2 = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]);
  15689. /* global BigInt */
  15690. const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value);
  15691. const stringifyJSON = ({
  15692. value
  15693. }) => JSON.stringify(value);
  15694. const json = [map, seq, {
  15695. identify: value => typeof value === 'string',
  15696. default: true,
  15697. tag: 'tag:yaml.org,2002:str',
  15698. resolve: resolveSeq$1.resolveString,
  15699. stringify: stringifyJSON
  15700. }, {
  15701. identify: value => value == null,
  15702. createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
  15703. default: true,
  15704. tag: 'tag:yaml.org,2002:null',
  15705. test: /^null$/,
  15706. resolve: () => null,
  15707. stringify: stringifyJSON
  15708. }, {
  15709. identify: value => typeof value === 'boolean',
  15710. default: true,
  15711. tag: 'tag:yaml.org,2002:bool',
  15712. test: /^true|false$/,
  15713. resolve: str => str === 'true',
  15714. stringify: stringifyJSON
  15715. }, {
  15716. identify: intIdentify$1,
  15717. default: true,
  15718. tag: 'tag:yaml.org,2002:int',
  15719. test: /^-?(?:0|[1-9][0-9]*)$/,
  15720. resolve: str => resolveSeq$1.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10),
  15721. stringify: ({
  15722. value
  15723. }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
  15724. }, {
  15725. identify: value => typeof value === 'number',
  15726. default: true,
  15727. tag: 'tag:yaml.org,2002:float',
  15728. test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
  15729. resolve: str => parseFloat(str),
  15730. stringify: stringifyJSON
  15731. }];
  15732. json.scalarFallback = str => {
  15733. throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`);
  15734. };
  15735. /* global BigInt */
  15736. const boolStringify = ({
  15737. value
  15738. }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr;
  15739. const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value);
  15740. function intResolve(sign, src, radix) {
  15741. let str = src.replace(/_/g, '');
  15742. if (resolveSeq$1.intOptions.asBigInt) {
  15743. switch (radix) {
  15744. case 2:
  15745. str = `0b${str}`;
  15746. break;
  15747. case 8:
  15748. str = `0o${str}`;
  15749. break;
  15750. case 16:
  15751. str = `0x${str}`;
  15752. break;
  15753. }
  15754. const n = BigInt(str);
  15755. return sign === '-' ? BigInt(-1) * n : n;
  15756. }
  15757. const n = parseInt(str, radix);
  15758. return sign === '-' ? -1 * n : n;
  15759. }
  15760. function intStringify(node, radix, prefix) {
  15761. const {
  15762. value
  15763. } = node;
  15764. if (intIdentify(value)) {
  15765. const str = value.toString(radix);
  15766. return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
  15767. }
  15768. return resolveSeq$1.stringifyNumber(node);
  15769. }
  15770. const yaml11 = failsafe.concat([{
  15771. identify: value => value == null,
  15772. createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
  15773. default: true,
  15774. tag: 'tag:yaml.org,2002:null',
  15775. test: /^(?:~|[Nn]ull|NULL)?$/,
  15776. resolve: () => null,
  15777. options: resolveSeq$1.nullOptions,
  15778. stringify: () => resolveSeq$1.nullOptions.nullStr
  15779. }, {
  15780. identify: value => typeof value === 'boolean',
  15781. default: true,
  15782. tag: 'tag:yaml.org,2002:bool',
  15783. test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
  15784. resolve: () => true,
  15785. options: resolveSeq$1.boolOptions,
  15786. stringify: boolStringify
  15787. }, {
  15788. identify: value => typeof value === 'boolean',
  15789. default: true,
  15790. tag: 'tag:yaml.org,2002:bool',
  15791. test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
  15792. resolve: () => false,
  15793. options: resolveSeq$1.boolOptions,
  15794. stringify: boolStringify
  15795. }, {
  15796. identify: intIdentify,
  15797. default: true,
  15798. tag: 'tag:yaml.org,2002:int',
  15799. format: 'BIN',
  15800. test: /^([-+]?)0b([0-1_]+)$/,
  15801. resolve: (str, sign, bin) => intResolve(sign, bin, 2),
  15802. stringify: node => intStringify(node, 2, '0b')
  15803. }, {
  15804. identify: intIdentify,
  15805. default: true,
  15806. tag: 'tag:yaml.org,2002:int',
  15807. format: 'OCT',
  15808. test: /^([-+]?)0([0-7_]+)$/,
  15809. resolve: (str, sign, oct) => intResolve(sign, oct, 8),
  15810. stringify: node => intStringify(node, 8, '0')
  15811. }, {
  15812. identify: intIdentify,
  15813. default: true,
  15814. tag: 'tag:yaml.org,2002:int',
  15815. test: /^([-+]?)([0-9][0-9_]*)$/,
  15816. resolve: (str, sign, abs) => intResolve(sign, abs, 10),
  15817. stringify: resolveSeq$1.stringifyNumber
  15818. }, {
  15819. identify: intIdentify,
  15820. default: true,
  15821. tag: 'tag:yaml.org,2002:int',
  15822. format: 'HEX',
  15823. test: /^([-+]?)0x([0-9a-fA-F_]+)$/,
  15824. resolve: (str, sign, hex) => intResolve(sign, hex, 16),
  15825. stringify: node => intStringify(node, 16, '0x')
  15826. }, {
  15827. identify: value => typeof value === 'number',
  15828. default: true,
  15829. tag: 'tag:yaml.org,2002:float',
  15830. test: /^(?:[-+]?\.inf|(\.nan))$/i,
  15831. resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  15832. stringify: resolveSeq$1.stringifyNumber
  15833. }, {
  15834. identify: value => typeof value === 'number',
  15835. default: true,
  15836. tag: 'tag:yaml.org,2002:float',
  15837. format: 'EXP',
  15838. test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,
  15839. resolve: str => parseFloat(str.replace(/_/g, '')),
  15840. stringify: ({
  15841. value
  15842. }) => Number(value).toExponential()
  15843. }, {
  15844. identify: value => typeof value === 'number',
  15845. default: true,
  15846. tag: 'tag:yaml.org,2002:float',
  15847. test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,
  15848. resolve(str, frac) {
  15849. const node = new resolveSeq$1.Scalar(parseFloat(str.replace(/_/g, '')));
  15850. if (frac) {
  15851. const f = frac.replace(/_/g, '');
  15852. if (f[f.length - 1] === '0') node.minFractionDigits = f.length;
  15853. }
  15854. return node;
  15855. },
  15856. stringify: resolveSeq$1.stringifyNumber
  15857. }], warnings$1.binary, warnings$1.omap, warnings$1.pairs, warnings$1.set, warnings$1.intTime, warnings$1.floatTime, warnings$1.timestamp);
  15858. const schemas = {
  15859. core: core$2,
  15860. failsafe,
  15861. json,
  15862. yaml11
  15863. };
  15864. const tags = {
  15865. binary: warnings$1.binary,
  15866. bool: boolObj,
  15867. float: floatObj,
  15868. floatExp: expObj,
  15869. floatNaN: nanObj,
  15870. floatTime: warnings$1.floatTime,
  15871. int: intObj,
  15872. intHex: hexObj,
  15873. intOct: octObj,
  15874. intTime: warnings$1.intTime,
  15875. map,
  15876. null: nullObj,
  15877. omap: warnings$1.omap,
  15878. pairs: warnings$1.pairs,
  15879. seq,
  15880. set: warnings$1.set,
  15881. timestamp: warnings$1.timestamp
  15882. };
  15883. function findTagObject(value, tagName, tags) {
  15884. if (tagName) {
  15885. const match = tags.filter(t => t.tag === tagName);
  15886. const tagObj = match.find(t => !t.format) || match[0];
  15887. if (!tagObj) throw new Error(`Tag ${tagName} not found`);
  15888. return tagObj;
  15889. } // TODO: deprecate/remove class check
  15890. return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format);
  15891. }
  15892. function createNode$1(value, tagName, ctx) {
  15893. if (value instanceof resolveSeq$1.Node) return value;
  15894. const {
  15895. defaultPrefix,
  15896. onTagObj,
  15897. prevObjects,
  15898. schema,
  15899. wrapScalars
  15900. } = ctx;
  15901. if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2);
  15902. let tagObj = findTagObject(value, tagName, schema.tags);
  15903. if (!tagObj) {
  15904. if (typeof value.toJSON === 'function') value = value.toJSON();
  15905. if (!value || typeof value !== 'object') return wrapScalars ? new resolveSeq$1.Scalar(value) : value;
  15906. tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map;
  15907. }
  15908. if (onTagObj) {
  15909. onTagObj(tagObj);
  15910. delete ctx.onTagObj;
  15911. } // Detect duplicate references to the same object & use Alias nodes for all
  15912. // after first. The `obj` wrapper allows for circular references to resolve.
  15913. const obj = {
  15914. value: undefined,
  15915. node: undefined
  15916. };
  15917. if (value && typeof value === 'object' && prevObjects) {
  15918. const prev = prevObjects.get(value);
  15919. if (prev) {
  15920. const alias = new resolveSeq$1.Alias(prev); // leaves source dirty; must be cleaned by caller
  15921. ctx.aliasNodes.push(alias); // defined along with prevObjects
  15922. return alias;
  15923. }
  15924. obj.value = value;
  15925. prevObjects.set(value, obj);
  15926. }
  15927. obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq$1.Scalar(value) : value;
  15928. if (tagName && obj.node instanceof resolveSeq$1.Node) obj.node.tag = tagName;
  15929. return obj.node;
  15930. }
  15931. function getSchemaTags(schemas, knownTags, customTags, schemaId) {
  15932. let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11'
  15933. if (!tags) {
  15934. const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', ');
  15935. throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`);
  15936. }
  15937. if (Array.isArray(customTags)) {
  15938. for (const tag of customTags) tags = tags.concat(tag);
  15939. } else if (typeof customTags === 'function') {
  15940. tags = customTags(tags.slice());
  15941. }
  15942. for (let i = 0; i < tags.length; ++i) {
  15943. const tag = tags[i];
  15944. if (typeof tag === 'string') {
  15945. const tagObj = knownTags[tag];
  15946. if (!tagObj) {
  15947. const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', ');
  15948. throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
  15949. }
  15950. tags[i] = tagObj;
  15951. }
  15952. }
  15953. return tags;
  15954. }
  15955. const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
  15956. class Schema$2 {
  15957. // TODO: remove in v2
  15958. // TODO: remove in v2
  15959. constructor({
  15960. customTags,
  15961. merge,
  15962. schema,
  15963. sortMapEntries,
  15964. tags: deprecatedCustomTags
  15965. }) {
  15966. this.merge = !!merge;
  15967. this.name = schema;
  15968. this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null;
  15969. if (!customTags && deprecatedCustomTags) warnings$1.warnOptionDeprecation('tags', 'customTags');
  15970. this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema);
  15971. }
  15972. createNode(value, wrapScalars, tagName, ctx) {
  15973. const baseCtx = {
  15974. defaultPrefix: Schema$2.defaultPrefix,
  15975. schema: this,
  15976. wrapScalars
  15977. };
  15978. const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx;
  15979. return createNode$1(value, tagName, createCtx);
  15980. }
  15981. createPair(key, value, ctx) {
  15982. if (!ctx) ctx = {
  15983. wrapScalars: true
  15984. };
  15985. const k = this.createNode(key, ctx.wrapScalars, null, ctx);
  15986. const v = this.createNode(value, ctx.wrapScalars, null, ctx);
  15987. return new resolveSeq$1.Pair(k, v);
  15988. }
  15989. }
  15990. PlainValue$2._defineProperty(Schema$2, "defaultPrefix", PlainValue$2.defaultTagPrefix);
  15991. PlainValue$2._defineProperty(Schema$2, "defaultTags", PlainValue$2.defaultTags);
  15992. Schema88e323a7.Schema = Schema$2;
  15993. var PlainValue$1 = PlainValueEc8e588e;
  15994. var resolveSeq = resolveSeqD03cb037;
  15995. var Schema$1 = Schema88e323a7;
  15996. const defaultOptions$1 = {
  15997. anchorPrefix: 'a',
  15998. customTags: null,
  15999. indent: 2,
  16000. indentSeq: true,
  16001. keepCstNodes: false,
  16002. keepNodeTypes: true,
  16003. keepBlobsInJSON: true,
  16004. mapAsMap: false,
  16005. maxAliasCount: 100,
  16006. prettyErrors: false,
  16007. // TODO Set true in v2
  16008. simpleKeys: false,
  16009. version: '1.2'
  16010. };
  16011. const scalarOptions = {
  16012. get binary() {
  16013. return resolveSeq.binaryOptions;
  16014. },
  16015. set binary(opt) {
  16016. Object.assign(resolveSeq.binaryOptions, opt);
  16017. },
  16018. get bool() {
  16019. return resolveSeq.boolOptions;
  16020. },
  16021. set bool(opt) {
  16022. Object.assign(resolveSeq.boolOptions, opt);
  16023. },
  16024. get int() {
  16025. return resolveSeq.intOptions;
  16026. },
  16027. set int(opt) {
  16028. Object.assign(resolveSeq.intOptions, opt);
  16029. },
  16030. get null() {
  16031. return resolveSeq.nullOptions;
  16032. },
  16033. set null(opt) {
  16034. Object.assign(resolveSeq.nullOptions, opt);
  16035. },
  16036. get str() {
  16037. return resolveSeq.strOptions;
  16038. },
  16039. set str(opt) {
  16040. Object.assign(resolveSeq.strOptions, opt);
  16041. }
  16042. };
  16043. const documentOptions = {
  16044. '1.0': {
  16045. schema: 'yaml-1.1',
  16046. merge: true,
  16047. tagPrefixes: [{
  16048. handle: '!',
  16049. prefix: PlainValue$1.defaultTagPrefix
  16050. }, {
  16051. handle: '!!',
  16052. prefix: 'tag:private.yaml.org,2002:'
  16053. }]
  16054. },
  16055. 1.1: {
  16056. schema: 'yaml-1.1',
  16057. merge: true,
  16058. tagPrefixes: [{
  16059. handle: '!',
  16060. prefix: '!'
  16061. }, {
  16062. handle: '!!',
  16063. prefix: PlainValue$1.defaultTagPrefix
  16064. }]
  16065. },
  16066. 1.2: {
  16067. schema: 'core',
  16068. merge: false,
  16069. tagPrefixes: [{
  16070. handle: '!',
  16071. prefix: '!'
  16072. }, {
  16073. handle: '!!',
  16074. prefix: PlainValue$1.defaultTagPrefix
  16075. }]
  16076. }
  16077. };
  16078. function stringifyTag(doc, tag) {
  16079. if ((doc.version || doc.options.version) === '1.0') {
  16080. const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);
  16081. if (priv) return '!' + priv[1];
  16082. const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);
  16083. return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`;
  16084. }
  16085. let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0);
  16086. if (!p) {
  16087. const dtp = doc.getDefaults().tagPrefixes;
  16088. p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0);
  16089. }
  16090. if (!p) return tag[0] === '!' ? tag : `!<${tag}>`;
  16091. const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({
  16092. '!': '%21',
  16093. ',': '%2C',
  16094. '[': '%5B',
  16095. ']': '%5D',
  16096. '{': '%7B',
  16097. '}': '%7D'
  16098. })[ch]);
  16099. return p.handle + suffix;
  16100. }
  16101. function getTagObject(tags, item) {
  16102. if (item instanceof resolveSeq.Alias) return resolveSeq.Alias;
  16103. if (item.tag) {
  16104. const match = tags.filter(t => t.tag === item.tag);
  16105. if (match.length > 0) return match.find(t => t.format === item.format) || match[0];
  16106. }
  16107. let tagObj, obj;
  16108. if (item instanceof resolveSeq.Scalar) {
  16109. obj = item.value; // TODO: deprecate/remove class check
  16110. const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class);
  16111. tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format);
  16112. } else {
  16113. obj = item;
  16114. tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
  16115. }
  16116. if (!tagObj) {
  16117. const name = obj && obj.constructor ? obj.constructor.name : typeof obj;
  16118. throw new Error(`Tag not resolved for ${name} value`);
  16119. }
  16120. return tagObj;
  16121. } // needs to be called before value stringifier to allow for circular anchor refs
  16122. function stringifyProps(node, tagObj, {
  16123. anchors,
  16124. doc
  16125. }) {
  16126. const props = [];
  16127. const anchor = doc.anchors.getName(node);
  16128. if (anchor) {
  16129. anchors[anchor] = node;
  16130. props.push(`&${anchor}`);
  16131. }
  16132. if (node.tag) {
  16133. props.push(stringifyTag(doc, node.tag));
  16134. } else if (!tagObj.default) {
  16135. props.push(stringifyTag(doc, tagObj.tag));
  16136. }
  16137. return props.join(' ');
  16138. }
  16139. function stringify$2(item, ctx, onComment, onChompKeep) {
  16140. const {
  16141. anchors,
  16142. schema
  16143. } = ctx.doc;
  16144. let tagObj;
  16145. if (!(item instanceof resolveSeq.Node)) {
  16146. const createCtx = {
  16147. aliasNodes: [],
  16148. onTagObj: o => tagObj = o,
  16149. prevObjects: new Map()
  16150. };
  16151. item = schema.createNode(item, true, null, createCtx);
  16152. for (const alias of createCtx.aliasNodes) {
  16153. alias.source = alias.source.node;
  16154. let name = anchors.getName(alias.source);
  16155. if (!name) {
  16156. name = anchors.newName();
  16157. anchors.map[name] = alias.source;
  16158. }
  16159. }
  16160. }
  16161. if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep);
  16162. if (!tagObj) tagObj = getTagObject(schema.tags, item);
  16163. const props = stringifyProps(item, tagObj, ctx);
  16164. if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1;
  16165. const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep);
  16166. if (!props) return str;
  16167. return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`;
  16168. }
  16169. class Anchors {
  16170. static validAnchorNode(node) {
  16171. return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap;
  16172. }
  16173. constructor(prefix) {
  16174. PlainValue$1._defineProperty(this, "map", Object.create(null));
  16175. this.prefix = prefix;
  16176. }
  16177. createAlias(node, name) {
  16178. this.setAnchor(node, name);
  16179. return new resolveSeq.Alias(node);
  16180. }
  16181. createMergePair(...sources) {
  16182. const merge = new resolveSeq.Merge();
  16183. merge.value.items = sources.map(s => {
  16184. if (s instanceof resolveSeq.Alias) {
  16185. if (s.source instanceof resolveSeq.YAMLMap) return s;
  16186. } else if (s instanceof resolveSeq.YAMLMap) {
  16187. return this.createAlias(s);
  16188. }
  16189. throw new Error('Merge sources must be Map nodes or their Aliases');
  16190. });
  16191. return merge;
  16192. }
  16193. getName(node) {
  16194. const {
  16195. map
  16196. } = this;
  16197. return Object.keys(map).find(a => map[a] === node);
  16198. }
  16199. getNames() {
  16200. return Object.keys(this.map);
  16201. }
  16202. getNode(name) {
  16203. return this.map[name];
  16204. }
  16205. newName(prefix) {
  16206. if (!prefix) prefix = this.prefix;
  16207. const names = Object.keys(this.map);
  16208. for (let i = 1; true; ++i) {
  16209. const name = `${prefix}${i}`;
  16210. if (!names.includes(name)) return name;
  16211. }
  16212. } // During parsing, map & aliases contain CST nodes
  16213. resolveNodes() {
  16214. const {
  16215. map,
  16216. _cstAliases
  16217. } = this;
  16218. Object.keys(map).forEach(a => {
  16219. map[a] = map[a].resolved;
  16220. });
  16221. _cstAliases.forEach(a => {
  16222. a.source = a.source.resolved;
  16223. });
  16224. delete this._cstAliases;
  16225. }
  16226. setAnchor(node, name) {
  16227. if (node != null && !Anchors.validAnchorNode(node)) {
  16228. throw new Error('Anchors may only be set for Scalar, Seq and Map nodes');
  16229. }
  16230. if (name && /[\x00-\x19\s,[\]{}]/.test(name)) {
  16231. throw new Error('Anchor names must not contain whitespace or control characters');
  16232. }
  16233. const {
  16234. map
  16235. } = this;
  16236. const prev = node && Object.keys(map).find(a => map[a] === node);
  16237. if (prev) {
  16238. if (!name) {
  16239. return prev;
  16240. } else if (prev !== name) {
  16241. delete map[prev];
  16242. map[name] = node;
  16243. }
  16244. } else {
  16245. if (!name) {
  16246. if (!node) return null;
  16247. name = this.newName();
  16248. }
  16249. map[name] = node;
  16250. }
  16251. return name;
  16252. }
  16253. }
  16254. const visit$1 = (node, tags) => {
  16255. if (node && typeof node === 'object') {
  16256. const {
  16257. tag
  16258. } = node;
  16259. if (node instanceof resolveSeq.Collection) {
  16260. if (tag) tags[tag] = true;
  16261. node.items.forEach(n => visit$1(n, tags));
  16262. } else if (node instanceof resolveSeq.Pair) {
  16263. visit$1(node.key, tags);
  16264. visit$1(node.value, tags);
  16265. } else if (node instanceof resolveSeq.Scalar) {
  16266. if (tag) tags[tag] = true;
  16267. }
  16268. }
  16269. return tags;
  16270. };
  16271. const listTagNames = node => Object.keys(visit$1(node, {}));
  16272. function parseContents(doc, contents) {
  16273. const comments = {
  16274. before: [],
  16275. after: []
  16276. };
  16277. let body = undefined;
  16278. let spaceBefore = false;
  16279. for (const node of contents) {
  16280. if (node.valueRange) {
  16281. if (body !== undefined) {
  16282. const msg = 'Document contains trailing content not separated by a ... or --- line';
  16283. doc.errors.push(new PlainValue$1.YAMLSyntaxError(node, msg));
  16284. break;
  16285. }
  16286. const res = resolveSeq.resolveNode(doc, node);
  16287. if (spaceBefore) {
  16288. res.spaceBefore = true;
  16289. spaceBefore = false;
  16290. }
  16291. body = res;
  16292. } else if (node.comment !== null) {
  16293. const cc = body === undefined ? comments.before : comments.after;
  16294. cc.push(node.comment);
  16295. } else if (node.type === PlainValue$1.Type.BLANK_LINE) {
  16296. spaceBefore = true;
  16297. if (body === undefined && comments.before.length > 0 && !doc.commentBefore) {
  16298. // space-separated comments at start are parsed as document comments
  16299. doc.commentBefore = comments.before.join('\n');
  16300. comments.before = [];
  16301. }
  16302. }
  16303. }
  16304. doc.contents = body || null;
  16305. if (!body) {
  16306. doc.comment = comments.before.concat(comments.after).join('\n') || null;
  16307. } else {
  16308. const cb = comments.before.join('\n');
  16309. if (cb) {
  16310. const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body;
  16311. cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb;
  16312. }
  16313. doc.comment = comments.after.join('\n') || null;
  16314. }
  16315. }
  16316. function resolveTagDirective({
  16317. tagPrefixes
  16318. }, directive) {
  16319. const [handle, prefix] = directive.parameters;
  16320. if (!handle || !prefix) {
  16321. const msg = 'Insufficient parameters given for %TAG directive';
  16322. throw new PlainValue$1.YAMLSemanticError(directive, msg);
  16323. }
  16324. if (tagPrefixes.some(p => p.handle === handle)) {
  16325. const msg = 'The %TAG directive must only be given at most once per handle in the same document.';
  16326. throw new PlainValue$1.YAMLSemanticError(directive, msg);
  16327. }
  16328. return {
  16329. handle,
  16330. prefix
  16331. };
  16332. }
  16333. function resolveYamlDirective(doc, directive) {
  16334. let [version] = directive.parameters;
  16335. if (directive.name === 'YAML:1.0') version = '1.0';
  16336. if (!version) {
  16337. const msg = 'Insufficient parameters given for %YAML directive';
  16338. throw new PlainValue$1.YAMLSemanticError(directive, msg);
  16339. }
  16340. if (!documentOptions[version]) {
  16341. const v0 = doc.version || doc.options.version;
  16342. const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`;
  16343. doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg));
  16344. }
  16345. return version;
  16346. }
  16347. function parseDirectives(doc, directives, prevDoc) {
  16348. const directiveComments = [];
  16349. let hasDirectives = false;
  16350. for (const directive of directives) {
  16351. const {
  16352. comment,
  16353. name
  16354. } = directive;
  16355. switch (name) {
  16356. case 'TAG':
  16357. try {
  16358. doc.tagPrefixes.push(resolveTagDirective(doc, directive));
  16359. } catch (error) {
  16360. doc.errors.push(error);
  16361. }
  16362. hasDirectives = true;
  16363. break;
  16364. case 'YAML':
  16365. case 'YAML:1.0':
  16366. if (doc.version) {
  16367. const msg = 'The %YAML directive must only be given at most once per document.';
  16368. doc.errors.push(new PlainValue$1.YAMLSemanticError(directive, msg));
  16369. }
  16370. try {
  16371. doc.version = resolveYamlDirective(doc, directive);
  16372. } catch (error) {
  16373. doc.errors.push(error);
  16374. }
  16375. hasDirectives = true;
  16376. break;
  16377. default:
  16378. if (name) {
  16379. const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`;
  16380. doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg));
  16381. }
  16382. }
  16383. if (comment) directiveComments.push(comment);
  16384. }
  16385. if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) {
  16386. const copyTagPrefix = ({
  16387. handle,
  16388. prefix
  16389. }) => ({
  16390. handle,
  16391. prefix
  16392. });
  16393. doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix);
  16394. doc.version = prevDoc.version;
  16395. }
  16396. doc.commentBefore = directiveComments.join('\n') || null;
  16397. }
  16398. function assertCollection(contents) {
  16399. if (contents instanceof resolveSeq.Collection) return true;
  16400. throw new Error('Expected a YAML collection as document contents');
  16401. }
  16402. class Document$2 {
  16403. constructor(options) {
  16404. this.anchors = new Anchors(options.anchorPrefix);
  16405. this.commentBefore = null;
  16406. this.comment = null;
  16407. this.contents = null;
  16408. this.directivesEndMarker = null;
  16409. this.errors = [];
  16410. this.options = options;
  16411. this.schema = null;
  16412. this.tagPrefixes = [];
  16413. this.version = null;
  16414. this.warnings = [];
  16415. }
  16416. add(value) {
  16417. assertCollection(this.contents);
  16418. return this.contents.add(value);
  16419. }
  16420. addIn(path, value) {
  16421. assertCollection(this.contents);
  16422. this.contents.addIn(path, value);
  16423. }
  16424. delete(key) {
  16425. assertCollection(this.contents);
  16426. return this.contents.delete(key);
  16427. }
  16428. deleteIn(path) {
  16429. if (resolveSeq.isEmptyPath(path)) {
  16430. if (this.contents == null) return false;
  16431. this.contents = null;
  16432. return true;
  16433. }
  16434. assertCollection(this.contents);
  16435. return this.contents.deleteIn(path);
  16436. }
  16437. getDefaults() {
  16438. return Document$2.defaults[this.version] || Document$2.defaults[this.options.version] || {};
  16439. }
  16440. get(key, keepScalar) {
  16441. return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined;
  16442. }
  16443. getIn(path, keepScalar) {
  16444. if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents;
  16445. return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined;
  16446. }
  16447. has(key) {
  16448. return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false;
  16449. }
  16450. hasIn(path) {
  16451. if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined;
  16452. return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false;
  16453. }
  16454. set(key, value) {
  16455. assertCollection(this.contents);
  16456. this.contents.set(key, value);
  16457. }
  16458. setIn(path, value) {
  16459. if (resolveSeq.isEmptyPath(path)) this.contents = value;else {
  16460. assertCollection(this.contents);
  16461. this.contents.setIn(path, value);
  16462. }
  16463. }
  16464. setSchema(id, customTags) {
  16465. if (!id && !customTags && this.schema) return;
  16466. if (typeof id === 'number') id = id.toFixed(1);
  16467. if (id === '1.0' || id === '1.1' || id === '1.2') {
  16468. if (this.version) this.version = id;else this.options.version = id;
  16469. delete this.options.schema;
  16470. } else if (id && typeof id === 'string') {
  16471. this.options.schema = id;
  16472. }
  16473. if (Array.isArray(customTags)) this.options.customTags = customTags;
  16474. const opt = Object.assign({}, this.getDefaults(), this.options);
  16475. this.schema = new Schema$1.Schema(opt);
  16476. }
  16477. parse(node, prevDoc) {
  16478. if (this.options.keepCstNodes) this.cstNode = node;
  16479. if (this.options.keepNodeTypes) this.type = 'DOCUMENT';
  16480. const {
  16481. directives = [],
  16482. contents = [],
  16483. directivesEndMarker,
  16484. error,
  16485. valueRange
  16486. } = node;
  16487. if (error) {
  16488. if (!error.source) error.source = this;
  16489. this.errors.push(error);
  16490. }
  16491. parseDirectives(this, directives, prevDoc);
  16492. if (directivesEndMarker) this.directivesEndMarker = true;
  16493. this.range = valueRange ? [valueRange.start, valueRange.end] : null;
  16494. this.setSchema();
  16495. this.anchors._cstAliases = [];
  16496. parseContents(this, contents);
  16497. this.anchors.resolveNodes();
  16498. if (this.options.prettyErrors) {
  16499. for (const error of this.errors) if (error instanceof PlainValue$1.YAMLError) error.makePretty();
  16500. for (const warn of this.warnings) if (warn instanceof PlainValue$1.YAMLError) warn.makePretty();
  16501. }
  16502. return this;
  16503. }
  16504. listNonDefaultTags() {
  16505. return listTagNames(this.contents).filter(t => t.indexOf(Schema$1.Schema.defaultPrefix) !== 0);
  16506. }
  16507. setTagPrefix(handle, prefix) {
  16508. if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !');
  16509. if (prefix) {
  16510. const prev = this.tagPrefixes.find(p => p.handle === handle);
  16511. if (prev) prev.prefix = prefix;else this.tagPrefixes.push({
  16512. handle,
  16513. prefix
  16514. });
  16515. } else {
  16516. this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle);
  16517. }
  16518. }
  16519. toJSON(arg, onAnchor) {
  16520. const {
  16521. keepBlobsInJSON,
  16522. mapAsMap,
  16523. maxAliasCount
  16524. } = this.options;
  16525. const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar));
  16526. const ctx = {
  16527. doc: this,
  16528. indentStep: ' ',
  16529. keep,
  16530. mapAsMap: keep && !!mapAsMap,
  16531. maxAliasCount,
  16532. stringify: stringify$2 // Requiring directly in Pair would create circular dependencies
  16533. };
  16534. const anchorNames = Object.keys(this.anchors.map);
  16535. if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], {
  16536. alias: [],
  16537. aliasCount: 0,
  16538. count: 1
  16539. }]));
  16540. const res = resolveSeq.toJSON(this.contents, arg, ctx);
  16541. if (typeof onAnchor === 'function' && ctx.anchors) for (const {
  16542. count,
  16543. res
  16544. } of ctx.anchors.values()) onAnchor(res, count);
  16545. return res;
  16546. }
  16547. toString() {
  16548. if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified');
  16549. const indentSize = this.options.indent;
  16550. if (!Number.isInteger(indentSize) || indentSize <= 0) {
  16551. const s = JSON.stringify(indentSize);
  16552. throw new Error(`"indent" option must be a positive integer, not ${s}`);
  16553. }
  16554. this.setSchema();
  16555. const lines = [];
  16556. let hasDirectives = false;
  16557. if (this.version) {
  16558. let vd = '%YAML 1.2';
  16559. if (this.schema.name === 'yaml-1.1') {
  16560. if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1';
  16561. }
  16562. lines.push(vd);
  16563. hasDirectives = true;
  16564. }
  16565. const tagNames = this.listNonDefaultTags();
  16566. this.tagPrefixes.forEach(({
  16567. handle,
  16568. prefix
  16569. }) => {
  16570. if (tagNames.some(t => t.indexOf(prefix) === 0)) {
  16571. lines.push(`%TAG ${handle} ${prefix}`);
  16572. hasDirectives = true;
  16573. }
  16574. });
  16575. if (hasDirectives || this.directivesEndMarker) lines.push('---');
  16576. if (this.commentBefore) {
  16577. if (hasDirectives || !this.directivesEndMarker) lines.unshift('');
  16578. lines.unshift(this.commentBefore.replace(/^/gm, '#'));
  16579. }
  16580. const ctx = {
  16581. anchors: Object.create(null),
  16582. doc: this,
  16583. indent: '',
  16584. indentStep: ' '.repeat(indentSize),
  16585. stringify: stringify$2 // Requiring directly in nodes would create circular dependencies
  16586. };
  16587. let chompKeep = false;
  16588. let contentComment = null;
  16589. if (this.contents) {
  16590. if (this.contents instanceof resolveSeq.Node) {
  16591. if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push('');
  16592. if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment
  16593. ctx.forceBlockIndent = !!this.comment;
  16594. contentComment = this.contents.comment;
  16595. }
  16596. const onChompKeep = contentComment ? null : () => chompKeep = true;
  16597. const body = stringify$2(this.contents, ctx, () => contentComment = null, onChompKeep);
  16598. lines.push(resolveSeq.addComment(body, '', contentComment));
  16599. } else if (this.contents !== undefined) {
  16600. lines.push(stringify$2(this.contents, ctx));
  16601. }
  16602. if (this.comment) {
  16603. if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push('');
  16604. lines.push(this.comment.replace(/^/gm, '#'));
  16605. }
  16606. return lines.join('\n') + '\n';
  16607. }
  16608. }
  16609. PlainValue$1._defineProperty(Document$2, "defaults", documentOptions);
  16610. Document9b4560a1.Document = Document$2;
  16611. Document9b4560a1.defaultOptions = defaultOptions$1;
  16612. Document9b4560a1.scalarOptions = scalarOptions;
  16613. var parseCst = parseCst$1;
  16614. var Document$1 = Document9b4560a1;
  16615. var Schema = Schema88e323a7;
  16616. var PlainValue = PlainValueEc8e588e;
  16617. var warnings = warnings1000a372;
  16618. function createNode(value, wrapScalars = true, tag) {
  16619. if (tag === undefined && typeof wrapScalars === 'string') {
  16620. tag = wrapScalars;
  16621. wrapScalars = true;
  16622. }
  16623. const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions);
  16624. const schema = new Schema.Schema(options);
  16625. return schema.createNode(value, wrapScalars, tag);
  16626. }
  16627. class Document extends Document$1.Document {
  16628. constructor(options) {
  16629. super(Object.assign({}, Document$1.defaultOptions, options));
  16630. }
  16631. }
  16632. function parseAllDocuments(src, options) {
  16633. const stream = [];
  16634. let prev;
  16635. for (const cstDoc of parseCst.parse(src)) {
  16636. const doc = new Document(options);
  16637. doc.parse(cstDoc, prev);
  16638. stream.push(doc);
  16639. prev = doc;
  16640. }
  16641. return stream;
  16642. }
  16643. function parseDocument(src, options) {
  16644. const cst = parseCst.parse(src);
  16645. const doc = new Document(options).parse(cst[0]);
  16646. if (cst.length > 1) {
  16647. const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()';
  16648. doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg));
  16649. }
  16650. return doc;
  16651. }
  16652. function parse$f(src, options) {
  16653. const doc = parseDocument(src, options);
  16654. doc.warnings.forEach(warning => warnings.warn(warning));
  16655. if (doc.errors.length > 0) throw doc.errors[0];
  16656. return doc.toJSON();
  16657. }
  16658. function stringify$1(value, options) {
  16659. const doc = new Document(options);
  16660. doc.contents = value;
  16661. return String(doc);
  16662. }
  16663. const YAML = {
  16664. createNode,
  16665. defaultOptions: Document$1.defaultOptions,
  16666. Document,
  16667. parse: parse$f,
  16668. parseAllDocuments,
  16669. parseCST: parseCst.parse,
  16670. parseDocument,
  16671. scalarOptions: Document$1.scalarOptions,
  16672. stringify: stringify$1
  16673. };
  16674. dist$2.YAML = YAML;
  16675. var yaml$1 = dist$2.YAML;
  16676. var importCwd = {exports: {}};
  16677. var importFrom$1 = {exports: {}};
  16678. var resolveFrom$2 = {exports: {}};
  16679. const path$l = path__default;
  16680. const Module = require$$0__default$5;
  16681. const fs$m = fs__default;
  16682. const resolveFrom$1 = (fromDirectory, moduleId, silent) => {
  16683. if (typeof fromDirectory !== 'string') {
  16684. throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``);
  16685. }
  16686. if (typeof moduleId !== 'string') {
  16687. throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
  16688. }
  16689. try {
  16690. fromDirectory = fs$m.realpathSync(fromDirectory);
  16691. } catch (error) {
  16692. if (error.code === 'ENOENT') {
  16693. fromDirectory = path$l.resolve(fromDirectory);
  16694. } else if (silent) {
  16695. return;
  16696. } else {
  16697. throw error;
  16698. }
  16699. }
  16700. const fromFile = path$l.join(fromDirectory, 'noop.js');
  16701. const resolveFileName = () => Module._resolveFilename(moduleId, {
  16702. id: fromFile,
  16703. filename: fromFile,
  16704. paths: Module._nodeModulePaths(fromDirectory)
  16705. });
  16706. if (silent) {
  16707. try {
  16708. return resolveFileName();
  16709. } catch (error) {
  16710. return;
  16711. }
  16712. }
  16713. return resolveFileName();
  16714. };
  16715. resolveFrom$2.exports = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId);
  16716. resolveFrom$2.exports.silent = (fromDirectory, moduleId) => resolveFrom$1(fromDirectory, moduleId, true);
  16717. const resolveFrom = resolveFrom$2.exports;
  16718. importFrom$1.exports = (fromDirectory, moduleId) => eval('require')(resolveFrom(fromDirectory, moduleId));
  16719. importFrom$1.exports.silent = (fromDirectory, moduleId) => {
  16720. try {
  16721. return eval('require')(resolveFrom(fromDirectory, moduleId));
  16722. } catch (_) {}
  16723. };
  16724. const importFrom = importFrom$1.exports;
  16725. importCwd.exports = moduleId => importFrom(process.cwd(), moduleId);
  16726. importCwd.exports.silent = moduleId => importFrom.silent(process.cwd(), moduleId);
  16727. const req$1 = importCwd.exports;
  16728. /**
  16729. * Load Options
  16730. *
  16731. * @private
  16732. * @method options
  16733. *
  16734. * @param {Object} config PostCSS Config
  16735. *
  16736. * @return {Object} options PostCSS Options
  16737. */
  16738. const options = (config, file) => {
  16739. if (config.parser && typeof config.parser === 'string') {
  16740. try {
  16741. config.parser = req$1(config.parser);
  16742. } catch (err) {
  16743. throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`)
  16744. }
  16745. }
  16746. if (config.syntax && typeof config.syntax === 'string') {
  16747. try {
  16748. config.syntax = req$1(config.syntax);
  16749. } catch (err) {
  16750. throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`)
  16751. }
  16752. }
  16753. if (config.stringifier && typeof config.stringifier === 'string') {
  16754. try {
  16755. config.stringifier = req$1(config.stringifier);
  16756. } catch (err) {
  16757. throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`)
  16758. }
  16759. }
  16760. if (config.plugins) {
  16761. delete config.plugins;
  16762. }
  16763. return config
  16764. };
  16765. var options_1 = options;
  16766. const req = importCwd.exports;
  16767. /**
  16768. * Plugin Loader
  16769. *
  16770. * @private
  16771. * @method load
  16772. *
  16773. * @param {String} plugin PostCSS Plugin Name
  16774. * @param {Object} options PostCSS Plugin Options
  16775. *
  16776. * @return {Function} PostCSS Plugin
  16777. */
  16778. const load$1 = (plugin, options, file) => {
  16779. try {
  16780. if (
  16781. options === null ||
  16782. options === undefined ||
  16783. Object.keys(options).length === 0
  16784. ) {
  16785. return req(plugin)
  16786. } else {
  16787. return req(plugin)(options)
  16788. }
  16789. } catch (err) {
  16790. throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`)
  16791. }
  16792. };
  16793. /**
  16794. * Load Plugins
  16795. *
  16796. * @private
  16797. * @method plugins
  16798. *
  16799. * @param {Object} config PostCSS Config Plugins
  16800. *
  16801. * @return {Array} plugins PostCSS Plugins
  16802. */
  16803. const plugins = (config, file) => {
  16804. let plugins = [];
  16805. if (Array.isArray(config.plugins)) {
  16806. plugins = config.plugins.filter(Boolean);
  16807. } else {
  16808. plugins = Object.keys(config.plugins)
  16809. .filter((plugin) => {
  16810. return config.plugins[plugin] !== false ? plugin : ''
  16811. })
  16812. .map((plugin) => {
  16813. return load$1(plugin, config.plugins[plugin], file)
  16814. });
  16815. }
  16816. if (plugins.length && plugins.length > 0) {
  16817. plugins.forEach((plugin, i) => {
  16818. if (plugin.default) {
  16819. plugin = plugin.default;
  16820. }
  16821. if (plugin.postcss === true) {
  16822. plugin = plugin();
  16823. } else if (plugin.postcss) {
  16824. plugin = plugin.postcss;
  16825. }
  16826. if (
  16827. // eslint-disable-next-line
  16828. !(
  16829. (typeof plugin === 'object' && Array.isArray(plugin.plugins)) ||
  16830. (typeof plugin === 'object' && plugin.postcssPlugin) ||
  16831. (typeof plugin === 'function')
  16832. )
  16833. ) {
  16834. throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`)
  16835. }
  16836. });
  16837. }
  16838. return plugins
  16839. };
  16840. var plugins_1 = plugins;
  16841. var dist$1 = {};
  16842. var sourceMapSupport = {exports: {}};
  16843. var sourceMap = {};
  16844. var sourceMapConsumer$1 = {};
  16845. var util$9 = {};
  16846. /* -*- Mode: js; js-indent-level: 2; -*- */
  16847. (function (exports) {
  16848. /*
  16849. * Copyright 2011 Mozilla Foundation and contributors
  16850. * Licensed under the New BSD license. See LICENSE or:
  16851. * http://opensource.org/licenses/BSD-3-Clause
  16852. */
  16853. /**
  16854. * This is a helper function for getting values from parameter/options
  16855. * objects.
  16856. *
  16857. * @param args The object we are extracting values from
  16858. * @param name The name of the property we are getting.
  16859. * @param defaultValue An optional value to return if the property is missing
  16860. * from the object. If this is not specified and the property is missing, an
  16861. * error will be thrown.
  16862. */
  16863. function getArg(aArgs, aName, aDefaultValue) {
  16864. if (aName in aArgs) {
  16865. return aArgs[aName];
  16866. } else if (arguments.length === 3) {
  16867. return aDefaultValue;
  16868. }
  16869. throw new Error('"' + aName + '" is a required argument.');
  16870. }
  16871. exports.getArg = getArg;
  16872. const urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  16873. const dataUrlRegexp = /^data:.+\,.+$/;
  16874. function urlParse(aUrl) {
  16875. const match = aUrl.match(urlRegexp);
  16876. if (!match) {
  16877. return null;
  16878. }
  16879. return {
  16880. scheme: match[1],
  16881. auth: match[2],
  16882. host: match[3],
  16883. port: match[4],
  16884. path: match[5]
  16885. };
  16886. }
  16887. exports.urlParse = urlParse;
  16888. function urlGenerate(aParsedUrl) {
  16889. let url = "";
  16890. if (aParsedUrl.scheme) {
  16891. url += aParsedUrl.scheme + ":";
  16892. }
  16893. url += "//";
  16894. if (aParsedUrl.auth) {
  16895. url += aParsedUrl.auth + "@";
  16896. }
  16897. if (aParsedUrl.host) {
  16898. url += aParsedUrl.host;
  16899. }
  16900. if (aParsedUrl.port) {
  16901. url += ":" + aParsedUrl.port;
  16902. }
  16903. if (aParsedUrl.path) {
  16904. url += aParsedUrl.path;
  16905. }
  16906. return url;
  16907. }
  16908. exports.urlGenerate = urlGenerate;
  16909. const MAX_CACHED_INPUTS = 32;
  16910. /**
  16911. * Takes some function `f(input) -> result` and returns a memoized version of
  16912. * `f`.
  16913. *
  16914. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  16915. * memoization is a dumb-simple, linear least-recently-used cache.
  16916. */
  16917. function lruMemoize(f) {
  16918. const cache = [];
  16919. return function(input) {
  16920. for (let i = 0; i < cache.length; i++) {
  16921. if (cache[i].input === input) {
  16922. const temp = cache[0];
  16923. cache[0] = cache[i];
  16924. cache[i] = temp;
  16925. return cache[0].result;
  16926. }
  16927. }
  16928. const result = f(input);
  16929. cache.unshift({
  16930. input,
  16931. result,
  16932. });
  16933. if (cache.length > MAX_CACHED_INPUTS) {
  16934. cache.pop();
  16935. }
  16936. return result;
  16937. };
  16938. }
  16939. /**
  16940. * Normalizes a path, or the path portion of a URL:
  16941. *
  16942. * - Replaces consecutive slashes with one slash.
  16943. * - Removes unnecessary '.' parts.
  16944. * - Removes unnecessary '<dir>/..' parts.
  16945. *
  16946. * Based on code in the Node.js 'path' core module.
  16947. *
  16948. * @param aPath The path or url to normalize.
  16949. */
  16950. const normalize = lruMemoize(function normalize(aPath) {
  16951. let path = aPath;
  16952. const url = urlParse(aPath);
  16953. if (url) {
  16954. if (!url.path) {
  16955. return aPath;
  16956. }
  16957. path = url.path;
  16958. }
  16959. const isAbsolute = exports.isAbsolute(path);
  16960. // Split the path into parts between `/` characters. This is much faster than
  16961. // using `.split(/\/+/g)`.
  16962. const parts = [];
  16963. let start = 0;
  16964. let i = 0;
  16965. while (true) {
  16966. start = i;
  16967. i = path.indexOf("/", start);
  16968. if (i === -1) {
  16969. parts.push(path.slice(start));
  16970. break;
  16971. } else {
  16972. parts.push(path.slice(start, i));
  16973. while (i < path.length && path[i] === "/") {
  16974. i++;
  16975. }
  16976. }
  16977. }
  16978. let up = 0;
  16979. for (i = parts.length - 1; i >= 0; i--) {
  16980. const part = parts[i];
  16981. if (part === ".") {
  16982. parts.splice(i, 1);
  16983. } else if (part === "..") {
  16984. up++;
  16985. } else if (up > 0) {
  16986. if (part === "") {
  16987. // The first part is blank if the path is absolute. Trying to go
  16988. // above the root is a no-op. Therefore we can remove all '..' parts
  16989. // directly after the root.
  16990. parts.splice(i + 1, up);
  16991. up = 0;
  16992. } else {
  16993. parts.splice(i, 2);
  16994. up--;
  16995. }
  16996. }
  16997. }
  16998. path = parts.join("/");
  16999. if (path === "") {
  17000. path = isAbsolute ? "/" : ".";
  17001. }
  17002. if (url) {
  17003. url.path = path;
  17004. return urlGenerate(url);
  17005. }
  17006. return path;
  17007. });
  17008. exports.normalize = normalize;
  17009. /**
  17010. * Joins two paths/URLs.
  17011. *
  17012. * @param aRoot The root path or URL.
  17013. * @param aPath The path or URL to be joined with the root.
  17014. *
  17015. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  17016. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  17017. * first.
  17018. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  17019. * is updated with the result and aRoot is returned. Otherwise the result
  17020. * is returned.
  17021. * - If aPath is absolute, the result is aPath.
  17022. * - Otherwise the two paths are joined with a slash.
  17023. * - Joining for example 'http://' and 'www.example.com' is also supported.
  17024. */
  17025. function join(aRoot, aPath) {
  17026. if (aRoot === "") {
  17027. aRoot = ".";
  17028. }
  17029. if (aPath === "") {
  17030. aPath = ".";
  17031. }
  17032. const aPathUrl = urlParse(aPath);
  17033. const aRootUrl = urlParse(aRoot);
  17034. if (aRootUrl) {
  17035. aRoot = aRootUrl.path || "/";
  17036. }
  17037. // `join(foo, '//www.example.org')`
  17038. if (aPathUrl && !aPathUrl.scheme) {
  17039. if (aRootUrl) {
  17040. aPathUrl.scheme = aRootUrl.scheme;
  17041. }
  17042. return urlGenerate(aPathUrl);
  17043. }
  17044. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  17045. return aPath;
  17046. }
  17047. // `join('http://', 'www.example.com')`
  17048. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  17049. aRootUrl.host = aPath;
  17050. return urlGenerate(aRootUrl);
  17051. }
  17052. const joined = aPath.charAt(0) === "/"
  17053. ? aPath
  17054. : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath);
  17055. if (aRootUrl) {
  17056. aRootUrl.path = joined;
  17057. return urlGenerate(aRootUrl);
  17058. }
  17059. return joined;
  17060. }
  17061. exports.join = join;
  17062. exports.isAbsolute = function(aPath) {
  17063. return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
  17064. };
  17065. /**
  17066. * Make a path relative to a URL or another path.
  17067. *
  17068. * @param aRoot The root path or URL.
  17069. * @param aPath The path or URL to be made relative to aRoot.
  17070. */
  17071. function relative(aRoot, aPath) {
  17072. if (aRoot === "") {
  17073. aRoot = ".";
  17074. }
  17075. aRoot = aRoot.replace(/\/$/, "");
  17076. // It is possible for the path to be above the root. In this case, simply
  17077. // checking whether the root is a prefix of the path won't work. Instead, we
  17078. // need to remove components from the root one by one, until either we find
  17079. // a prefix that fits, or we run out of components to remove.
  17080. let level = 0;
  17081. while (aPath.indexOf(aRoot + "/") !== 0) {
  17082. const index = aRoot.lastIndexOf("/");
  17083. if (index < 0) {
  17084. return aPath;
  17085. }
  17086. // If the only part of the root that is left is the scheme (i.e. http://,
  17087. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  17088. // have exhausted all components, so the path is not relative to the root.
  17089. aRoot = aRoot.slice(0, index);
  17090. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  17091. return aPath;
  17092. }
  17093. ++level;
  17094. }
  17095. // Make sure we add a "../" for each component we removed from the root.
  17096. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  17097. }
  17098. exports.relative = relative;
  17099. const supportsNullProto = (function() {
  17100. const obj = Object.create(null);
  17101. return !("__proto__" in obj);
  17102. }());
  17103. function identity(s) {
  17104. return s;
  17105. }
  17106. /**
  17107. * Because behavior goes wacky when you set `__proto__` on objects, we
  17108. * have to prefix all the strings in our set with an arbitrary character.
  17109. *
  17110. * See https://github.com/mozilla/source-map/pull/31 and
  17111. * https://github.com/mozilla/source-map/issues/30
  17112. *
  17113. * @param String aStr
  17114. */
  17115. function toSetString(aStr) {
  17116. if (isProtoString(aStr)) {
  17117. return "$" + aStr;
  17118. }
  17119. return aStr;
  17120. }
  17121. exports.toSetString = supportsNullProto ? identity : toSetString;
  17122. function fromSetString(aStr) {
  17123. if (isProtoString(aStr)) {
  17124. return aStr.slice(1);
  17125. }
  17126. return aStr;
  17127. }
  17128. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  17129. function isProtoString(s) {
  17130. if (!s) {
  17131. return false;
  17132. }
  17133. const length = s.length;
  17134. if (length < 9 /* "__proto__".length */) {
  17135. return false;
  17136. }
  17137. /* eslint-disable no-multi-spaces */
  17138. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  17139. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  17140. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  17141. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  17142. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  17143. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  17144. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  17145. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  17146. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  17147. return false;
  17148. }
  17149. /* eslint-enable no-multi-spaces */
  17150. for (let i = length - 10; i >= 0; i--) {
  17151. if (s.charCodeAt(i) !== 36 /* '$' */) {
  17152. return false;
  17153. }
  17154. }
  17155. return true;
  17156. }
  17157. /**
  17158. * Comparator between two mappings where the original positions are compared.
  17159. *
  17160. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  17161. * mappings with the same original source/line/column, but different generated
  17162. * line and column the same. Useful when searching for a mapping with a
  17163. * stubbed out mapping.
  17164. */
  17165. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  17166. let cmp = strcmp(mappingA.source, mappingB.source);
  17167. if (cmp !== 0) {
  17168. return cmp;
  17169. }
  17170. cmp = mappingA.originalLine - mappingB.originalLine;
  17171. if (cmp !== 0) {
  17172. return cmp;
  17173. }
  17174. cmp = mappingA.originalColumn - mappingB.originalColumn;
  17175. if (cmp !== 0 || onlyCompareOriginal) {
  17176. return cmp;
  17177. }
  17178. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  17179. if (cmp !== 0) {
  17180. return cmp;
  17181. }
  17182. cmp = mappingA.generatedLine - mappingB.generatedLine;
  17183. if (cmp !== 0) {
  17184. return cmp;
  17185. }
  17186. return strcmp(mappingA.name, mappingB.name);
  17187. }
  17188. exports.compareByOriginalPositions = compareByOriginalPositions;
  17189. /**
  17190. * Comparator between two mappings with deflated source and name indices where
  17191. * the generated positions are compared.
  17192. *
  17193. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  17194. * mappings with the same generated line and column, but different
  17195. * source/name/original line and column the same. Useful when searching for a
  17196. * mapping with a stubbed out mapping.
  17197. */
  17198. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  17199. let cmp = mappingA.generatedLine - mappingB.generatedLine;
  17200. if (cmp !== 0) {
  17201. return cmp;
  17202. }
  17203. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  17204. if (cmp !== 0 || onlyCompareGenerated) {
  17205. return cmp;
  17206. }
  17207. cmp = strcmp(mappingA.source, mappingB.source);
  17208. if (cmp !== 0) {
  17209. return cmp;
  17210. }
  17211. cmp = mappingA.originalLine - mappingB.originalLine;
  17212. if (cmp !== 0) {
  17213. return cmp;
  17214. }
  17215. cmp = mappingA.originalColumn - mappingB.originalColumn;
  17216. if (cmp !== 0) {
  17217. return cmp;
  17218. }
  17219. return strcmp(mappingA.name, mappingB.name);
  17220. }
  17221. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  17222. function strcmp(aStr1, aStr2) {
  17223. if (aStr1 === aStr2) {
  17224. return 0;
  17225. }
  17226. if (aStr1 === null) {
  17227. return 1; // aStr2 !== null
  17228. }
  17229. if (aStr2 === null) {
  17230. return -1; // aStr1 !== null
  17231. }
  17232. if (aStr1 > aStr2) {
  17233. return 1;
  17234. }
  17235. return -1;
  17236. }
  17237. /**
  17238. * Comparator between two mappings with inflated source and name strings where
  17239. * the generated positions are compared.
  17240. */
  17241. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  17242. let cmp = mappingA.generatedLine - mappingB.generatedLine;
  17243. if (cmp !== 0) {
  17244. return cmp;
  17245. }
  17246. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  17247. if (cmp !== 0) {
  17248. return cmp;
  17249. }
  17250. cmp = strcmp(mappingA.source, mappingB.source);
  17251. if (cmp !== 0) {
  17252. return cmp;
  17253. }
  17254. cmp = mappingA.originalLine - mappingB.originalLine;
  17255. if (cmp !== 0) {
  17256. return cmp;
  17257. }
  17258. cmp = mappingA.originalColumn - mappingB.originalColumn;
  17259. if (cmp !== 0) {
  17260. return cmp;
  17261. }
  17262. return strcmp(mappingA.name, mappingB.name);
  17263. }
  17264. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  17265. /**
  17266. * Strip any JSON XSSI avoidance prefix from the string (as documented
  17267. * in the source maps specification), and then parse the string as
  17268. * JSON.
  17269. */
  17270. function parseSourceMapInput(str) {
  17271. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
  17272. }
  17273. exports.parseSourceMapInput = parseSourceMapInput;
  17274. /**
  17275. * Compute the URL of a source given the the source root, the source's
  17276. * URL, and the source map's URL.
  17277. */
  17278. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  17279. sourceURL = sourceURL || "";
  17280. if (sourceRoot) {
  17281. // This follows what Chrome does.
  17282. if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
  17283. sourceRoot += "/";
  17284. }
  17285. // The spec says:
  17286. // Line 4: An optional source root, useful for relocating source
  17287. // files on a server or removing repeated values in the
  17288. // “sources” entry. This value is prepended to the individual
  17289. // entries in the “source” field.
  17290. sourceURL = sourceRoot + sourceURL;
  17291. }
  17292. // Historically, SourceMapConsumer did not take the sourceMapURL as
  17293. // a parameter. This mode is still somewhat supported, which is why
  17294. // this code block is conditional. However, it's preferable to pass
  17295. // the source map URL to SourceMapConsumer, so that this function
  17296. // can implement the source URL resolution algorithm as outlined in
  17297. // the spec. This block is basically the equivalent of:
  17298. // new URL(sourceURL, sourceMapURL).toString()
  17299. // ... except it avoids using URL, which wasn't available in the
  17300. // older releases of node still supported by this library.
  17301. //
  17302. // The spec says:
  17303. // If the sources are not absolute URLs after prepending of the
  17304. // “sourceRoot”, the sources are resolved relative to the
  17305. // SourceMap (like resolving script src in a html document).
  17306. if (sourceMapURL) {
  17307. const parsed = urlParse(sourceMapURL);
  17308. if (!parsed) {
  17309. throw new Error("sourceMapURL could not be parsed");
  17310. }
  17311. if (parsed.path) {
  17312. // Strip the last path component, but keep the "/".
  17313. const index = parsed.path.lastIndexOf("/");
  17314. if (index >= 0) {
  17315. parsed.path = parsed.path.substring(0, index + 1);
  17316. }
  17317. }
  17318. sourceURL = join(urlGenerate(parsed), sourceURL);
  17319. }
  17320. return normalize(sourceURL);
  17321. }
  17322. exports.computeSourceURL = computeSourceURL;
  17323. }(util$9));
  17324. var binarySearch$3 = {};
  17325. /* -*- Mode: js; js-indent-level: 2; -*- */
  17326. (function (exports) {
  17327. /*
  17328. * Copyright 2011 Mozilla Foundation and contributors
  17329. * Licensed under the New BSD license. See LICENSE or:
  17330. * http://opensource.org/licenses/BSD-3-Clause
  17331. */
  17332. exports.GREATEST_LOWER_BOUND = 1;
  17333. exports.LEAST_UPPER_BOUND = 2;
  17334. /**
  17335. * Recursive implementation of binary search.
  17336. *
  17337. * @param aLow Indices here and lower do not contain the needle.
  17338. * @param aHigh Indices here and higher do not contain the needle.
  17339. * @param aNeedle The element being searched for.
  17340. * @param aHaystack The non-empty array being searched.
  17341. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  17342. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  17343. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  17344. * closest element that is smaller than or greater than the one we are
  17345. * searching for, respectively, if the exact element cannot be found.
  17346. */
  17347. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  17348. // This function terminates when one of the following is true:
  17349. //
  17350. // 1. We find the exact element we are looking for.
  17351. //
  17352. // 2. We did not find the exact element, but we can return the index of
  17353. // the next-closest element.
  17354. //
  17355. // 3. We did not find the exact element, and there is no next-closest
  17356. // element than the one we are searching for, so we return -1.
  17357. const mid = Math.floor((aHigh - aLow) / 2) + aLow;
  17358. const cmp = aCompare(aNeedle, aHaystack[mid], true);
  17359. if (cmp === 0) {
  17360. // Found the element we are looking for.
  17361. return mid;
  17362. } else if (cmp > 0) {
  17363. // Our needle is greater than aHaystack[mid].
  17364. if (aHigh - mid > 1) {
  17365. // The element is in the upper half.
  17366. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  17367. }
  17368. // The exact needle element was not found in this haystack. Determine if
  17369. // we are in termination case (3) or (2) and return the appropriate thing.
  17370. if (aBias == exports.LEAST_UPPER_BOUND) {
  17371. return aHigh < aHaystack.length ? aHigh : -1;
  17372. }
  17373. return mid;
  17374. }
  17375. // Our needle is less than aHaystack[mid].
  17376. if (mid - aLow > 1) {
  17377. // The element is in the lower half.
  17378. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  17379. }
  17380. // we are in termination case (3) or (2) and return the appropriate thing.
  17381. if (aBias == exports.LEAST_UPPER_BOUND) {
  17382. return mid;
  17383. }
  17384. return aLow < 0 ? -1 : aLow;
  17385. }
  17386. /**
  17387. * This is an implementation of binary search which will always try and return
  17388. * the index of the closest element if there is no exact hit. This is because
  17389. * mappings between original and generated line/col pairs are single points,
  17390. * and there is an implicit region between each of them, so a miss just means
  17391. * that you aren't on the very start of a region.
  17392. *
  17393. * @param aNeedle The element you are looking for.
  17394. * @param aHaystack The array that is being searched.
  17395. * @param aCompare A function which takes the needle and an element in the
  17396. * array and returns -1, 0, or 1 depending on whether the needle is less
  17397. * than, equal to, or greater than the element, respectively.
  17398. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  17399. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  17400. * closest element that is smaller than or greater than the one we are
  17401. * searching for, respectively, if the exact element cannot be found.
  17402. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  17403. */
  17404. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  17405. if (aHaystack.length === 0) {
  17406. return -1;
  17407. }
  17408. let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  17409. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  17410. if (index < 0) {
  17411. return -1;
  17412. }
  17413. // We have found either the exact element, or the next-closest element than
  17414. // the one we are searching for. However, there may be more than one such
  17415. // element. Make sure we always return the smallest of these.
  17416. while (index - 1 >= 0) {
  17417. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  17418. break;
  17419. }
  17420. --index;
  17421. }
  17422. return index;
  17423. };
  17424. }(binarySearch$3));
  17425. var arraySet$1 = {};
  17426. /* -*- Mode: js; js-indent-level: 2; -*- */
  17427. /*
  17428. * Copyright 2011 Mozilla Foundation and contributors
  17429. * Licensed under the New BSD license. See LICENSE or:
  17430. * http://opensource.org/licenses/BSD-3-Clause
  17431. */
  17432. /**
  17433. * A data structure which is a combination of an array and a set. Adding a new
  17434. * member is O(1), testing for membership is O(1), and finding the index of an
  17435. * element is O(1). Removing elements from the set is not supported. Only
  17436. * strings are supported for membership.
  17437. */
  17438. class ArraySet$4 {
  17439. constructor() {
  17440. this._array = [];
  17441. this._set = new Map();
  17442. }
  17443. /**
  17444. * Static method for creating ArraySet instances from an existing array.
  17445. */
  17446. static fromArray(aArray, aAllowDuplicates) {
  17447. const set = new ArraySet$4();
  17448. for (let i = 0, len = aArray.length; i < len; i++) {
  17449. set.add(aArray[i], aAllowDuplicates);
  17450. }
  17451. return set;
  17452. }
  17453. /**
  17454. * Return how many unique items are in this ArraySet. If duplicates have been
  17455. * added, than those do not count towards the size.
  17456. *
  17457. * @returns Number
  17458. */
  17459. size() {
  17460. return this._set.size;
  17461. }
  17462. /**
  17463. * Add the given string to this set.
  17464. *
  17465. * @param String aStr
  17466. */
  17467. add(aStr, aAllowDuplicates) {
  17468. const isDuplicate = this.has(aStr);
  17469. const idx = this._array.length;
  17470. if (!isDuplicate || aAllowDuplicates) {
  17471. this._array.push(aStr);
  17472. }
  17473. if (!isDuplicate) {
  17474. this._set.set(aStr, idx);
  17475. }
  17476. }
  17477. /**
  17478. * Is the given string a member of this set?
  17479. *
  17480. * @param String aStr
  17481. */
  17482. has(aStr) {
  17483. return this._set.has(aStr);
  17484. }
  17485. /**
  17486. * What is the index of the given string in the array?
  17487. *
  17488. * @param String aStr
  17489. */
  17490. indexOf(aStr) {
  17491. const idx = this._set.get(aStr);
  17492. if (idx >= 0) {
  17493. return idx;
  17494. }
  17495. throw new Error('"' + aStr + '" is not in the set.');
  17496. }
  17497. /**
  17498. * What is the element at the given index?
  17499. *
  17500. * @param Number aIdx
  17501. */
  17502. at(aIdx) {
  17503. if (aIdx >= 0 && aIdx < this._array.length) {
  17504. return this._array[aIdx];
  17505. }
  17506. throw new Error("No element indexed by " + aIdx);
  17507. }
  17508. /**
  17509. * Returns the array representation of this set (which has the proper indices
  17510. * indicated by indexOf). Note that this is a copy of the internal array used
  17511. * for storing the members so that no one can mess with internal state.
  17512. */
  17513. toArray() {
  17514. return this._array.slice();
  17515. }
  17516. }
  17517. arraySet$1.ArraySet = ArraySet$4;
  17518. var readWasm$2 = {exports: {}};
  17519. // Node version of reading a wasm file into an array buffer.
  17520. const fs$l = fs__default;
  17521. const path$k = path__default;
  17522. readWasm$2.exports = function readWasm() {
  17523. return new Promise((resolve, reject) => {
  17524. const wasmPath = path$k.join(__dirname, "mappings.wasm");
  17525. fs$l.readFile(wasmPath, null, (error, data) => {
  17526. if (error) {
  17527. reject(error);
  17528. return;
  17529. }
  17530. resolve(data.buffer);
  17531. });
  17532. });
  17533. };
  17534. readWasm$2.exports.sync = function readWasmSync() {
  17535. const wasmPath = path$k.join(__dirname, "mappings.wasm");
  17536. return fs$l.readFileSync(wasmPath).buffer;
  17537. };
  17538. readWasm$2.exports.initialize = _ => {
  17539. console.debug("SourceMapConsumer.initialize is a no-op when running in node.js");
  17540. };
  17541. var wasm$1 = {exports: {}};
  17542. const readWasm$1 = readWasm$2.exports;
  17543. /**
  17544. * Provide the JIT with a nice shape / hidden class.
  17545. */
  17546. function Mapping$1() {
  17547. this.generatedLine = 0;
  17548. this.generatedColumn = 0;
  17549. this.lastGeneratedColumn = null;
  17550. this.source = null;
  17551. this.originalLine = null;
  17552. this.originalColumn = null;
  17553. this.name = null;
  17554. }
  17555. let cachedWasm = null;
  17556. let cachedWasmSync = null;
  17557. wasm$1.exports = async function wasm() {
  17558. if (cachedWasm) {
  17559. return cachedWasm;
  17560. }
  17561. // At every step of the way, if a sync load already succeeded, abort and return
  17562. // the sync-loaded module.
  17563. cachedWasm = async () => {
  17564. try {
  17565. const callbackStack = [];
  17566. const buffer = await readWasm$1();
  17567. if (cachedWasmSync) return cachedWasmSync;
  17568. const Wasm = await WebAssembly.instantiate(buffer, getImportObject({callbackStack}));
  17569. if (cachedWasmSync) return cachedWasmSync;
  17570. cachedWasmSync = {
  17571. exports: Wasm.instance.exports,
  17572. withMappingCallback: (mappingCallback, f) => {
  17573. callbackStack.push(mappingCallback);
  17574. try {
  17575. f();
  17576. } finally {
  17577. callbackStack.pop();
  17578. }
  17579. }
  17580. };
  17581. } catch (e) {
  17582. if (cachedWasmSync) return cachedWasmSync;
  17583. cachedWasm = null;
  17584. throw e;
  17585. }
  17586. return cachedWasmSync;
  17587. };
  17588. return cachedWasm;
  17589. };
  17590. wasm$1.exports.sync = function wasmSync() {
  17591. if (cachedWasmSync) {
  17592. return cachedWasmSync;
  17593. }
  17594. const callbackStack = [];
  17595. try {
  17596. const cachedWasmBuffer = readWasm$1.sync();
  17597. const wasmModule = new WebAssembly.Module(cachedWasmBuffer);
  17598. const Wasm = new WebAssembly.Instance(wasmModule, getImportObject({callbackStack}));
  17599. cachedWasmSync = {
  17600. exports: Wasm.exports,
  17601. withMappingCallback: (mappingCallback, f) => {
  17602. callbackStack.push(mappingCallback);
  17603. try {
  17604. f();
  17605. } finally {
  17606. callbackStack.pop();
  17607. }
  17608. }
  17609. };
  17610. } catch (e) {
  17611. cachedWasmSync = null;
  17612. throw e;
  17613. }
  17614. return cachedWasmSync;
  17615. };
  17616. function getImportObject({callbackStack}) {
  17617. return {
  17618. env: {
  17619. mapping_callback(
  17620. generatedLine,
  17621. generatedColumn,
  17622. hasLastGeneratedColumn,
  17623. lastGeneratedColumn,
  17624. hasOriginal,
  17625. source,
  17626. originalLine,
  17627. originalColumn,
  17628. hasName,
  17629. name
  17630. ) {
  17631. const mapping = new Mapping$1();
  17632. // JS uses 1-based line numbers, wasm uses 0-based.
  17633. mapping.generatedLine = generatedLine + 1;
  17634. mapping.generatedColumn = generatedColumn;
  17635. if (hasLastGeneratedColumn) {
  17636. // JS uses inclusive last generated column, wasm uses exclusive.
  17637. mapping.lastGeneratedColumn = lastGeneratedColumn - 1;
  17638. }
  17639. if (hasOriginal) {
  17640. mapping.source = source;
  17641. // JS uses 1-based line numbers, wasm uses 0-based.
  17642. mapping.originalLine = originalLine + 1;
  17643. mapping.originalColumn = originalColumn;
  17644. if (hasName) {
  17645. mapping.name = name;
  17646. }
  17647. }
  17648. callbackStack[callbackStack.length - 1](mapping);
  17649. },
  17650. start_all_generated_locations_for() { console.time("all_generated_locations_for"); },
  17651. end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); },
  17652. start_compute_column_spans() { console.time("compute_column_spans"); },
  17653. end_compute_column_spans() { console.timeEnd("compute_column_spans"); },
  17654. start_generated_location_for() { console.time("generated_location_for"); },
  17655. end_generated_location_for() { console.timeEnd("generated_location_for"); },
  17656. start_original_location_for() { console.time("original_location_for"); },
  17657. end_original_location_for() { console.timeEnd("original_location_for"); },
  17658. start_parse_mappings() { console.time("parse_mappings"); },
  17659. end_parse_mappings() { console.timeEnd("parse_mappings"); },
  17660. start_sort_by_generated_location() { console.time("sort_by_generated_location"); },
  17661. end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); },
  17662. start_sort_by_original_location() { console.time("sort_by_original_location"); },
  17663. end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); },
  17664. }
  17665. };
  17666. }
  17667. /* -*- Mode: js; js-indent-level: 2; -*- */
  17668. /*
  17669. * Copyright 2011 Mozilla Foundation and contributors
  17670. * Licensed under the New BSD license. See LICENSE or:
  17671. * http://opensource.org/licenses/BSD-3-Clause
  17672. */
  17673. const util$8 = util$9;
  17674. const binarySearch$2 = binarySearch$3;
  17675. const ArraySet$3 = arraySet$1.ArraySet;
  17676. const readWasm = readWasm$2.exports;
  17677. const wasm = wasm$1.exports;
  17678. const INTERNAL = Symbol("smcInternal");
  17679. class SourceMapConsumer$2 {
  17680. constructor(aSourceMap, aSourceMapURL) {
  17681. if (aSourceMap === INTERNAL) return this;
  17682. return _factory(aSourceMap, aSourceMapURL);
  17683. }
  17684. static initialize(opts) {
  17685. readWasm.initialize(opts["lib/mappings.wasm"]);
  17686. }
  17687. static fromSourceMap(aSourceMap, aSourceMapURL) {
  17688. return _factoryBSM(aSourceMap, aSourceMapURL);
  17689. }
  17690. /**
  17691. * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
  17692. * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async
  17693. * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
  17694. * for `f` to complete, call `destroy` on the consumer, and return `f`'s return
  17695. * value.
  17696. *
  17697. * You must not use the consumer after `f` completes!
  17698. *
  17699. * By using `with`, you do not have to remember to manually call `destroy` on
  17700. * the consumer, since it will be called automatically once `f` completes.
  17701. *
  17702. * ```js
  17703. * const xSquared = await SourceMapConsumer.with(
  17704. * myRawSourceMap,
  17705. * null,
  17706. * async function (consumer) {
  17707. * // Use `consumer` inside here and don't worry about remembering
  17708. * // to call `destroy`.
  17709. *
  17710. * const x = await whatever(consumer);
  17711. * return x * x;
  17712. * }
  17713. * );
  17714. *
  17715. * // You may not use that `consumer` anymore out here; it has
  17716. * // been destroyed. But you can use `xSquared`.
  17717. * console.log(xSquared);
  17718. * ```
  17719. */
  17720. static async with(rawSourceMap, sourceMapUrl, f) {
  17721. // Note: The `acorn` version that `webpack` currently depends on doesn't
  17722. // support `async` functions, and the nodes that we support don't all have
  17723. // `.finally`. Therefore, this is written a bit more convolutedly than it
  17724. // should really be.
  17725. let consumer = null;
  17726. try {
  17727. consumer = new SourceMapConsumer$2(rawSourceMap, sourceMapUrl);
  17728. return await f(consumer);
  17729. } finally {
  17730. if (consumer) {
  17731. consumer.destroy();
  17732. }
  17733. }
  17734. }
  17735. /**
  17736. * Parse the mappings in a string in to a data structure which we can easily
  17737. * query (the ordered arrays in the `this.__generatedMappings` and
  17738. * `this.__originalMappings` properties).
  17739. */
  17740. _parseMappings(aStr, aSourceRoot) {
  17741. throw new Error("Subclasses must implement _parseMappings");
  17742. }
  17743. /**
  17744. * Iterate over each mapping between an original source/line/column and a
  17745. * generated line/column in this source map.
  17746. *
  17747. * @param Function aCallback
  17748. * The function that is called with each mapping.
  17749. * @param Object aContext
  17750. * Optional. If specified, this object will be the value of `this` every
  17751. * time that `aCallback` is called.
  17752. * @param aOrder
  17753. * Either `SourceMapConsumer.GENERATED_ORDER` or
  17754. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  17755. * iterate over the mappings sorted by the generated file's line/column
  17756. * order or the original's source/line/column order, respectively. Defaults to
  17757. * `SourceMapConsumer.GENERATED_ORDER`.
  17758. */
  17759. eachMapping(aCallback, aContext, aOrder) {
  17760. throw new Error("Subclasses must implement eachMapping");
  17761. }
  17762. /**
  17763. * Returns all generated line and column information for the original source,
  17764. * line, and column provided. If no column is provided, returns all mappings
  17765. * corresponding to a either the line we are searching for or the next
  17766. * closest line that has any mappings. Otherwise, returns all mappings
  17767. * corresponding to the given line and either the column we are searching for
  17768. * or the next closest column that has any offsets.
  17769. *
  17770. * The only argument is an object with the following properties:
  17771. *
  17772. * - source: The filename of the original source.
  17773. * - line: The line number in the original source. The line number is 1-based.
  17774. * - column: Optional. the column number in the original source.
  17775. * The column number is 0-based.
  17776. *
  17777. * and an array of objects is returned, each with the following properties:
  17778. *
  17779. * - line: The line number in the generated source, or null. The
  17780. * line number is 1-based.
  17781. * - column: The column number in the generated source, or null.
  17782. * The column number is 0-based.
  17783. */
  17784. allGeneratedPositionsFor(aArgs) {
  17785. throw new Error("Subclasses must implement allGeneratedPositionsFor");
  17786. }
  17787. destroy() {
  17788. throw new Error("Subclasses must implement destroy");
  17789. }
  17790. }
  17791. /**
  17792. * The version of the source mapping spec that we are consuming.
  17793. */
  17794. SourceMapConsumer$2.prototype._version = 3;
  17795. SourceMapConsumer$2.GENERATED_ORDER = 1;
  17796. SourceMapConsumer$2.ORIGINAL_ORDER = 2;
  17797. SourceMapConsumer$2.GREATEST_LOWER_BOUND = 1;
  17798. SourceMapConsumer$2.LEAST_UPPER_BOUND = 2;
  17799. sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer$2;
  17800. /**
  17801. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  17802. * query for information about the original file positions by giving it a file
  17803. * position in the generated source.
  17804. *
  17805. * The first parameter is the raw source map (either as a JSON string, or
  17806. * already parsed to an object). According to the spec, source maps have the
  17807. * following attributes:
  17808. *
  17809. * - version: Which version of the source map spec this map is following.
  17810. * - sources: An array of URLs to the original source files.
  17811. * - names: An array of identifiers which can be referenced by individual mappings.
  17812. * - sourceRoot: Optional. The URL root from which all sources are relative.
  17813. * - sourcesContent: Optional. An array of contents of the original source files.
  17814. * - mappings: A string of base64 VLQs which contain the actual mappings.
  17815. * - file: Optional. The generated file this source map is associated with.
  17816. *
  17817. * Here is an example source map, taken from the source map spec[0]:
  17818. *
  17819. * {
  17820. * version : 3,
  17821. * file: "out.js",
  17822. * sourceRoot : "",
  17823. * sources: ["foo.js", "bar.js"],
  17824. * names: ["src", "maps", "are", "fun"],
  17825. * mappings: "AA,AB;;ABCDE;"
  17826. * }
  17827. *
  17828. * The second parameter, if given, is a string whose value is the URL
  17829. * at which the source map was found. This URL is used to compute the
  17830. * sources array.
  17831. *
  17832. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  17833. */
  17834. class BasicSourceMapConsumer$1 extends SourceMapConsumer$2 {
  17835. constructor(aSourceMap, aSourceMapURL) {
  17836. super(INTERNAL);
  17837. let sourceMap = aSourceMap;
  17838. if (typeof aSourceMap === "string") {
  17839. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  17840. }
  17841. const version = util$8.getArg(sourceMap, "version");
  17842. let sources = util$8.getArg(sourceMap, "sources");
  17843. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  17844. // requires the array) to play nice here.
  17845. const names = util$8.getArg(sourceMap, "names", []);
  17846. let sourceRoot = util$8.getArg(sourceMap, "sourceRoot", null);
  17847. const sourcesContent = util$8.getArg(sourceMap, "sourcesContent", null);
  17848. const mappings = util$8.getArg(sourceMap, "mappings");
  17849. const file = util$8.getArg(sourceMap, "file", null);
  17850. // Once again, Sass deviates from the spec and supplies the version as a
  17851. // string rather than a number, so we use loose equality checking here.
  17852. if (version != this._version) {
  17853. throw new Error("Unsupported version: " + version);
  17854. }
  17855. if (sourceRoot) {
  17856. sourceRoot = util$8.normalize(sourceRoot);
  17857. }
  17858. sources = sources
  17859. .map(String)
  17860. // Some source maps produce relative source paths like "./foo.js" instead of
  17861. // "foo.js". Normalize these first so that future comparisons will succeed.
  17862. // See bugzil.la/1090768.
  17863. .map(util$8.normalize)
  17864. // Always ensure that absolute sources are internally stored relative to
  17865. // the source root, if the source root is absolute. Not doing this would
  17866. // be particularly problematic when the source root is a prefix of the
  17867. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  17868. .map(function(source) {
  17869. return sourceRoot && util$8.isAbsolute(sourceRoot) && util$8.isAbsolute(source)
  17870. ? util$8.relative(sourceRoot, source)
  17871. : source;
  17872. });
  17873. // Pass `true` below to allow duplicate names and sources. While source maps
  17874. // are intended to be compressed and deduplicated, the TypeScript compiler
  17875. // sometimes generates source maps with duplicates in them. See Github issue
  17876. // #72 and bugzil.la/889492.
  17877. this._names = ArraySet$3.fromArray(names.map(String), true);
  17878. this._sources = ArraySet$3.fromArray(sources, true);
  17879. this._absoluteSources = this._sources.toArray().map(function(s) {
  17880. return util$8.computeSourceURL(sourceRoot, s, aSourceMapURL);
  17881. });
  17882. this.sourceRoot = sourceRoot;
  17883. this.sourcesContent = sourcesContent;
  17884. this._mappings = mappings;
  17885. this._sourceMapURL = aSourceMapURL;
  17886. this.file = file;
  17887. this._computedColumnSpans = false;
  17888. this._mappingsPtr = 0;
  17889. this._wasm = null;
  17890. const w = wasm.sync();
  17891. this._wasm = w;
  17892. }
  17893. /**
  17894. * Utility function to find the index of a source. Returns -1 if not
  17895. * found.
  17896. */
  17897. _findSourceIndex(aSource) {
  17898. let relativeSource = aSource;
  17899. if (this.sourceRoot != null) {
  17900. relativeSource = util$8.relative(this.sourceRoot, relativeSource);
  17901. }
  17902. if (this._sources.has(relativeSource)) {
  17903. return this._sources.indexOf(relativeSource);
  17904. }
  17905. // Maybe aSource is an absolute URL as returned by |sources|. In
  17906. // this case we can't simply undo the transform.
  17907. for (let i = 0; i < this._absoluteSources.length; ++i) {
  17908. if (this._absoluteSources[i] == aSource) {
  17909. return i;
  17910. }
  17911. }
  17912. return -1;
  17913. }
  17914. /**
  17915. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  17916. *
  17917. * @param SourceMapGenerator aSourceMap
  17918. * The source map that will be consumed.
  17919. * @param String aSourceMapURL
  17920. * The URL at which the source map can be found (optional)
  17921. * @returns BasicSourceMapConsumer
  17922. */
  17923. static fromSourceMap(aSourceMap, aSourceMapURL) {
  17924. return new BasicSourceMapConsumer$1(aSourceMap.toString());
  17925. }
  17926. get sources() {
  17927. return this._absoluteSources.slice();
  17928. }
  17929. _getMappingsPtr() {
  17930. if (this._mappingsPtr === 0) {
  17931. this._parseMappings(this._mappings, this.sourceRoot);
  17932. }
  17933. return this._mappingsPtr;
  17934. }
  17935. /**
  17936. * Parse the mappings in a string in to a data structure which we can easily
  17937. * query (the ordered arrays in the `this.__generatedMappings` and
  17938. * `this.__originalMappings` properties).
  17939. */
  17940. _parseMappings(aStr, aSourceRoot) {
  17941. const size = aStr.length;
  17942. const mappingsBufPtr = this._wasm.exports.allocate_mappings(size);
  17943. const mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size);
  17944. for (let i = 0; i < size; i++) {
  17945. mappingsBuf[i] = aStr.charCodeAt(i);
  17946. }
  17947. const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr);
  17948. if (!mappingsPtr) {
  17949. const error = this._wasm.exports.get_last_error();
  17950. let msg = `Error parsing mappings (code ${error}): `;
  17951. // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`.
  17952. switch (error) {
  17953. case 1:
  17954. msg += "the mappings contained a negative line, column, source index, or name index";
  17955. break;
  17956. case 2:
  17957. msg += "the mappings contained a number larger than 2**32";
  17958. break;
  17959. case 3:
  17960. msg += "reached EOF while in the middle of parsing a VLQ";
  17961. break;
  17962. case 4:
  17963. msg += "invalid base 64 character while parsing a VLQ";
  17964. break;
  17965. default:
  17966. msg += "unknown error code";
  17967. break;
  17968. }
  17969. throw new Error(msg);
  17970. }
  17971. this._mappingsPtr = mappingsPtr;
  17972. }
  17973. eachMapping(aCallback, aContext, aOrder) {
  17974. const context = aContext || null;
  17975. const order = aOrder || SourceMapConsumer$2.GENERATED_ORDER;
  17976. const sourceRoot = this.sourceRoot;
  17977. this._wasm.withMappingCallback(
  17978. mapping => {
  17979. if (mapping.source !== null) {
  17980. mapping.source = this._sources.at(mapping.source);
  17981. mapping.source = util$8.computeSourceURL(sourceRoot, mapping.source, this._sourceMapURL);
  17982. if (mapping.name !== null) {
  17983. mapping.name = this._names.at(mapping.name);
  17984. }
  17985. }
  17986. aCallback.call(context, mapping);
  17987. },
  17988. () => {
  17989. switch (order) {
  17990. case SourceMapConsumer$2.GENERATED_ORDER:
  17991. this._wasm.exports.by_generated_location(this._getMappingsPtr());
  17992. break;
  17993. case SourceMapConsumer$2.ORIGINAL_ORDER:
  17994. this._wasm.exports.by_original_location(this._getMappingsPtr());
  17995. break;
  17996. default:
  17997. throw new Error("Unknown order of iteration.");
  17998. }
  17999. }
  18000. );
  18001. }
  18002. allGeneratedPositionsFor(aArgs) {
  18003. let source = util$8.getArg(aArgs, "source");
  18004. const originalLine = util$8.getArg(aArgs, "line");
  18005. const originalColumn = aArgs.column || 0;
  18006. source = this._findSourceIndex(source);
  18007. if (source < 0) {
  18008. return [];
  18009. }
  18010. if (originalLine < 1) {
  18011. throw new Error("Line numbers must be >= 1");
  18012. }
  18013. if (originalColumn < 0) {
  18014. throw new Error("Column numbers must be >= 0");
  18015. }
  18016. const mappings = [];
  18017. this._wasm.withMappingCallback(
  18018. m => {
  18019. let lastColumn = m.lastGeneratedColumn;
  18020. if (this._computedColumnSpans && lastColumn === null) {
  18021. lastColumn = Infinity;
  18022. }
  18023. mappings.push({
  18024. line: m.generatedLine,
  18025. column: m.generatedColumn,
  18026. lastColumn,
  18027. });
  18028. }, () => {
  18029. this._wasm.exports.all_generated_locations_for(
  18030. this._getMappingsPtr(),
  18031. source,
  18032. originalLine - 1,
  18033. "column" in aArgs,
  18034. originalColumn
  18035. );
  18036. }
  18037. );
  18038. return mappings;
  18039. }
  18040. destroy() {
  18041. if (this._mappingsPtr !== 0) {
  18042. this._wasm.exports.free_mappings(this._mappingsPtr);
  18043. this._mappingsPtr = 0;
  18044. }
  18045. }
  18046. /**
  18047. * Compute the last column for each generated mapping. The last column is
  18048. * inclusive.
  18049. */
  18050. computeColumnSpans() {
  18051. if (this._computedColumnSpans) {
  18052. return;
  18053. }
  18054. this._wasm.exports.compute_column_spans(this._getMappingsPtr());
  18055. this._computedColumnSpans = true;
  18056. }
  18057. /**
  18058. * Returns the original source, line, and column information for the generated
  18059. * source's line and column positions provided. The only argument is an object
  18060. * with the following properties:
  18061. *
  18062. * - line: The line number in the generated source. The line number
  18063. * is 1-based.
  18064. * - column: The column number in the generated source. The column
  18065. * number is 0-based.
  18066. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  18067. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  18068. * closest element that is smaller than or greater than the one we are
  18069. * searching for, respectively, if the exact element cannot be found.
  18070. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  18071. *
  18072. * and an object is returned with the following properties:
  18073. *
  18074. * - source: The original source file, or null.
  18075. * - line: The line number in the original source, or null. The
  18076. * line number is 1-based.
  18077. * - column: The column number in the original source, or null. The
  18078. * column number is 0-based.
  18079. * - name: The original identifier, or null.
  18080. */
  18081. originalPositionFor(aArgs) {
  18082. const needle = {
  18083. generatedLine: util$8.getArg(aArgs, "line"),
  18084. generatedColumn: util$8.getArg(aArgs, "column")
  18085. };
  18086. if (needle.generatedLine < 1) {
  18087. throw new Error("Line numbers must be >= 1");
  18088. }
  18089. if (needle.generatedColumn < 0) {
  18090. throw new Error("Column numbers must be >= 0");
  18091. }
  18092. let bias = util$8.getArg(aArgs, "bias", SourceMapConsumer$2.GREATEST_LOWER_BOUND);
  18093. if (bias == null) {
  18094. bias = SourceMapConsumer$2.GREATEST_LOWER_BOUND;
  18095. }
  18096. let mapping;
  18097. this._wasm.withMappingCallback(m => mapping = m, () => {
  18098. this._wasm.exports.original_location_for(
  18099. this._getMappingsPtr(),
  18100. needle.generatedLine - 1,
  18101. needle.generatedColumn,
  18102. bias
  18103. );
  18104. });
  18105. if (mapping) {
  18106. if (mapping.generatedLine === needle.generatedLine) {
  18107. let source = util$8.getArg(mapping, "source", null);
  18108. if (source !== null) {
  18109. source = this._sources.at(source);
  18110. source = util$8.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  18111. }
  18112. let name = util$8.getArg(mapping, "name", null);
  18113. if (name !== null) {
  18114. name = this._names.at(name);
  18115. }
  18116. return {
  18117. source,
  18118. line: util$8.getArg(mapping, "originalLine", null),
  18119. column: util$8.getArg(mapping, "originalColumn", null),
  18120. name
  18121. };
  18122. }
  18123. }
  18124. return {
  18125. source: null,
  18126. line: null,
  18127. column: null,
  18128. name: null
  18129. };
  18130. }
  18131. /**
  18132. * Return true if we have the source content for every source in the source
  18133. * map, false otherwise.
  18134. */
  18135. hasContentsOfAllSources() {
  18136. if (!this.sourcesContent) {
  18137. return false;
  18138. }
  18139. return this.sourcesContent.length >= this._sources.size() &&
  18140. !this.sourcesContent.some(function(sc) { return sc == null; });
  18141. }
  18142. /**
  18143. * Returns the original source content. The only argument is the url of the
  18144. * original source file. Returns null if no original source content is
  18145. * available.
  18146. */
  18147. sourceContentFor(aSource, nullOnMissing) {
  18148. if (!this.sourcesContent) {
  18149. return null;
  18150. }
  18151. const index = this._findSourceIndex(aSource);
  18152. if (index >= 0) {
  18153. return this.sourcesContent[index];
  18154. }
  18155. let relativeSource = aSource;
  18156. if (this.sourceRoot != null) {
  18157. relativeSource = util$8.relative(this.sourceRoot, relativeSource);
  18158. }
  18159. let url;
  18160. if (this.sourceRoot != null
  18161. && (url = util$8.urlParse(this.sourceRoot))) {
  18162. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  18163. // many users. We can help them out when they expect file:// URIs to
  18164. // behave like it would if they were running a local HTTP server. See
  18165. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  18166. const fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  18167. if (url.scheme == "file"
  18168. && this._sources.has(fileUriAbsPath)) {
  18169. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
  18170. }
  18171. if ((!url.path || url.path == "/")
  18172. && this._sources.has("/" + relativeSource)) {
  18173. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  18174. }
  18175. }
  18176. // This function is used recursively from
  18177. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  18178. // don't want to throw if we can't find the source - we just want to
  18179. // return null, so we provide a flag to exit gracefully.
  18180. if (nullOnMissing) {
  18181. return null;
  18182. }
  18183. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  18184. }
  18185. /**
  18186. * Returns the generated line and column information for the original source,
  18187. * line, and column positions provided. The only argument is an object with
  18188. * the following properties:
  18189. *
  18190. * - source: The filename of the original source.
  18191. * - line: The line number in the original source. The line number
  18192. * is 1-based.
  18193. * - column: The column number in the original source. The column
  18194. * number is 0-based.
  18195. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  18196. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  18197. * closest element that is smaller than or greater than the one we are
  18198. * searching for, respectively, if the exact element cannot be found.
  18199. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  18200. *
  18201. * and an object is returned with the following properties:
  18202. *
  18203. * - line: The line number in the generated source, or null. The
  18204. * line number is 1-based.
  18205. * - column: The column number in the generated source, or null.
  18206. * The column number is 0-based.
  18207. */
  18208. generatedPositionFor(aArgs) {
  18209. let source = util$8.getArg(aArgs, "source");
  18210. source = this._findSourceIndex(source);
  18211. if (source < 0) {
  18212. return {
  18213. line: null,
  18214. column: null,
  18215. lastColumn: null
  18216. };
  18217. }
  18218. const needle = {
  18219. source,
  18220. originalLine: util$8.getArg(aArgs, "line"),
  18221. originalColumn: util$8.getArg(aArgs, "column")
  18222. };
  18223. if (needle.originalLine < 1) {
  18224. throw new Error("Line numbers must be >= 1");
  18225. }
  18226. if (needle.originalColumn < 0) {
  18227. throw new Error("Column numbers must be >= 0");
  18228. }
  18229. let bias = util$8.getArg(aArgs, "bias", SourceMapConsumer$2.GREATEST_LOWER_BOUND);
  18230. if (bias == null) {
  18231. bias = SourceMapConsumer$2.GREATEST_LOWER_BOUND;
  18232. }
  18233. let mapping;
  18234. this._wasm.withMappingCallback(m => mapping = m, () => {
  18235. this._wasm.exports.generated_location_for(
  18236. this._getMappingsPtr(),
  18237. needle.source,
  18238. needle.originalLine - 1,
  18239. needle.originalColumn,
  18240. bias
  18241. );
  18242. });
  18243. if (mapping) {
  18244. if (mapping.source === needle.source) {
  18245. let lastColumn = mapping.lastGeneratedColumn;
  18246. if (this._computedColumnSpans && lastColumn === null) {
  18247. lastColumn = Infinity;
  18248. }
  18249. return {
  18250. line: util$8.getArg(mapping, "generatedLine", null),
  18251. column: util$8.getArg(mapping, "generatedColumn", null),
  18252. lastColumn,
  18253. };
  18254. }
  18255. }
  18256. return {
  18257. line: null,
  18258. column: null,
  18259. lastColumn: null
  18260. };
  18261. }
  18262. }
  18263. BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$2;
  18264. sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer$1;
  18265. /**
  18266. * An IndexedSourceMapConsumer instance represents a parsed source map which
  18267. * we can query for information. It differs from BasicSourceMapConsumer in
  18268. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  18269. * input.
  18270. *
  18271. * The first parameter is a raw source map (either as a JSON string, or already
  18272. * parsed to an object). According to the spec for indexed source maps, they
  18273. * have the following attributes:
  18274. *
  18275. * - version: Which version of the source map spec this map is following.
  18276. * - file: Optional. The generated file this source map is associated with.
  18277. * - sections: A list of section definitions.
  18278. *
  18279. * Each value under the "sections" field has two fields:
  18280. * - offset: The offset into the original specified at which this section
  18281. * begins to apply, defined as an object with a "line" and "column"
  18282. * field.
  18283. * - map: A source map definition. This source map could also be indexed,
  18284. * but doesn't have to be.
  18285. *
  18286. * Instead of the "map" field, it's also possible to have a "url" field
  18287. * specifying a URL to retrieve a source map from, but that's currently
  18288. * unsupported.
  18289. *
  18290. * Here's an example source map, taken from the source map spec[0], but
  18291. * modified to omit a section which uses the "url" field.
  18292. *
  18293. * {
  18294. * version : 3,
  18295. * file: "app.js",
  18296. * sections: [{
  18297. * offset: {line:100, column:10},
  18298. * map: {
  18299. * version : 3,
  18300. * file: "section.js",
  18301. * sources: ["foo.js", "bar.js"],
  18302. * names: ["src", "maps", "are", "fun"],
  18303. * mappings: "AAAA,E;;ABCDE;"
  18304. * }
  18305. * }],
  18306. * }
  18307. *
  18308. * The second parameter, if given, is a string whose value is the URL
  18309. * at which the source map was found. This URL is used to compute the
  18310. * sources array.
  18311. *
  18312. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  18313. */
  18314. class IndexedSourceMapConsumer$1 extends SourceMapConsumer$2 {
  18315. constructor(aSourceMap, aSourceMapURL) {
  18316. super(INTERNAL);
  18317. let sourceMap = aSourceMap;
  18318. if (typeof aSourceMap === "string") {
  18319. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  18320. }
  18321. const version = util$8.getArg(sourceMap, "version");
  18322. const sections = util$8.getArg(sourceMap, "sections");
  18323. if (version != this._version) {
  18324. throw new Error("Unsupported version: " + version);
  18325. }
  18326. this._sources = new ArraySet$3();
  18327. this._names = new ArraySet$3();
  18328. this.__generatedMappings = null;
  18329. this.__originalMappings = null;
  18330. this.__generatedMappingsUnsorted = null;
  18331. this.__originalMappingsUnsorted = null;
  18332. let lastOffset = {
  18333. line: -1,
  18334. column: 0
  18335. };
  18336. this._sections = sections.map(s => {
  18337. if (s.url) {
  18338. // The url field will require support for asynchronicity.
  18339. // See https://github.com/mozilla/source-map/issues/16
  18340. throw new Error("Support for url field in sections not implemented.");
  18341. }
  18342. const offset = util$8.getArg(s, "offset");
  18343. const offsetLine = util$8.getArg(offset, "line");
  18344. const offsetColumn = util$8.getArg(offset, "column");
  18345. if (offsetLine < lastOffset.line ||
  18346. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  18347. throw new Error("Section offsets must be ordered and non-overlapping.");
  18348. }
  18349. lastOffset = offset;
  18350. const consumer = new SourceMapConsumer$2(util$8.getArg(s, "map"), aSourceMapURL);
  18351. return {
  18352. generatedOffset: {
  18353. // The offset fields are 0-based, but we use 1-based indices when
  18354. // encoding/decoding from VLQ.
  18355. generatedLine: offsetLine + 1,
  18356. generatedColumn: offsetColumn + 1
  18357. },
  18358. consumer
  18359. };
  18360. });
  18361. }
  18362. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  18363. // parsed mapping coordinates from the source map's "mappings" attribute. They
  18364. // are lazily instantiated, accessed via the `_generatedMappings` and
  18365. // `_originalMappings` getters respectively, and we only parse the mappings
  18366. // and create these arrays once queried for a source location. We jump through
  18367. // these hoops because there can be many thousands of mappings, and parsing
  18368. // them is expensive, so we only want to do it if we must.
  18369. //
  18370. // Each object in the arrays is of the form:
  18371. //
  18372. // {
  18373. // generatedLine: The line number in the generated code,
  18374. // generatedColumn: The column number in the generated code,
  18375. // source: The path to the original source file that generated this
  18376. // chunk of code,
  18377. // originalLine: The line number in the original source that
  18378. // corresponds to this chunk of generated code,
  18379. // originalColumn: The column number in the original source that
  18380. // corresponds to this chunk of generated code,
  18381. // name: The name of the original symbol which generated this chunk of
  18382. // code.
  18383. // }
  18384. //
  18385. // All properties except for `generatedLine` and `generatedColumn` can be
  18386. // `null`.
  18387. //
  18388. // `_generatedMappings` is ordered by the generated positions.
  18389. //
  18390. // `_originalMappings` is ordered by the original positions.
  18391. get _generatedMappings() {
  18392. if (!this.__generatedMappings) {
  18393. this._sortGeneratedMappings();
  18394. }
  18395. return this.__generatedMappings;
  18396. }
  18397. get _originalMappings() {
  18398. if (!this.__originalMappings) {
  18399. this._sortOriginalMappings();
  18400. }
  18401. return this.__originalMappings;
  18402. }
  18403. get _generatedMappingsUnsorted() {
  18404. if (!this.__generatedMappingsUnsorted) {
  18405. this._parseMappings(this._mappings, this.sourceRoot);
  18406. }
  18407. return this.__generatedMappingsUnsorted;
  18408. }
  18409. get _originalMappingsUnsorted() {
  18410. if (!this.__originalMappingsUnsorted) {
  18411. this._parseMappings(this._mappings, this.sourceRoot);
  18412. }
  18413. return this.__originalMappingsUnsorted;
  18414. }
  18415. _sortGeneratedMappings() {
  18416. const mappings = this._generatedMappingsUnsorted;
  18417. mappings.sort(util$8.compareByGeneratedPositionsDeflated);
  18418. this.__generatedMappings = mappings;
  18419. }
  18420. _sortOriginalMappings() {
  18421. const mappings = this._originalMappingsUnsorted;
  18422. mappings.sort(util$8.compareByOriginalPositions);
  18423. this.__originalMappings = mappings;
  18424. }
  18425. /**
  18426. * The list of original sources.
  18427. */
  18428. get sources() {
  18429. const sources = [];
  18430. for (let i = 0; i < this._sections.length; i++) {
  18431. for (let j = 0; j < this._sections[i].consumer.sources.length; j++) {
  18432. sources.push(this._sections[i].consumer.sources[j]);
  18433. }
  18434. }
  18435. return sources;
  18436. }
  18437. /**
  18438. * Returns the original source, line, and column information for the generated
  18439. * source's line and column positions provided. The only argument is an object
  18440. * with the following properties:
  18441. *
  18442. * - line: The line number in the generated source. The line number
  18443. * is 1-based.
  18444. * - column: The column number in the generated source. The column
  18445. * number is 0-based.
  18446. *
  18447. * and an object is returned with the following properties:
  18448. *
  18449. * - source: The original source file, or null.
  18450. * - line: The line number in the original source, or null. The
  18451. * line number is 1-based.
  18452. * - column: The column number in the original source, or null. The
  18453. * column number is 0-based.
  18454. * - name: The original identifier, or null.
  18455. */
  18456. originalPositionFor(aArgs) {
  18457. const needle = {
  18458. generatedLine: util$8.getArg(aArgs, "line"),
  18459. generatedColumn: util$8.getArg(aArgs, "column")
  18460. };
  18461. // Find the section containing the generated position we're trying to map
  18462. // to an original position.
  18463. const sectionIndex = binarySearch$2.search(needle, this._sections,
  18464. function(aNeedle, section) {
  18465. const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine;
  18466. if (cmp) {
  18467. return cmp;
  18468. }
  18469. return (aNeedle.generatedColumn -
  18470. section.generatedOffset.generatedColumn);
  18471. });
  18472. const section = this._sections[sectionIndex];
  18473. if (!section) {
  18474. return {
  18475. source: null,
  18476. line: null,
  18477. column: null,
  18478. name: null
  18479. };
  18480. }
  18481. return section.consumer.originalPositionFor({
  18482. line: needle.generatedLine -
  18483. (section.generatedOffset.generatedLine - 1),
  18484. column: needle.generatedColumn -
  18485. (section.generatedOffset.generatedLine === needle.generatedLine
  18486. ? section.generatedOffset.generatedColumn - 1
  18487. : 0),
  18488. bias: aArgs.bias
  18489. });
  18490. }
  18491. /**
  18492. * Return true if we have the source content for every source in the source
  18493. * map, false otherwise.
  18494. */
  18495. hasContentsOfAllSources() {
  18496. return this._sections.every(function(s) {
  18497. return s.consumer.hasContentsOfAllSources();
  18498. });
  18499. }
  18500. /**
  18501. * Returns the original source content. The only argument is the url of the
  18502. * original source file. Returns null if no original source content is
  18503. * available.
  18504. */
  18505. sourceContentFor(aSource, nullOnMissing) {
  18506. for (let i = 0; i < this._sections.length; i++) {
  18507. const section = this._sections[i];
  18508. const content = section.consumer.sourceContentFor(aSource, true);
  18509. if (content) {
  18510. return content;
  18511. }
  18512. }
  18513. if (nullOnMissing) {
  18514. return null;
  18515. }
  18516. throw new Error('"' + aSource + '" is not in the SourceMap.');
  18517. }
  18518. /**
  18519. * Returns the generated line and column information for the original source,
  18520. * line, and column positions provided. The only argument is an object with
  18521. * the following properties:
  18522. *
  18523. * - source: The filename of the original source.
  18524. * - line: The line number in the original source. The line number
  18525. * is 1-based.
  18526. * - column: The column number in the original source. The column
  18527. * number is 0-based.
  18528. *
  18529. * and an object is returned with the following properties:
  18530. *
  18531. * - line: The line number in the generated source, or null. The
  18532. * line number is 1-based.
  18533. * - column: The column number in the generated source, or null.
  18534. * The column number is 0-based.
  18535. */
  18536. generatedPositionFor(aArgs) {
  18537. for (let i = 0; i < this._sections.length; i++) {
  18538. const section = this._sections[i];
  18539. // Only consider this section if the requested source is in the list of
  18540. // sources of the consumer.
  18541. if (section.consumer._findSourceIndex(util$8.getArg(aArgs, "source")) === -1) {
  18542. continue;
  18543. }
  18544. const generatedPosition = section.consumer.generatedPositionFor(aArgs);
  18545. if (generatedPosition) {
  18546. const ret = {
  18547. line: generatedPosition.line +
  18548. (section.generatedOffset.generatedLine - 1),
  18549. column: generatedPosition.column +
  18550. (section.generatedOffset.generatedLine === generatedPosition.line
  18551. ? section.generatedOffset.generatedColumn - 1
  18552. : 0)
  18553. };
  18554. return ret;
  18555. }
  18556. }
  18557. return {
  18558. line: null,
  18559. column: null
  18560. };
  18561. }
  18562. /**
  18563. * Parse the mappings in a string in to a data structure which we can easily
  18564. * query (the ordered arrays in the `this.__generatedMappings` and
  18565. * `this.__originalMappings` properties).
  18566. */
  18567. _parseMappings(aStr, aSourceRoot) {
  18568. const generatedMappings = this.__generatedMappingsUnsorted = [];
  18569. const originalMappings = this.__originalMappingsUnsorted = [];
  18570. for (let i = 0; i < this._sections.length; i++) {
  18571. const section = this._sections[i];
  18572. const sectionMappings = [];
  18573. section.consumer.eachMapping(m => sectionMappings.push(m));
  18574. for (let j = 0; j < sectionMappings.length; j++) {
  18575. const mapping = sectionMappings[j];
  18576. // TODO: test if null is correct here. The original code used
  18577. // `source`, which would actually have gotten used as null because
  18578. // var's get hoisted.
  18579. // See: https://github.com/mozilla/source-map/issues/333
  18580. let source = util$8.computeSourceURL(section.consumer.sourceRoot, null, this._sourceMapURL);
  18581. this._sources.add(source);
  18582. source = this._sources.indexOf(source);
  18583. let name = null;
  18584. if (mapping.name) {
  18585. this._names.add(mapping.name);
  18586. name = this._names.indexOf(mapping.name);
  18587. }
  18588. // The mappings coming from the consumer for the section have
  18589. // generated positions relative to the start of the section, so we
  18590. // need to offset them to be relative to the start of the concatenated
  18591. // generated file.
  18592. const adjustedMapping = {
  18593. source,
  18594. generatedLine: mapping.generatedLine +
  18595. (section.generatedOffset.generatedLine - 1),
  18596. generatedColumn: mapping.generatedColumn +
  18597. (section.generatedOffset.generatedLine === mapping.generatedLine
  18598. ? section.generatedOffset.generatedColumn - 1
  18599. : 0),
  18600. originalLine: mapping.originalLine,
  18601. originalColumn: mapping.originalColumn,
  18602. name
  18603. };
  18604. generatedMappings.push(adjustedMapping);
  18605. if (typeof adjustedMapping.originalLine === "number") {
  18606. originalMappings.push(adjustedMapping);
  18607. }
  18608. }
  18609. }
  18610. }
  18611. eachMapping(aCallback, aContext, aOrder) {
  18612. const context = aContext || null;
  18613. const order = aOrder || SourceMapConsumer$2.GENERATED_ORDER;
  18614. let mappings;
  18615. switch (order) {
  18616. case SourceMapConsumer$2.GENERATED_ORDER:
  18617. mappings = this._generatedMappings;
  18618. break;
  18619. case SourceMapConsumer$2.ORIGINAL_ORDER:
  18620. mappings = this._originalMappings;
  18621. break;
  18622. default:
  18623. throw new Error("Unknown order of iteration.");
  18624. }
  18625. const sourceRoot = this.sourceRoot;
  18626. mappings.map(function(mapping) {
  18627. let source = null;
  18628. if (mapping.source !== null) {
  18629. source = this._sources.at(mapping.source);
  18630. source = util$8.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  18631. }
  18632. return {
  18633. source,
  18634. generatedLine: mapping.generatedLine,
  18635. generatedColumn: mapping.generatedColumn,
  18636. originalLine: mapping.originalLine,
  18637. originalColumn: mapping.originalColumn,
  18638. name: mapping.name === null ? null : this._names.at(mapping.name)
  18639. };
  18640. }, this).forEach(aCallback, context);
  18641. }
  18642. /**
  18643. * Find the mapping that best matches the hypothetical "needle" mapping that
  18644. * we are searching for in the given "haystack" of mappings.
  18645. */
  18646. _findMapping(aNeedle, aMappings, aLineName,
  18647. aColumnName, aComparator, aBias) {
  18648. // To return the position we are searching for, we must first find the
  18649. // mapping for the given position and then return the opposite position it
  18650. // points to. Because the mappings are sorted, we can use binary search to
  18651. // find the best mapping.
  18652. if (aNeedle[aLineName] <= 0) {
  18653. throw new TypeError("Line must be greater than or equal to 1, got "
  18654. + aNeedle[aLineName]);
  18655. }
  18656. if (aNeedle[aColumnName] < 0) {
  18657. throw new TypeError("Column must be greater than or equal to 0, got "
  18658. + aNeedle[aColumnName]);
  18659. }
  18660. return binarySearch$2.search(aNeedle, aMappings, aComparator, aBias);
  18661. }
  18662. allGeneratedPositionsFor(aArgs) {
  18663. const line = util$8.getArg(aArgs, "line");
  18664. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  18665. // returns the index of the closest mapping less than the needle. By
  18666. // setting needle.originalColumn to 0, we thus find the last mapping for
  18667. // the given line, provided such a mapping exists.
  18668. const needle = {
  18669. source: util$8.getArg(aArgs, "source"),
  18670. originalLine: line,
  18671. originalColumn: util$8.getArg(aArgs, "column", 0)
  18672. };
  18673. needle.source = this._findSourceIndex(needle.source);
  18674. if (needle.source < 0) {
  18675. return [];
  18676. }
  18677. if (needle.originalLine < 1) {
  18678. throw new Error("Line numbers must be >= 1");
  18679. }
  18680. if (needle.originalColumn < 0) {
  18681. throw new Error("Column numbers must be >= 0");
  18682. }
  18683. const mappings = [];
  18684. let index = this._findMapping(needle,
  18685. this._originalMappings,
  18686. "originalLine",
  18687. "originalColumn",
  18688. util$8.compareByOriginalPositions,
  18689. binarySearch$2.LEAST_UPPER_BOUND);
  18690. if (index >= 0) {
  18691. let mapping = this._originalMappings[index];
  18692. if (aArgs.column === undefined) {
  18693. const originalLine = mapping.originalLine;
  18694. // Iterate until either we run out of mappings, or we run into
  18695. // a mapping for a different line than the one we found. Since
  18696. // mappings are sorted, this is guaranteed to find all mappings for
  18697. // the line we found.
  18698. while (mapping && mapping.originalLine === originalLine) {
  18699. let lastColumn = mapping.lastGeneratedColumn;
  18700. if (this._computedColumnSpans && lastColumn === null) {
  18701. lastColumn = Infinity;
  18702. }
  18703. mappings.push({
  18704. line: util$8.getArg(mapping, "generatedLine", null),
  18705. column: util$8.getArg(mapping, "generatedColumn", null),
  18706. lastColumn,
  18707. });
  18708. mapping = this._originalMappings[++index];
  18709. }
  18710. } else {
  18711. const originalColumn = mapping.originalColumn;
  18712. // Iterate until either we run out of mappings, or we run into
  18713. // a mapping for a different line than the one we were searching for.
  18714. // Since mappings are sorted, this is guaranteed to find all mappings for
  18715. // the line we are searching for.
  18716. while (mapping &&
  18717. mapping.originalLine === line &&
  18718. mapping.originalColumn == originalColumn) {
  18719. let lastColumn = mapping.lastGeneratedColumn;
  18720. if (this._computedColumnSpans && lastColumn === null) {
  18721. lastColumn = Infinity;
  18722. }
  18723. mappings.push({
  18724. line: util$8.getArg(mapping, "generatedLine", null),
  18725. column: util$8.getArg(mapping, "generatedColumn", null),
  18726. lastColumn,
  18727. });
  18728. mapping = this._originalMappings[++index];
  18729. }
  18730. }
  18731. }
  18732. return mappings;
  18733. }
  18734. destroy() {
  18735. for (let i = 0; i < this._sections.length; i++) {
  18736. this._sections[i].consumer.destroy();
  18737. }
  18738. }
  18739. }
  18740. sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer$1;
  18741. /*
  18742. * Cheat to get around inter-twingled classes. `factory()` can be at the end
  18743. * where it has access to non-hoisted classes, but it gets hoisted itself.
  18744. */
  18745. function _factory(aSourceMap, aSourceMapURL) {
  18746. let sourceMap = aSourceMap;
  18747. if (typeof aSourceMap === "string") {
  18748. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  18749. }
  18750. const consumer = sourceMap.sections != null
  18751. ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL)
  18752. : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL);
  18753. return consumer;
  18754. }
  18755. function _factoryBSM(aSourceMap, aSourceMapURL) {
  18756. return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL);
  18757. }
  18758. /*
  18759. * Copyright 2009-2011 Mozilla Foundation and contributors
  18760. * Licensed under the New BSD license. See LICENSE.txt or:
  18761. * http://opensource.org/licenses/BSD-3-Clause
  18762. */
  18763. sourceMap.SourceMapConsumer = sourceMapConsumer$1.SourceMapConsumer;
  18764. (function (module, exports) {
  18765. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  18766. var path = path__default;
  18767. var util = require$$0__default$3;
  18768. var fs;
  18769. try {
  18770. fs = fs__default;
  18771. if (!fs.existsSync || !fs.readFileSync) {
  18772. // fs doesn't have all methods we need
  18773. fs = null;
  18774. }
  18775. } catch (err) {
  18776. /* nop */
  18777. }
  18778. /**
  18779. * Requires a module which is protected against bundler minification.
  18780. *
  18781. * @param {NodeModule} mod
  18782. * @param {string} request
  18783. */
  18784. function dynamicRequire(mod, request) {
  18785. return mod.require(request);
  18786. }
  18787. // Only install once if called multiple times
  18788. var errorFormatterInstalled = false;
  18789. var uncaughtShimInstalled = false;
  18790. // If true, the caches are reset before a stack trace formatting operation
  18791. var emptyCacheBetweenOperations = false;
  18792. // Supports {browser, node, auto}
  18793. var environment = "auto";
  18794. // Maps a file path to a string containing the file contents
  18795. var fileContentsCache = {};
  18796. // Maps a file path to a source map for that file
  18797. var sourceMapCache = {};
  18798. // Regex for detecting source maps
  18799. var reSourceMap = /^data:application\/json[^,]+base64,/;
  18800. // Priority list of retrieve handlers
  18801. var retrieveFileHandlers = [];
  18802. var retrieveMapHandlers = [];
  18803. function isInBrowser() {
  18804. if (environment === "browser")
  18805. return true;
  18806. if (environment === "node")
  18807. return false;
  18808. return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
  18809. }
  18810. function hasGlobalProcessEventEmitter() {
  18811. return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
  18812. }
  18813. function handlerExec(list) {
  18814. return function(arg) {
  18815. for (var i = 0; i < list.length; i++) {
  18816. var ret = list[i](arg);
  18817. if (ret) {
  18818. return ret;
  18819. }
  18820. }
  18821. return null;
  18822. };
  18823. }
  18824. var retrieveFile = handlerExec(retrieveFileHandlers);
  18825. retrieveFileHandlers.push(function(path) {
  18826. // Trim the path to make sure there is no extra whitespace.
  18827. path = path.trim();
  18828. if (/^file:/.test(path)) {
  18829. // existsSync/readFileSync can't handle file protocol, but once stripped, it works
  18830. path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
  18831. return drive ?
  18832. '' : // file:///C:/dir/file -> C:/dir/file
  18833. '/'; // file:///root-dir/file -> /root-dir/file
  18834. });
  18835. }
  18836. if (path in fileContentsCache) {
  18837. return fileContentsCache[path];
  18838. }
  18839. var contents = '';
  18840. try {
  18841. if (!fs) {
  18842. // Use SJAX if we are in the browser
  18843. var xhr = new XMLHttpRequest();
  18844. xhr.open('GET', path, /** async */ false);
  18845. xhr.send(null);
  18846. if (xhr.readyState === 4 && xhr.status === 200) {
  18847. contents = xhr.responseText;
  18848. }
  18849. } else if (fs.existsSync(path)) {
  18850. // Otherwise, use the filesystem
  18851. contents = fs.readFileSync(path, 'utf8');
  18852. }
  18853. } catch (er) {
  18854. /* ignore any errors */
  18855. }
  18856. return fileContentsCache[path] = contents;
  18857. });
  18858. // Support URLs relative to a directory, but be careful about a protocol prefix
  18859. // in case we are in the browser (i.e. directories may start with "http://" or "file:///")
  18860. function supportRelativeURL(file, url) {
  18861. if (!file) return url;
  18862. var dir = path.dirname(file);
  18863. var match = /^\w+:\/\/[^\/]*/.exec(dir);
  18864. var protocol = match ? match[0] : '';
  18865. var startPath = dir.slice(protocol.length);
  18866. if (protocol && /^\/\w\:/.test(startPath)) {
  18867. // handle file:///C:/ paths
  18868. protocol += '/';
  18869. return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/');
  18870. }
  18871. return protocol + path.resolve(dir.slice(protocol.length), url);
  18872. }
  18873. function retrieveSourceMapURL(source) {
  18874. var fileData;
  18875. if (isInBrowser()) {
  18876. try {
  18877. var xhr = new XMLHttpRequest();
  18878. xhr.open('GET', source, false);
  18879. xhr.send(null);
  18880. fileData = xhr.readyState === 4 ? xhr.responseText : null;
  18881. // Support providing a sourceMappingURL via the SourceMap header
  18882. var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
  18883. xhr.getResponseHeader("X-SourceMap");
  18884. if (sourceMapHeader) {
  18885. return sourceMapHeader;
  18886. }
  18887. } catch (e) {
  18888. }
  18889. }
  18890. // Get the URL of the source map
  18891. fileData = retrieveFile(source);
  18892. var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
  18893. // Keep executing the search to find the *last* sourceMappingURL to avoid
  18894. // picking up sourceMappingURLs from comments, strings, etc.
  18895. var lastMatch, match;
  18896. while (match = re.exec(fileData)) lastMatch = match;
  18897. if (!lastMatch) return null;
  18898. return lastMatch[1];
  18899. }
  18900. // Can be overridden by the retrieveSourceMap option to install. Takes a
  18901. // generated source filename; returns a {map, optional url} object, or null if
  18902. // there is no source map. The map field may be either a string or the parsed
  18903. // JSON object (ie, it must be a valid argument to the SourceMapConsumer
  18904. // constructor).
  18905. var retrieveSourceMap = handlerExec(retrieveMapHandlers);
  18906. retrieveMapHandlers.push(function(source) {
  18907. var sourceMappingURL = retrieveSourceMapURL(source);
  18908. if (!sourceMappingURL) return null;
  18909. // Read the contents of the source map
  18910. var sourceMapData;
  18911. if (reSourceMap.test(sourceMappingURL)) {
  18912. // Support source map URL as a data url
  18913. var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
  18914. sourceMapData = Buffer.from(rawData, "base64").toString();
  18915. sourceMappingURL = source;
  18916. } else {
  18917. // Support source map URLs relative to the source URL
  18918. sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
  18919. sourceMapData = retrieveFile(sourceMappingURL);
  18920. }
  18921. if (!sourceMapData) {
  18922. return null;
  18923. }
  18924. return {
  18925. url: sourceMappingURL,
  18926. map: sourceMapData
  18927. };
  18928. });
  18929. function mapSourcePosition(position) {
  18930. var sourceMap = sourceMapCache[position.source];
  18931. if (!sourceMap) {
  18932. // Call the (overrideable) retrieveSourceMap function to get the source map.
  18933. var urlAndMap = retrieveSourceMap(position.source);
  18934. if (urlAndMap) {
  18935. sourceMap = sourceMapCache[position.source] = {
  18936. url: urlAndMap.url,
  18937. map: new SourceMapConsumer(urlAndMap.map)
  18938. };
  18939. // Load all sources stored inline with the source map into the file cache
  18940. // to pretend like they are already loaded. They may not exist on disk.
  18941. if (sourceMap.map.sourcesContent) {
  18942. sourceMap.map.sources.forEach(function(source, i) {
  18943. var contents = sourceMap.map.sourcesContent[i];
  18944. if (contents) {
  18945. var url = supportRelativeURL(sourceMap.url, source);
  18946. fileContentsCache[url] = contents;
  18947. }
  18948. });
  18949. }
  18950. } else {
  18951. sourceMap = sourceMapCache[position.source] = {
  18952. url: null,
  18953. map: null
  18954. };
  18955. }
  18956. }
  18957. // Resolve the source URL relative to the URL of the source map
  18958. if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') {
  18959. var originalPosition = sourceMap.map.originalPositionFor(position);
  18960. // Only return the original position if a matching line was found. If no
  18961. // matching line is found then we return position instead, which will cause
  18962. // the stack trace to print the path and line for the compiled file. It is
  18963. // better to give a precise location in the compiled file than a vague
  18964. // location in the original file.
  18965. if (originalPosition.source !== null) {
  18966. originalPosition.source = supportRelativeURL(
  18967. sourceMap.url, originalPosition.source);
  18968. return originalPosition;
  18969. }
  18970. }
  18971. return position;
  18972. }
  18973. // Parses code generated by FormatEvalOrigin(), a function inside V8:
  18974. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
  18975. function mapEvalOrigin(origin) {
  18976. // Most eval() calls are in this format
  18977. var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  18978. if (match) {
  18979. var position = mapSourcePosition({
  18980. source: match[2],
  18981. line: +match[3],
  18982. column: match[4] - 1
  18983. });
  18984. return 'eval at ' + match[1] + ' (' + position.source + ':' +
  18985. position.line + ':' + (position.column + 1) + ')';
  18986. }
  18987. // Parse nested eval() calls using recursion
  18988. match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  18989. if (match) {
  18990. return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
  18991. }
  18992. // Make sure we still return useful information if we didn't find anything
  18993. return origin;
  18994. }
  18995. // This is copied almost verbatim from the V8 source code at
  18996. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
  18997. // implementation of wrapCallSite() used to just forward to the actual source
  18998. // code of CallSite.prototype.toString but unfortunately a new release of V8
  18999. // did something to the prototype chain and broke the shim. The only fix I
  19000. // could find was copy/paste.
  19001. function CallSiteToString() {
  19002. var fileName;
  19003. var fileLocation = "";
  19004. if (this.isNative()) {
  19005. fileLocation = "native";
  19006. } else {
  19007. fileName = this.getScriptNameOrSourceURL();
  19008. if (!fileName && this.isEval()) {
  19009. fileLocation = this.getEvalOrigin();
  19010. fileLocation += ", "; // Expecting source position to follow.
  19011. }
  19012. if (fileName) {
  19013. fileLocation += fileName;
  19014. } else {
  19015. // Source code does not originate from a file and is not native, but we
  19016. // can still get the source position inside the source string, e.g. in
  19017. // an eval string.
  19018. fileLocation += "<anonymous>";
  19019. }
  19020. var lineNumber = this.getLineNumber();
  19021. if (lineNumber != null) {
  19022. fileLocation += ":" + lineNumber;
  19023. var columnNumber = this.getColumnNumber();
  19024. if (columnNumber) {
  19025. fileLocation += ":" + columnNumber;
  19026. }
  19027. }
  19028. }
  19029. var line = "";
  19030. var isAsync = this.isAsync ? this.isAsync() : false;
  19031. if(isAsync) {
  19032. line += 'async ';
  19033. var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false;
  19034. var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false;
  19035. if(isPromiseAny || isPromiseAll) {
  19036. line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index ';
  19037. var promiseIndex = this.getPromiseIndex();
  19038. line += promiseIndex + ')';
  19039. }
  19040. }
  19041. var functionName = this.getFunctionName();
  19042. var addSuffix = true;
  19043. var isConstructor = this.isConstructor();
  19044. var isMethodCall = !(this.isToplevel() || isConstructor);
  19045. if (isMethodCall) {
  19046. var typeName = this.getTypeName();
  19047. // Fixes shim to be backward compatable with Node v0 to v4
  19048. if (typeName === "[object Object]") {
  19049. typeName = "null";
  19050. }
  19051. var methodName = this.getMethodName();
  19052. if (functionName) {
  19053. if (typeName && functionName.indexOf(typeName) != 0) {
  19054. line += typeName + ".";
  19055. }
  19056. line += functionName;
  19057. if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
  19058. line += " [as " + methodName + "]";
  19059. }
  19060. } else {
  19061. line += typeName + "." + (methodName || "<anonymous>");
  19062. }
  19063. } else if (isConstructor) {
  19064. line += "new " + (functionName || "<anonymous>");
  19065. } else if (functionName) {
  19066. line += functionName;
  19067. } else {
  19068. line += fileLocation;
  19069. addSuffix = false;
  19070. }
  19071. if (addSuffix) {
  19072. line += " (" + fileLocation + ")";
  19073. }
  19074. return line;
  19075. }
  19076. function cloneCallSite(frame) {
  19077. var object = {};
  19078. Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
  19079. object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
  19080. });
  19081. object.toString = CallSiteToString;
  19082. return object;
  19083. }
  19084. function wrapCallSite(frame, state) {
  19085. // provides interface backward compatibility
  19086. if (state === undefined) {
  19087. state = { nextPosition: null, curPosition: null };
  19088. }
  19089. if(frame.isNative()) {
  19090. state.curPosition = null;
  19091. return frame;
  19092. }
  19093. // Most call sites will return the source file from getFileName(), but code
  19094. // passed to eval() ending in "//# sourceURL=..." will return the source file
  19095. // from getScriptNameOrSourceURL() instead
  19096. var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  19097. if (source) {
  19098. var line = frame.getLineNumber();
  19099. var column = frame.getColumnNumber() - 1;
  19100. // Fix position in Node where some (internal) code is prepended.
  19101. // See https://github.com/evanw/node-source-map-support/issues/36
  19102. // Header removed in node at ^10.16 || >=11.11.0
  19103. // v11 is not an LTS candidate, we can just test the one version with it.
  19104. // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
  19105. var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
  19106. var headerLength = noHeader.test(process.version) ? 0 : 62;
  19107. if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
  19108. column -= headerLength;
  19109. }
  19110. var position = mapSourcePosition({
  19111. source: source,
  19112. line: line,
  19113. column: column
  19114. });
  19115. state.curPosition = position;
  19116. frame = cloneCallSite(frame);
  19117. var originalFunctionName = frame.getFunctionName;
  19118. frame.getFunctionName = function() {
  19119. if (state.nextPosition == null) {
  19120. return originalFunctionName();
  19121. }
  19122. return state.nextPosition.name || originalFunctionName();
  19123. };
  19124. frame.getFileName = function() { return position.source; };
  19125. frame.getLineNumber = function() { return position.line; };
  19126. frame.getColumnNumber = function() { return position.column + 1; };
  19127. frame.getScriptNameOrSourceURL = function() { return position.source; };
  19128. return frame;
  19129. }
  19130. // Code called using eval() needs special handling
  19131. var origin = frame.isEval() && frame.getEvalOrigin();
  19132. if (origin) {
  19133. origin = mapEvalOrigin(origin);
  19134. frame = cloneCallSite(frame);
  19135. frame.getEvalOrigin = function() { return origin; };
  19136. return frame;
  19137. }
  19138. // If we get here then we were unable to change the source position
  19139. return frame;
  19140. }
  19141. var kIsNodeError = undefined;
  19142. try {
  19143. // Get a deliberate ERR_INVALID_ARG_TYPE
  19144. // TODO is there a better way to reliably get an instance of NodeError?
  19145. path.resolve(123);
  19146. } catch(e) {
  19147. const symbols = Object.getOwnPropertySymbols(e);
  19148. const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0});
  19149. if(symbol) kIsNodeError = symbol;
  19150. }
  19151. const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err);
  19152. // This function is part of the V8 stack trace API, for more info see:
  19153. // https://v8.dev/docs/stack-trace-api
  19154. function prepareStackTrace(error, stack) {
  19155. if (emptyCacheBetweenOperations) {
  19156. fileContentsCache = {};
  19157. sourceMapCache = {};
  19158. }
  19159. // node gives its own errors special treatment. Mimic that behavior
  19160. // https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128
  19161. // https://github.com/nodejs/node/pull/39182
  19162. var errorString;
  19163. if (kIsNodeError) {
  19164. if(kIsNodeError in error) {
  19165. errorString = `${error.name} [${error.code}]: ${error.message}`;
  19166. } else {
  19167. errorString = ErrorPrototypeToString(error);
  19168. }
  19169. } else {
  19170. var name = error.name || 'Error';
  19171. var message = error.message || '';
  19172. errorString = name + ": " + message;
  19173. }
  19174. var state = { nextPosition: null, curPosition: null };
  19175. var processedStack = [];
  19176. for (var i = stack.length - 1; i >= 0; i--) {
  19177. processedStack.push('\n at ' + wrapCallSite(stack[i], state));
  19178. state.nextPosition = state.curPosition;
  19179. }
  19180. state.curPosition = state.nextPosition = null;
  19181. return errorString + processedStack.reverse().join('');
  19182. }
  19183. // Generate position and snippet of original source with pointer
  19184. function getErrorSource(error) {
  19185. var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
  19186. if (match) {
  19187. var source = match[1];
  19188. var line = +match[2];
  19189. var column = +match[3];
  19190. // Support the inline sourceContents inside the source map
  19191. var contents = fileContentsCache[source];
  19192. // Support files on disk
  19193. if (!contents && fs && fs.existsSync(source)) {
  19194. try {
  19195. contents = fs.readFileSync(source, 'utf8');
  19196. } catch (er) {
  19197. contents = '';
  19198. }
  19199. }
  19200. // Format the line from the original source code like node does
  19201. if (contents) {
  19202. var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
  19203. if (code) {
  19204. return source + ':' + line + '\n' + code + '\n' +
  19205. new Array(column).join(' ') + '^';
  19206. }
  19207. }
  19208. }
  19209. return null;
  19210. }
  19211. function printFatalErrorUponExit (error) {
  19212. var source = getErrorSource(error);
  19213. // Ensure error is printed synchronously and not truncated
  19214. if (process.stderr._handle && process.stderr._handle.setBlocking) {
  19215. process.stderr._handle.setBlocking(true);
  19216. }
  19217. if (source) {
  19218. console.error(source);
  19219. }
  19220. // Matches node's behavior for colorized output
  19221. console.error(
  19222. util.inspect(error, {
  19223. customInspect: false,
  19224. colors: process.stderr.isTTY
  19225. })
  19226. );
  19227. }
  19228. function shimEmitUncaughtException () {
  19229. var origEmit = process.emit;
  19230. var isTerminatingDueToFatalException = false;
  19231. var fatalException;
  19232. process.emit = function (type) {
  19233. const hadListeners = origEmit.apply(this, arguments);
  19234. if (type === 'uncaughtException' && !hadListeners) {
  19235. isTerminatingDueToFatalException = true;
  19236. fatalException = arguments[1];
  19237. process.exit(1);
  19238. }
  19239. if (type === 'exit' && isTerminatingDueToFatalException) {
  19240. printFatalErrorUponExit(fatalException);
  19241. }
  19242. return hadListeners;
  19243. };
  19244. }
  19245. var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
  19246. var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
  19247. exports.wrapCallSite = wrapCallSite;
  19248. exports.getErrorSource = getErrorSource;
  19249. exports.mapSourcePosition = mapSourcePosition;
  19250. exports.retrieveSourceMap = retrieveSourceMap;
  19251. exports.install = function(options) {
  19252. options = options || {};
  19253. if (options.environment) {
  19254. environment = options.environment;
  19255. if (["node", "browser", "auto"].indexOf(environment) === -1) {
  19256. throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
  19257. }
  19258. }
  19259. // Allow sources to be found by methods other than reading the files
  19260. // directly from disk.
  19261. if (options.retrieveFile) {
  19262. if (options.overrideRetrieveFile) {
  19263. retrieveFileHandlers.length = 0;
  19264. }
  19265. retrieveFileHandlers.unshift(options.retrieveFile);
  19266. }
  19267. // Allow source maps to be found by methods other than reading the files
  19268. // directly from disk.
  19269. if (options.retrieveSourceMap) {
  19270. if (options.overrideRetrieveSourceMap) {
  19271. retrieveMapHandlers.length = 0;
  19272. }
  19273. retrieveMapHandlers.unshift(options.retrieveSourceMap);
  19274. }
  19275. // Support runtime transpilers that include inline source maps
  19276. if (options.hookRequire && !isInBrowser()) {
  19277. // Use dynamicRequire to avoid including in browser bundles
  19278. var Module = dynamicRequire(module, 'module');
  19279. var $compile = Module.prototype._compile;
  19280. if (!$compile.__sourceMapSupport) {
  19281. Module.prototype._compile = function(content, filename) {
  19282. fileContentsCache[filename] = content;
  19283. sourceMapCache[filename] = undefined;
  19284. return $compile.call(this, content, filename);
  19285. };
  19286. Module.prototype._compile.__sourceMapSupport = true;
  19287. }
  19288. }
  19289. // Configure options
  19290. if (!emptyCacheBetweenOperations) {
  19291. emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
  19292. options.emptyCacheBetweenOperations : false;
  19293. }
  19294. // Install the error reformatter
  19295. if (!errorFormatterInstalled) {
  19296. errorFormatterInstalled = true;
  19297. Error.prepareStackTrace = prepareStackTrace;
  19298. }
  19299. if (!uncaughtShimInstalled) {
  19300. var installHandler = 'handleUncaughtExceptions' in options ?
  19301. options.handleUncaughtExceptions : true;
  19302. // Do not override 'uncaughtException' with our own handler in Node.js
  19303. // Worker threads. Workers pass the error to the main thread as an event,
  19304. // rather than printing something to stderr and exiting.
  19305. try {
  19306. // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
  19307. var worker_threads = dynamicRequire(module, 'worker_threads');
  19308. if (worker_threads.isMainThread === false) {
  19309. installHandler = false;
  19310. }
  19311. } catch(e) {}
  19312. // Provide the option to not install the uncaught exception handler. This is
  19313. // to support other uncaught exception handlers (in test frameworks, for
  19314. // example). If this handler is not installed and there are no other uncaught
  19315. // exception handlers, uncaught exceptions will be caught by node's built-in
  19316. // exception handler and the process will still be terminated. However, the
  19317. // generated JavaScript code will be shown above the stack trace instead of
  19318. // the original source code.
  19319. if (installHandler && hasGlobalProcessEventEmitter()) {
  19320. uncaughtShimInstalled = true;
  19321. shimEmitUncaughtException();
  19322. }
  19323. }
  19324. };
  19325. exports.resetRetrieveHandlers = function() {
  19326. retrieveFileHandlers.length = 0;
  19327. retrieveMapHandlers.length = 0;
  19328. retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
  19329. retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
  19330. retrieveSourceMap = handlerExec(retrieveMapHandlers);
  19331. retrieveFile = handlerExec(retrieveFileHandlers);
  19332. };
  19333. }(sourceMapSupport, sourceMapSupport.exports));
  19334. var makeError$2 = {exports: {}};
  19335. (function (module, exports) {
  19336. // ===================================================================
  19337. var construct = typeof Reflect !== "undefined" ? Reflect.construct : undefined;
  19338. var defineProperty = Object.defineProperty;
  19339. // -------------------------------------------------------------------
  19340. var captureStackTrace = Error.captureStackTrace;
  19341. if (captureStackTrace === undefined) {
  19342. captureStackTrace = function captureStackTrace(error) {
  19343. var container = new Error();
  19344. defineProperty(error, "stack", {
  19345. configurable: true,
  19346. get: function getStack() {
  19347. var stack = container.stack;
  19348. // Replace property with value for faster future accesses.
  19349. defineProperty(this, "stack", {
  19350. configurable: true,
  19351. value: stack,
  19352. writable: true,
  19353. });
  19354. return stack;
  19355. },
  19356. set: function setStack(stack) {
  19357. defineProperty(error, "stack", {
  19358. configurable: true,
  19359. value: stack,
  19360. writable: true,
  19361. });
  19362. },
  19363. });
  19364. };
  19365. }
  19366. // -------------------------------------------------------------------
  19367. function BaseError(message) {
  19368. if (message !== undefined) {
  19369. defineProperty(this, "message", {
  19370. configurable: true,
  19371. value: message,
  19372. writable: true,
  19373. });
  19374. }
  19375. var cname = this.constructor.name;
  19376. if (cname !== undefined && cname !== this.name) {
  19377. defineProperty(this, "name", {
  19378. configurable: true,
  19379. value: cname,
  19380. writable: true,
  19381. });
  19382. }
  19383. captureStackTrace(this, this.constructor);
  19384. }
  19385. BaseError.prototype = Object.create(Error.prototype, {
  19386. // See: https://github.com/JsCommunity/make-error/issues/4
  19387. constructor: {
  19388. configurable: true,
  19389. value: BaseError,
  19390. writable: true,
  19391. },
  19392. });
  19393. // -------------------------------------------------------------------
  19394. // Sets the name of a function if possible (depends of the JS engine).
  19395. var setFunctionName = (function() {
  19396. function setFunctionName(fn, name) {
  19397. return defineProperty(fn, "name", {
  19398. configurable: true,
  19399. value: name,
  19400. });
  19401. }
  19402. try {
  19403. var f = function() {};
  19404. setFunctionName(f, "foo");
  19405. if (f.name === "foo") {
  19406. return setFunctionName;
  19407. }
  19408. } catch (_) {}
  19409. })();
  19410. // -------------------------------------------------------------------
  19411. function makeError(constructor, super_) {
  19412. if (super_ == null || super_ === Error) {
  19413. super_ = BaseError;
  19414. } else if (typeof super_ !== "function") {
  19415. throw new TypeError("super_ should be a function");
  19416. }
  19417. var name;
  19418. if (typeof constructor === "string") {
  19419. name = constructor;
  19420. constructor =
  19421. construct !== undefined
  19422. ? function() {
  19423. return construct(super_, arguments, this.constructor);
  19424. }
  19425. : function() {
  19426. super_.apply(this, arguments);
  19427. };
  19428. // If the name can be set, do it once and for all.
  19429. if (setFunctionName !== undefined) {
  19430. setFunctionName(constructor, name);
  19431. name = undefined;
  19432. }
  19433. } else if (typeof constructor !== "function") {
  19434. throw new TypeError("constructor should be either a string or a function");
  19435. }
  19436. // Also register the super constructor also as `constructor.super_` just
  19437. // like Node's `util.inherits()`.
  19438. //
  19439. // eslint-disable-next-line dot-notation
  19440. constructor.super_ = constructor["super"] = super_;
  19441. var properties = {
  19442. constructor: {
  19443. configurable: true,
  19444. value: constructor,
  19445. writable: true,
  19446. },
  19447. };
  19448. // If the name could not be set on the constructor, set it on the
  19449. // prototype.
  19450. if (name !== undefined) {
  19451. properties.name = {
  19452. configurable: true,
  19453. value: name,
  19454. writable: true,
  19455. };
  19456. }
  19457. constructor.prototype = Object.create(super_.prototype, properties);
  19458. return constructor;
  19459. }
  19460. exports = module.exports = makeError;
  19461. exports.BaseError = BaseError;
  19462. }(makeError$2, makeError$2.exports));
  19463. var util$7 = {};
  19464. var yn$2 = {exports: {}};
  19465. const YES_MATCH_SCORE_THRESHOLD = 2;
  19466. const NO_MATCH_SCORE_THRESHOLD = 1.25;
  19467. const yMatch = new Map([
  19468. [5, 0.25],
  19469. [6, 0.25],
  19470. [7, 0.25],
  19471. ['t', 0.75],
  19472. ['y', 1],
  19473. ['u', 0.75],
  19474. ['g', 0.25],
  19475. ['h', 0.25],
  19476. ['j', 0.25]
  19477. ]);
  19478. const eMatch = new Map([
  19479. [2, 0.25],
  19480. [3, 0.25],
  19481. [4, 0.25],
  19482. ['w', 0.75],
  19483. ['e', 1],
  19484. ['r', 0.75],
  19485. ['s', 0.25],
  19486. ['d', 0.25],
  19487. ['f', 0.25]
  19488. ]);
  19489. const sMatch = new Map([
  19490. ['q', 0.25],
  19491. ['w', 0.25],
  19492. ['e', 0.25],
  19493. ['a', 0.75],
  19494. ['s', 1],
  19495. ['d', 0.75],
  19496. ['z', 0.25],
  19497. ['x', 0.25],
  19498. ['c', 0.25]
  19499. ]);
  19500. const nMatch = new Map([
  19501. ['h', 0.25],
  19502. ['j', 0.25],
  19503. ['k', 0.25],
  19504. ['b', 0.75],
  19505. ['n', 1],
  19506. ['m', 0.75]
  19507. ]);
  19508. const oMatch = new Map([
  19509. [9, 0.25],
  19510. [0, 0.25],
  19511. ['i', 0.75],
  19512. ['o', 1],
  19513. ['p', 0.75],
  19514. ['k', 0.25],
  19515. ['l', 0.25]
  19516. ]);
  19517. function getYesMatchScore(value) {
  19518. const [y, e, s] = value;
  19519. let score = 0;
  19520. if (yMatch.has(y)) {
  19521. score += yMatch.get(y);
  19522. }
  19523. if (eMatch.has(e)) {
  19524. score += eMatch.get(e);
  19525. }
  19526. if (sMatch.has(s)) {
  19527. score += sMatch.get(s);
  19528. }
  19529. return score;
  19530. }
  19531. function getNoMatchScore(value) {
  19532. const [n, o] = value;
  19533. let score = 0;
  19534. if (nMatch.has(n)) {
  19535. score += nMatch.get(n);
  19536. }
  19537. if (oMatch.has(o)) {
  19538. score += oMatch.get(o);
  19539. }
  19540. return score;
  19541. }
  19542. var lenient$1 = (input, options) => {
  19543. if (getYesMatchScore(input) >= YES_MATCH_SCORE_THRESHOLD) {
  19544. return true;
  19545. }
  19546. if (getNoMatchScore(input) >= NO_MATCH_SCORE_THRESHOLD) {
  19547. return false;
  19548. }
  19549. return options.default;
  19550. };
  19551. const lenient = lenient$1;
  19552. const yn$1 = (input, options) => {
  19553. input = String(input).trim();
  19554. options = Object.assign({
  19555. lenient: false,
  19556. default: null
  19557. }, options);
  19558. if (options.default !== null && typeof options.default !== 'boolean') {
  19559. throw new TypeError(`Expected the \`default\` option to be of type \`boolean\`, got \`${typeof options.default}\``);
  19560. }
  19561. if (/^(?:y|yes|true|1)$/i.test(input)) {
  19562. return true;
  19563. }
  19564. if (/^(?:n|no|false|0)$/i.test(input)) {
  19565. return false;
  19566. }
  19567. if (options.lenient === true) {
  19568. return lenient(input, options);
  19569. }
  19570. return options.default;
  19571. };
  19572. yn$2.exports = yn$1;
  19573. // TODO: Remove this for the next major release
  19574. yn$2.exports.default = yn$1;
  19575. const nativeModule = require$$0__default$5;
  19576. const path$j = path__default;
  19577. const fs$k = fs__default;
  19578. function createRequire (filename) {
  19579. // Fallback to process.cwd() if no filename passed
  19580. if (!filename) {
  19581. filename = process.cwd();
  19582. }
  19583. // If filename is dir, createRequire goes with parent directory, so we need fakepath
  19584. if (isDir(filename)) {
  19585. filename = path$j.join(filename, 'index.js');
  19586. }
  19587. // Added in Node v12.2.0
  19588. if (nativeModule.createRequire) {
  19589. return nativeModule.createRequire(filename)
  19590. }
  19591. // Added in Node v10.12.0 and deprecated since Node v12.2.0
  19592. if (nativeModule.createRequireFromPath) {
  19593. return nativeModule.createRequireFromPath(filename)
  19594. }
  19595. // Polyfill
  19596. return _createRequire(filename)
  19597. }
  19598. // Polyfill
  19599. function _createRequire (filename) {
  19600. const mod = new nativeModule.Module(filename, null);
  19601. mod.filename = filename;
  19602. mod.paths = nativeModule.Module._nodeModulePaths(path$j.dirname(filename));
  19603. mod._compile('module.exports = require;', filename);
  19604. return mod.exports
  19605. }
  19606. function isDir (path) {
  19607. try {
  19608. const stat = fs$k.lstatSync(path);
  19609. return stat.isDirectory()
  19610. } catch (e) {
  19611. // lstatSync throws an error if path doesn't exist
  19612. return false
  19613. }
  19614. }
  19615. var createRequire_1 = createRequire;
  19616. var _a;
  19617. Object.defineProperty(util$7, "__esModule", { value: true });
  19618. util$7.trace = util$7.cachedLookup = util$7.hasOwnProperty = util$7.normalizeSlashes = util$7.parse = util$7.split = util$7.assign = util$7.yn = util$7.createRequire = void 0;
  19619. const module_1 = require$$0__default$5;
  19620. const ynModule = yn$2.exports;
  19621. /** @internal */
  19622. util$7.createRequire = (_a = module_1.createRequire !== null && module_1.createRequire !== void 0 ? module_1.createRequire : module_1.createRequireFromPath) !== null && _a !== void 0 ? _a : createRequire_1;
  19623. /**
  19624. * Wrapper around yn module that returns `undefined` instead of `null`.
  19625. * This is implemented by yn v4, but we're staying on v3 to avoid v4's node 10 requirement.
  19626. * @internal
  19627. */
  19628. function yn(value) {
  19629. var _a;
  19630. return (_a = ynModule(value)) !== null && _a !== void 0 ? _a : undefined;
  19631. }
  19632. util$7.yn = yn;
  19633. /**
  19634. * Like `Object.assign`, but ignores `undefined` properties.
  19635. *
  19636. * @internal
  19637. */
  19638. function assign(initialValue, ...sources) {
  19639. for (const source of sources) {
  19640. for (const key of Object.keys(source)) {
  19641. const value = source[key];
  19642. if (value !== undefined)
  19643. initialValue[key] = value;
  19644. }
  19645. }
  19646. return initialValue;
  19647. }
  19648. util$7.assign = assign;
  19649. /**
  19650. * Split a string array of values.
  19651. * @internal
  19652. */
  19653. function split(value) {
  19654. return typeof value === 'string' ? value.split(/ *, */g) : undefined;
  19655. }
  19656. util$7.split = split;
  19657. /**
  19658. * Parse a string as JSON.
  19659. * @internal
  19660. */
  19661. function parse$e(value) {
  19662. return typeof value === 'string' ? JSON.parse(value) : undefined;
  19663. }
  19664. util$7.parse = parse$e;
  19665. const directorySeparator$1 = '/';
  19666. const backslashRegExp = /\\/g;
  19667. /**
  19668. * Replace backslashes with forward slashes.
  19669. * @internal
  19670. */
  19671. function normalizeSlashes$1(value) {
  19672. return value.replace(backslashRegExp, directorySeparator$1);
  19673. }
  19674. util$7.normalizeSlashes = normalizeSlashes$1;
  19675. /**
  19676. * Safe `hasOwnProperty`
  19677. * @internal
  19678. */
  19679. function hasOwnProperty$2(object, property) {
  19680. return Object.prototype.hasOwnProperty.call(object, property);
  19681. }
  19682. util$7.hasOwnProperty = hasOwnProperty$2;
  19683. /**
  19684. * Cached fs operation wrapper.
  19685. */
  19686. function cachedLookup(fn) {
  19687. const cache = new Map();
  19688. return (arg) => {
  19689. if (!cache.has(arg)) {
  19690. const v = fn(arg);
  19691. cache.set(arg, v);
  19692. return v;
  19693. }
  19694. return cache.get(arg);
  19695. };
  19696. }
  19697. util$7.cachedLookup = cachedLookup;
  19698. /**
  19699. * We do not support ts's `trace` option yet. In the meantime, rather than omit
  19700. * `trace` options in hosts, I am using this placeholder.
  19701. */
  19702. function trace(s) { }
  19703. util$7.trace = trace;
  19704. var configuration = {};
  19705. var tsInternals = {};
  19706. Object.defineProperty(tsInternals, "__esModule", { value: true });
  19707. tsInternals.getPatternFromSpec = tsInternals.createTsInternals = void 0;
  19708. const path_1$2 = path__default;
  19709. const util_1$2 = util$7;
  19710. /** @internal */
  19711. tsInternals.createTsInternals = util_1$2.cachedLookup(createTsInternalsUncached);
  19712. /**
  19713. * Given a reference to the TS compiler, return some TS internal functions that we
  19714. * could not or did not want to grab off the `ts` object.
  19715. * These have been copy-pasted from TS's source and tweaked as necessary.
  19716. *
  19717. * NOTE: This factory returns *only* functions which need a reference to the TS
  19718. * compiler. Other functions do not need a reference to the TS compiler so are
  19719. * exported directly from this file.
  19720. */
  19721. function createTsInternalsUncached(_ts) {
  19722. const ts = _ts;
  19723. /**
  19724. * Copied from:
  19725. * https://github.com/microsoft/TypeScript/blob/v4.3.2/src/compiler/commandLineParser.ts#L2821-L2846
  19726. */
  19727. function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
  19728. extendedConfig = util_1$2.normalizeSlashes(extendedConfig);
  19729. if (isRootedDiskPath(extendedConfig) ||
  19730. startsWith(extendedConfig, './') ||
  19731. startsWith(extendedConfig, '../')) {
  19732. let extendedConfigPath = getNormalizedAbsolutePath(extendedConfig, basePath);
  19733. if (!host.fileExists(extendedConfigPath) &&
  19734. !endsWith(extendedConfigPath, ts.Extension.Json)) {
  19735. extendedConfigPath = `${extendedConfigPath}.json`;
  19736. if (!host.fileExists(extendedConfigPath)) {
  19737. errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
  19738. return undefined;
  19739. }
  19740. }
  19741. return extendedConfigPath;
  19742. }
  19743. // If the path isn't a rooted or relative path, resolve like a module
  19744. const resolved = ts.nodeModuleNameResolver(extendedConfig, combinePaths(basePath, 'tsconfig.json'), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host,
  19745. /*cache*/ undefined,
  19746. /*projectRefs*/ undefined,
  19747. /*lookupConfig*/ true);
  19748. if (resolved.resolvedModule) {
  19749. return resolved.resolvedModule.resolvedFileName;
  19750. }
  19751. errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
  19752. return undefined;
  19753. }
  19754. return { getExtendsConfigPath };
  19755. }
  19756. // These functions have alternative implementation to avoid copying too much from TS
  19757. function isRootedDiskPath(path) {
  19758. return path_1$2.isAbsolute(path);
  19759. }
  19760. function combinePaths(path, ...paths) {
  19761. return util_1$2.normalizeSlashes(path_1$2.resolve(path, ...paths.filter((path) => path)));
  19762. }
  19763. function getNormalizedAbsolutePath(fileName, currentDirectory) {
  19764. return util_1$2.normalizeSlashes(currentDirectory != null
  19765. ? path_1$2.resolve(currentDirectory, fileName)
  19766. : path_1$2.resolve(fileName));
  19767. }
  19768. function startsWith(str, prefix) {
  19769. return str.lastIndexOf(prefix, 0) === 0;
  19770. }
  19771. function endsWith(str, suffix) {
  19772. const expectedPos = str.length - suffix.length;
  19773. return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
  19774. }
  19775. // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
  19776. // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
  19777. // proof.
  19778. const reservedCharacterPattern = /[^\w\s\/]/g;
  19779. /**
  19780. * @internal
  19781. * See also: getRegularExpressionForWildcard, which seems to do almost the same thing
  19782. */
  19783. function getPatternFromSpec(spec, basePath) {
  19784. const pattern = spec && getSubPatternFromSpec(spec, basePath, excludeMatcher);
  19785. return pattern && `^(${pattern})${'($|/)'}`;
  19786. }
  19787. tsInternals.getPatternFromSpec = getPatternFromSpec;
  19788. function getSubPatternFromSpec(spec, basePath, { singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter, }) {
  19789. let subpattern = '';
  19790. let hasWrittenComponent = false;
  19791. const components = getNormalizedPathComponents(spec, basePath);
  19792. const lastComponent = last(components);
  19793. // getNormalizedPathComponents includes the separator for the root component.
  19794. // We need to remove to create our regex correctly.
  19795. components[0] = removeTrailingDirectorySeparator(components[0]);
  19796. if (isImplicitGlob(lastComponent)) {
  19797. components.push('**', '*');
  19798. }
  19799. let optionalCount = 0;
  19800. for (let component of components) {
  19801. if (component === '**') {
  19802. subpattern += doubleAsteriskRegexFragment;
  19803. }
  19804. else {
  19805. if (hasWrittenComponent) {
  19806. subpattern += directorySeparator;
  19807. }
  19808. subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
  19809. }
  19810. hasWrittenComponent = true;
  19811. }
  19812. while (optionalCount > 0) {
  19813. subpattern += ')?';
  19814. optionalCount--;
  19815. }
  19816. return subpattern;
  19817. }
  19818. const excludeMatcher = {
  19819. singleAsteriskRegexFragment: '[^/]*',
  19820. doubleAsteriskRegexFragment: '(/.+?)?',
  19821. replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment),
  19822. };
  19823. function getNormalizedPathComponents(path, currentDirectory) {
  19824. return reducePathComponents(getPathComponents(path, currentDirectory));
  19825. }
  19826. function getPathComponents(path, currentDirectory = '') {
  19827. path = combinePaths(currentDirectory, path);
  19828. return pathComponents(path, getRootLength(path));
  19829. }
  19830. function reducePathComponents(components) {
  19831. if (!some(components))
  19832. return [];
  19833. const reduced = [components[0]];
  19834. for (let i = 1; i < components.length; i++) {
  19835. const component = components[i];
  19836. if (!component)
  19837. continue;
  19838. if (component === '.')
  19839. continue;
  19840. if (component === '..') {
  19841. if (reduced.length > 1) {
  19842. if (reduced[reduced.length - 1] !== '..') {
  19843. reduced.pop();
  19844. continue;
  19845. }
  19846. }
  19847. else if (reduced[0])
  19848. continue;
  19849. }
  19850. reduced.push(component);
  19851. }
  19852. return reduced;
  19853. }
  19854. function getRootLength(path) {
  19855. const rootLength = getEncodedRootLength(path);
  19856. return rootLength < 0 ? ~rootLength : rootLength;
  19857. }
  19858. function getEncodedRootLength(path) {
  19859. if (!path)
  19860. return 0;
  19861. const ch0 = path.charCodeAt(0);
  19862. // POSIX or UNC
  19863. if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
  19864. if (path.charCodeAt(1) !== ch0)
  19865. return 1; // POSIX: "/" (or non-normalized "\")
  19866. const p1 = path.indexOf(ch0 === 47 /* slash */ ? directorySeparator : altDirectorySeparator, 2);
  19867. if (p1 < 0)
  19868. return path.length; // UNC: "//server" or "\\server"
  19869. return p1 + 1; // UNC: "//server/" or "\\server\"
  19870. }
  19871. // DOS
  19872. if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
  19873. const ch2 = path.charCodeAt(2);
  19874. if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
  19875. return 3; // DOS: "c:/" or "c:\"
  19876. if (path.length === 2)
  19877. return 2; // DOS: "c:" (but not "c:d")
  19878. }
  19879. // URL
  19880. const schemeEnd = path.indexOf(urlSchemeSeparator);
  19881. if (schemeEnd !== -1) {
  19882. const authorityStart = schemeEnd + urlSchemeSeparator.length;
  19883. const authorityEnd = path.indexOf(directorySeparator, authorityStart);
  19884. if (authorityEnd !== -1) {
  19885. // URL: "file:///", "file://server/", "file://server/path"
  19886. // For local "file" URLs, include the leading DOS volume (if present).
  19887. // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
  19888. // special case interpreted as "the machine from which the URL is being interpreted".
  19889. const scheme = path.slice(0, schemeEnd);
  19890. const authority = path.slice(authorityStart, authorityEnd);
  19891. if (scheme === 'file' &&
  19892. (authority === '' || authority === 'localhost') &&
  19893. isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
  19894. const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
  19895. if (volumeSeparatorEnd !== -1) {
  19896. if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
  19897. // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
  19898. return ~(volumeSeparatorEnd + 1);
  19899. }
  19900. if (volumeSeparatorEnd === path.length) {
  19901. // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
  19902. // but not "file:///c:d" or "file:///c%3ad"
  19903. return ~volumeSeparatorEnd;
  19904. }
  19905. }
  19906. }
  19907. return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
  19908. }
  19909. return ~path.length; // URL: "file://server", "http://server"
  19910. }
  19911. // relative
  19912. return 0;
  19913. }
  19914. function hasTrailingDirectorySeparator(path) {
  19915. return (path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)));
  19916. }
  19917. function isAnyDirectorySeparator(charCode) {
  19918. return (charCode === 47 /* slash */ || charCode === 92 /* backslash */);
  19919. }
  19920. function removeTrailingDirectorySeparator(path) {
  19921. if (hasTrailingDirectorySeparator(path)) {
  19922. return path.substr(0, path.length - 1);
  19923. }
  19924. return path;
  19925. }
  19926. const directorySeparator = '/';
  19927. const altDirectorySeparator = '\\';
  19928. const urlSchemeSeparator = '://';
  19929. function isVolumeCharacter(charCode) {
  19930. return ((charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
  19931. (charCode >= 65 /* A */ && charCode <= 90 /* Z */));
  19932. }
  19933. function getFileUrlVolumeSeparatorEnd(url, start) {
  19934. const ch0 = url.charCodeAt(start);
  19935. if (ch0 === 58 /* colon */)
  19936. return start + 1;
  19937. if (ch0 === 37 /* percent */ &&
  19938. url.charCodeAt(start + 1) === 51 /* _3 */) {
  19939. const ch2 = url.charCodeAt(start + 2);
  19940. if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
  19941. return start + 3;
  19942. }
  19943. return -1;
  19944. }
  19945. function some(array, predicate) {
  19946. if (array) {
  19947. if (predicate) {
  19948. for (const v of array) {
  19949. if (predicate(v)) {
  19950. return true;
  19951. }
  19952. }
  19953. }
  19954. else {
  19955. return array.length > 0;
  19956. }
  19957. }
  19958. return false;
  19959. }
  19960. function pathComponents(path, rootLength) {
  19961. const root = path.substring(0, rootLength);
  19962. const rest = path.substring(rootLength).split(directorySeparator);
  19963. if (rest.length && !lastOrUndefined(rest))
  19964. rest.pop();
  19965. return [root, ...rest];
  19966. }
  19967. function lastOrUndefined(array) {
  19968. return array.length === 0 ? undefined : array[array.length - 1];
  19969. }
  19970. function last(array) {
  19971. // Debug.assert(array.length !== 0);
  19972. return array[array.length - 1];
  19973. }
  19974. function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
  19975. return match === '*'
  19976. ? singleAsteriskRegexFragment
  19977. : match === '?'
  19978. ? '[^/]'
  19979. : '\\' + match;
  19980. }
  19981. /**
  19982. * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
  19983. * and does not contain any glob characters itself.
  19984. */
  19985. function isImplicitGlob(lastPathComponent) {
  19986. return !/[.*?]/.test(lastPathComponent);
  19987. }
  19988. var tsconfigs = {};
  19989. var $schema$3 = "https://json.schemastore.org/tsconfig";
  19990. var display$3 = "Node 16";
  19991. var compilerOptions$3 = {
  19992. lib: [
  19993. "es2021"
  19994. ],
  19995. module: "commonjs",
  19996. target: "es2021",
  19997. strict: true,
  19998. esModuleInterop: true,
  19999. skipLibCheck: true,
  20000. forceConsistentCasingInFileNames: true
  20001. };
  20002. var require$$0$3 = {
  20003. $schema: $schema$3,
  20004. display: display$3,
  20005. compilerOptions: compilerOptions$3
  20006. };
  20007. var $schema$2 = "https://json.schemastore.org/tsconfig";
  20008. var display$2 = "Node 14";
  20009. var compilerOptions$2 = {
  20010. lib: [
  20011. "es2020"
  20012. ],
  20013. module: "commonjs",
  20014. target: "es2020",
  20015. strict: true,
  20016. esModuleInterop: true,
  20017. skipLibCheck: true,
  20018. forceConsistentCasingInFileNames: true
  20019. };
  20020. var require$$1 = {
  20021. $schema: $schema$2,
  20022. display: display$2,
  20023. compilerOptions: compilerOptions$2
  20024. };
  20025. var $schema$1 = "https://json.schemastore.org/tsconfig";
  20026. var display$1 = "Node 12";
  20027. var compilerOptions$1 = {
  20028. lib: [
  20029. "es2019",
  20030. "es2020.promise",
  20031. "es2020.bigint",
  20032. "es2020.string"
  20033. ],
  20034. module: "commonjs",
  20035. target: "es2019",
  20036. strict: true,
  20037. esModuleInterop: true,
  20038. skipLibCheck: true,
  20039. forceConsistentCasingInFileNames: true
  20040. };
  20041. var require$$2 = {
  20042. $schema: $schema$1,
  20043. display: display$1,
  20044. compilerOptions: compilerOptions$1
  20045. };
  20046. var $schema = "https://json.schemastore.org/tsconfig";
  20047. var display = "Node 10";
  20048. var compilerOptions = {
  20049. lib: [
  20050. "es2018"
  20051. ],
  20052. module: "commonjs",
  20053. target: "es2018",
  20054. strict: true,
  20055. esModuleInterop: true,
  20056. skipLibCheck: true,
  20057. forceConsistentCasingInFileNames: true
  20058. };
  20059. var require$$3 = {
  20060. $schema: $schema,
  20061. display: display,
  20062. compilerOptions: compilerOptions
  20063. };
  20064. Object.defineProperty(tsconfigs, "__esModule", { value: true });
  20065. tsconfigs.getDefaultTsconfigJsonForNodeVersion = void 0;
  20066. const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
  20067. /**
  20068. * return parsed JSON of the bundled @tsconfig/bases config appropriate for the
  20069. * running version of nodejs
  20070. * @internal
  20071. */
  20072. function getDefaultTsconfigJsonForNodeVersion(ts) {
  20073. const tsInternal = ts;
  20074. if (nodeMajor >= 16) {
  20075. const config = require$$0$3;
  20076. if (configCompatible(config))
  20077. return config;
  20078. }
  20079. if (nodeMajor >= 14) {
  20080. const config = require$$1;
  20081. if (configCompatible(config))
  20082. return config;
  20083. }
  20084. if (nodeMajor >= 12) {
  20085. const config = require$$2;
  20086. if (configCompatible(config))
  20087. return config;
  20088. }
  20089. return require$$3;
  20090. // Verify that tsconfig target and lib options are compatible with TypeScript compiler
  20091. function configCompatible(config) {
  20092. return (typeof ts.ScriptTarget[config.compilerOptions.target.toUpperCase()] === 'number' &&
  20093. tsInternal.libs &&
  20094. config.compilerOptions.lib.every((lib) => tsInternal.libs.includes(lib)));
  20095. }
  20096. }
  20097. tsconfigs.getDefaultTsconfigJsonForNodeVersion = getDefaultTsconfigJsonForNodeVersion;
  20098. var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
  20099. var t = {};
  20100. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  20101. t[p] = s[p];
  20102. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  20103. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  20104. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  20105. t[p[i]] = s[p[i]];
  20106. }
  20107. return t;
  20108. };
  20109. Object.defineProperty(configuration, "__esModule", { value: true });
  20110. configuration.readConfig = void 0;
  20111. const path_1$1 = path__default;
  20112. const index_1 = dist$1;
  20113. const ts_internals_1$1 = tsInternals;
  20114. const tsconfigs_1 = tsconfigs;
  20115. const util_1$1 = util$7;
  20116. /**
  20117. * TypeScript compiler option values required by `ts-node` which cannot be overridden.
  20118. */
  20119. const TS_NODE_COMPILER_OPTIONS = {
  20120. sourceMap: true,
  20121. inlineSourceMap: false,
  20122. inlineSources: true,
  20123. declaration: false,
  20124. noEmit: false,
  20125. outDir: '.ts-node',
  20126. };
  20127. /*
  20128. * Do post-processing on config options to support `ts-node`.
  20129. */
  20130. function fixConfig(ts, config) {
  20131. // Delete options that *should not* be passed through.
  20132. delete config.options.out;
  20133. delete config.options.outFile;
  20134. delete config.options.composite;
  20135. delete config.options.declarationDir;
  20136. delete config.options.declarationMap;
  20137. delete config.options.emitDeclarationOnly;
  20138. // Target ES5 output by default (instead of ES3).
  20139. if (config.options.target === undefined) {
  20140. config.options.target = ts.ScriptTarget.ES5;
  20141. }
  20142. // Target CommonJS modules by default (instead of magically switching to ES6 when the target is ES6).
  20143. if (config.options.module === undefined) {
  20144. config.options.module = ts.ModuleKind.CommonJS;
  20145. }
  20146. return config;
  20147. }
  20148. /**
  20149. * Load TypeScript configuration. Returns the parsed TypeScript config and
  20150. * any `ts-node` options specified in the config file.
  20151. *
  20152. * Even when a tsconfig.json is not loaded, this function still handles merging
  20153. * compilerOptions from various sources: API, environment variables, etc.
  20154. *
  20155. * @internal
  20156. */
  20157. function readConfig(cwd, ts, rawApiOptions) {
  20158. var _a, _b, _c;
  20159. // Ordered [a, b, c] where config a extends b extends c
  20160. const configChain = [];
  20161. let config = { compilerOptions: {} };
  20162. let basePath = cwd;
  20163. let configFilePath = undefined;
  20164. const projectSearchDir = path_1$1.resolve(cwd, (_a = rawApiOptions.projectSearchDir) !== null && _a !== void 0 ? _a : cwd);
  20165. const { fileExists = ts.sys.fileExists, readFile = ts.sys.readFile, skipProject = index_1.DEFAULTS.skipProject, project = index_1.DEFAULTS.project, } = rawApiOptions;
  20166. // Read project configuration when available.
  20167. if (!skipProject) {
  20168. configFilePath = project
  20169. ? path_1$1.resolve(cwd, project)
  20170. : ts.findConfigFile(projectSearchDir, fileExists);
  20171. if (configFilePath) {
  20172. let pathToNextConfigInChain = configFilePath;
  20173. const tsInternals = ts_internals_1$1.createTsInternals(ts);
  20174. const errors = [];
  20175. // Follow chain of "extends"
  20176. while (true) {
  20177. const result = ts.readConfigFile(pathToNextConfigInChain, readFile);
  20178. // Return diagnostics.
  20179. if (result.error) {
  20180. return {
  20181. configFilePath,
  20182. config: { errors: [result.error], fileNames: [], options: {} },
  20183. tsNodeOptionsFromTsconfig: {},
  20184. optionBasePaths: {},
  20185. };
  20186. }
  20187. const c = result.config;
  20188. const bp = path_1$1.dirname(pathToNextConfigInChain);
  20189. configChain.push({
  20190. config: c,
  20191. basePath: bp,
  20192. configPath: pathToNextConfigInChain,
  20193. });
  20194. if (c.extends == null)
  20195. break;
  20196. const resolvedExtendedConfigPath = tsInternals.getExtendsConfigPath(c.extends, {
  20197. fileExists,
  20198. readDirectory: ts.sys.readDirectory,
  20199. readFile,
  20200. useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
  20201. trace: util_1$1.trace,
  20202. }, bp, errors, ts.createCompilerDiagnostic);
  20203. if (errors.length) {
  20204. return {
  20205. configFilePath,
  20206. config: { errors, fileNames: [], options: {} },
  20207. tsNodeOptionsFromTsconfig: {},
  20208. optionBasePaths: {},
  20209. };
  20210. }
  20211. if (resolvedExtendedConfigPath == null)
  20212. break;
  20213. pathToNextConfigInChain = resolvedExtendedConfigPath;
  20214. }
  20215. ({ config, basePath } = configChain[0]);
  20216. }
  20217. }
  20218. // Merge and fix ts-node options that come from tsconfig.json(s)
  20219. const tsNodeOptionsFromTsconfig = {};
  20220. const optionBasePaths = {};
  20221. for (let i = configChain.length - 1; i >= 0; i--) {
  20222. const { config, basePath, configPath } = configChain[i];
  20223. const options = filterRecognizedTsConfigTsNodeOptions(config['ts-node'])
  20224. .recognized;
  20225. // Some options are relative to the config file, so must be converted to absolute paths here
  20226. if (options.require) {
  20227. // Modules are found relative to the tsconfig file, not the `dir` option
  20228. const tsconfigRelativeRequire = util_1$1.createRequire(configPath);
  20229. options.require = options.require.map((path) => tsconfigRelativeRequire.resolve(path));
  20230. }
  20231. if (options.scopeDir) {
  20232. options.scopeDir = path_1$1.resolve(basePath, options.scopeDir);
  20233. }
  20234. // Downstream code uses the basePath; we do not do that here.
  20235. if (options.moduleTypes) {
  20236. optionBasePaths.moduleTypes = basePath;
  20237. }
  20238. util_1$1.assign(tsNodeOptionsFromTsconfig, options);
  20239. }
  20240. // Remove resolution of "files".
  20241. const files = (_c = (_b = rawApiOptions.files) !== null && _b !== void 0 ? _b : tsNodeOptionsFromTsconfig.files) !== null && _c !== void 0 ? _c : index_1.DEFAULTS.files;
  20242. if (!files) {
  20243. config.files = [];
  20244. config.include = [];
  20245. }
  20246. // Only if a config file is *not* loaded, load an implicit configuration from @tsconfig/bases
  20247. const skipDefaultCompilerOptions = configFilePath != null;
  20248. const defaultCompilerOptionsForNodeVersion = skipDefaultCompilerOptions
  20249. ? undefined
  20250. : Object.assign(Object.assign({}, tsconfigs_1.getDefaultTsconfigJsonForNodeVersion(ts).compilerOptions), { types: ['node'] });
  20251. // Merge compilerOptions from all sources
  20252. config.compilerOptions = Object.assign({},
  20253. // automatically-applied options from @tsconfig/bases
  20254. defaultCompilerOptionsForNodeVersion,
  20255. // tsconfig.json "compilerOptions"
  20256. config.compilerOptions,
  20257. // from env var
  20258. index_1.DEFAULTS.compilerOptions,
  20259. // tsconfig.json "ts-node": "compilerOptions"
  20260. tsNodeOptionsFromTsconfig.compilerOptions,
  20261. // passed programmatically
  20262. rawApiOptions.compilerOptions,
  20263. // overrides required by ts-node, cannot be changed
  20264. TS_NODE_COMPILER_OPTIONS);
  20265. const fixedConfig = fixConfig(ts, ts.parseJsonConfigFileContent(config, {
  20266. fileExists,
  20267. readFile,
  20268. readDirectory: ts.sys.readDirectory,
  20269. useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
  20270. }, basePath, undefined, configFilePath));
  20271. return {
  20272. configFilePath,
  20273. config: fixedConfig,
  20274. tsNodeOptionsFromTsconfig,
  20275. optionBasePaths,
  20276. };
  20277. }
  20278. configuration.readConfig = readConfig;
  20279. /**
  20280. * Given the raw "ts-node" sub-object from a tsconfig, return an object with only the properties
  20281. * recognized by "ts-node"
  20282. */
  20283. function filterRecognizedTsConfigTsNodeOptions(jsonObject) {
  20284. if (jsonObject == null)
  20285. return { recognized: {}, unrecognized: {} };
  20286. const _a = jsonObject, { compiler, compilerHost, compilerOptions, emit, files, ignore, ignoreDiagnostics, logError, preferTsExts, pretty, require, skipIgnore, transpileOnly, typeCheck, transpiler, scope, scopeDir, moduleTypes, experimentalReplAwait } = _a, unrecognized = __rest(_a, ["compiler", "compilerHost", "compilerOptions", "emit", "files", "ignore", "ignoreDiagnostics", "logError", "preferTsExts", "pretty", "require", "skipIgnore", "transpileOnly", "typeCheck", "transpiler", "scope", "scopeDir", "moduleTypes", "experimentalReplAwait"]);
  20287. const filteredTsConfigOptions = {
  20288. compiler,
  20289. compilerHost,
  20290. compilerOptions,
  20291. emit,
  20292. experimentalReplAwait,
  20293. files,
  20294. ignore,
  20295. ignoreDiagnostics,
  20296. logError,
  20297. preferTsExts,
  20298. pretty,
  20299. require,
  20300. skipIgnore,
  20301. transpileOnly,
  20302. typeCheck,
  20303. transpiler,
  20304. scope,
  20305. scopeDir,
  20306. moduleTypes,
  20307. };
  20308. return { recognized: filteredTsConfigOptions, unrecognized };
  20309. }
  20310. var moduleTypeClassifier = {};
  20311. Object.defineProperty(moduleTypeClassifier, "__esModule", { value: true });
  20312. moduleTypeClassifier.createModuleTypeClassifier = void 0;
  20313. const ts_internals_1 = tsInternals;
  20314. const util_1 = util$7;
  20315. /**
  20316. * @internal
  20317. * May receive non-normalized options -- basePath and patterns -- and will normalize them
  20318. * internally.
  20319. * However, calls to `classifyModule` must pass pre-normalized paths!
  20320. */
  20321. function createModuleTypeClassifier(options) {
  20322. const { patterns, basePath: _basePath } = options;
  20323. const basePath = _basePath !== undefined
  20324. ? util_1.normalizeSlashes(_basePath).replace(/\/$/, '')
  20325. : undefined;
  20326. const patternTypePairs = Object.entries(patterns !== null && patterns !== void 0 ? patterns : []).map(([_pattern, type]) => {
  20327. const pattern = util_1.normalizeSlashes(_pattern);
  20328. return { pattern: parsePattern(basePath, pattern), type };
  20329. });
  20330. const classifications = {
  20331. package: {
  20332. moduleType: 'package',
  20333. },
  20334. cjs: {
  20335. moduleType: 'cjs',
  20336. },
  20337. esm: {
  20338. moduleType: 'esm',
  20339. },
  20340. };
  20341. const auto = classifications.package;
  20342. // Passed path must be normalized!
  20343. function classifyModuleNonCached(path) {
  20344. const matched = matchPatterns$1(patternTypePairs, (_) => _.pattern, path);
  20345. if (matched)
  20346. return classifications[matched.type];
  20347. return auto;
  20348. }
  20349. const classifyModule = util_1.cachedLookup(classifyModuleNonCached);
  20350. function classifyModuleAuto(path) {
  20351. return auto;
  20352. }
  20353. return {
  20354. classifyModule: patternTypePairs.length
  20355. ? classifyModule
  20356. : classifyModuleAuto,
  20357. };
  20358. }
  20359. moduleTypeClassifier.createModuleTypeClassifier = createModuleTypeClassifier;
  20360. function parsePattern(basePath, patternString) {
  20361. const pattern = ts_internals_1.getPatternFromSpec(patternString, basePath);
  20362. return pattern !== undefined ? new RegExp(pattern) : /(?:)/;
  20363. }
  20364. function matchPatterns$1(objects, getPattern, candidate) {
  20365. for (let i = objects.length - 1; i >= 0; i--) {
  20366. const object = objects[i];
  20367. const pattern = getPattern(object);
  20368. if (pattern === null || pattern === void 0 ? void 0 : pattern.test(candidate)) {
  20369. return object;
  20370. }
  20371. }
  20372. }
  20373. var resolverFunctions = {};
  20374. Object.defineProperty(resolverFunctions, "__esModule", { value: true });
  20375. resolverFunctions.createResolverFunctions = void 0;
  20376. const path_1 = path__default;
  20377. /**
  20378. * @internal
  20379. * In a factory because these are shared across both CompilerHost and LanguageService codepaths
  20380. */
  20381. function createResolverFunctions(kwargs) {
  20382. const { serviceHost, ts, config, cwd, getCanonicalFileName, configFilePath, } = kwargs;
  20383. const moduleResolutionCache = ts.createModuleResolutionCache(cwd, getCanonicalFileName, config.options);
  20384. const knownInternalFilenames = new Set();
  20385. /** "Buckets" (module directories) whose contents should be marked "internal" */
  20386. const internalBuckets = new Set();
  20387. // Get bucket for a source filename. Bucket is the containing `./node_modules/*/` directory
  20388. // For '/project/node_modules/foo/node_modules/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/bar/'
  20389. // For '/project/node_modules/foo/node_modules/@scope/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/@scope/bar/'
  20390. const moduleBucketRe = /.*\/node_modules\/(?:@[^\/]+\/)?[^\/]+\//;
  20391. function getModuleBucket(filename) {
  20392. const find = moduleBucketRe.exec(filename);
  20393. if (find)
  20394. return find[0];
  20395. return '';
  20396. }
  20397. // Mark that this file and all siblings in its bucket should be "internal"
  20398. function markBucketOfFilenameInternal(filename) {
  20399. internalBuckets.add(getModuleBucket(filename));
  20400. }
  20401. function isFileInInternalBucket(filename) {
  20402. return internalBuckets.has(getModuleBucket(filename));
  20403. }
  20404. function isFileKnownToBeInternal(filename) {
  20405. return knownInternalFilenames.has(filename);
  20406. }
  20407. /**
  20408. * If we need to emit JS for a file, force TS to consider it non-external
  20409. */
  20410. const fixupResolvedModule = (resolvedModule) => {
  20411. const { resolvedFileName } = resolvedModule;
  20412. if (resolvedFileName === undefined)
  20413. return;
  20414. // .ts is always switched to internal
  20415. // .js is switched on-demand
  20416. if (resolvedModule.isExternalLibraryImport &&
  20417. ((resolvedFileName.endsWith('.ts') &&
  20418. !resolvedFileName.endsWith('.d.ts')) ||
  20419. isFileKnownToBeInternal(resolvedFileName) ||
  20420. isFileInInternalBucket(resolvedFileName))) {
  20421. resolvedModule.isExternalLibraryImport = false;
  20422. }
  20423. if (!resolvedModule.isExternalLibraryImport) {
  20424. knownInternalFilenames.add(resolvedFileName);
  20425. }
  20426. };
  20427. /*
  20428. * NOTE:
  20429. * Older ts versions do not pass `redirectedReference` nor `options`.
  20430. * We must pass `redirectedReference` to newer ts versions, but cannot rely on `options`, hence the weird argument name
  20431. */
  20432. const resolveModuleNames = (moduleNames, containingFile, reusedNames, redirectedReference, optionsOnlyWithNewerTsVersions) => {
  20433. return moduleNames.map((moduleName) => {
  20434. const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, config.options, serviceHost, moduleResolutionCache, redirectedReference);
  20435. if (resolvedModule) {
  20436. fixupResolvedModule(resolvedModule);
  20437. }
  20438. return resolvedModule;
  20439. });
  20440. };
  20441. // language service never calls this, but TS docs recommend that we implement it
  20442. const getResolvedModuleWithFailedLookupLocationsFromCache = (moduleName, containingFile) => {
  20443. const ret = ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
  20444. if (ret && ret.resolvedModule) {
  20445. fixupResolvedModule(ret.resolvedModule);
  20446. }
  20447. return ret;
  20448. };
  20449. const resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile, redirectedReference, options) => {
  20450. // Note: seems to be called with empty typeDirectiveNames array for all files.
  20451. return typeDirectiveNames.map((typeDirectiveName) => {
  20452. let { resolvedTypeReferenceDirective } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, config.options, serviceHost, redirectedReference);
  20453. if (typeDirectiveName === 'node' && !resolvedTypeReferenceDirective) {
  20454. // Resolve @types/node relative to project first, then __dirname (copy logic from elsewhere / refactor into reusable function)
  20455. let typesNodePackageJsonPath;
  20456. try {
  20457. typesNodePackageJsonPath = require.resolve('@types/node/package.json', {
  20458. paths: [configFilePath !== null && configFilePath !== void 0 ? configFilePath : cwd, __dirname],
  20459. });
  20460. }
  20461. catch (_a) { } // gracefully do nothing when @types/node is not installed for any reason
  20462. if (typesNodePackageJsonPath) {
  20463. const typeRoots = [path_1.resolve(typesNodePackageJsonPath, '../..')];
  20464. ({
  20465. resolvedTypeReferenceDirective,
  20466. } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, Object.assign(Object.assign({}, config.options), { typeRoots }), serviceHost, redirectedReference));
  20467. }
  20468. }
  20469. if (resolvedTypeReferenceDirective) {
  20470. fixupResolvedModule(resolvedTypeReferenceDirective);
  20471. }
  20472. return resolvedTypeReferenceDirective;
  20473. });
  20474. };
  20475. return {
  20476. resolveModuleNames,
  20477. getResolvedModuleWithFailedLookupLocationsFromCache,
  20478. resolveTypeReferenceDirectives,
  20479. isFileKnownToBeInternal,
  20480. markBucketOfFilenameInternal,
  20481. };
  20482. }
  20483. resolverFunctions.createResolverFunctions = createResolverFunctions;
  20484. var repl = {};
  20485. function Diff() {}
  20486. Diff.prototype = {
  20487. diff: function diff(oldString, newString) {
  20488. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  20489. var callback = options.callback;
  20490. if (typeof options === 'function') {
  20491. callback = options;
  20492. options = {};
  20493. }
  20494. this.options = options;
  20495. var self = this;
  20496. function done(value) {
  20497. if (callback) {
  20498. setTimeout(function () {
  20499. callback(undefined, value);
  20500. }, 0);
  20501. return true;
  20502. } else {
  20503. return value;
  20504. }
  20505. } // Allow subclasses to massage the input prior to running
  20506. oldString = this.castInput(oldString);
  20507. newString = this.castInput(newString);
  20508. oldString = this.removeEmpty(this.tokenize(oldString));
  20509. newString = this.removeEmpty(this.tokenize(newString));
  20510. var newLen = newString.length,
  20511. oldLen = oldString.length;
  20512. var editLength = 1;
  20513. var maxEditLength = newLen + oldLen;
  20514. var bestPath = [{
  20515. newPos: -1,
  20516. components: []
  20517. }]; // Seed editLength = 0, i.e. the content starts with the same values
  20518. var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
  20519. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  20520. // Identity per the equality and tokenizer
  20521. return done([{
  20522. value: this.join(newString),
  20523. count: newString.length
  20524. }]);
  20525. } // Main worker method. checks all permutations of a given edit length for acceptance.
  20526. function execEditLength() {
  20527. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  20528. var basePath = void 0;
  20529. var addPath = bestPath[diagonalPath - 1],
  20530. removePath = bestPath[diagonalPath + 1],
  20531. _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  20532. if (addPath) {
  20533. // No one else is going to attempt to use this value, clear it
  20534. bestPath[diagonalPath - 1] = undefined;
  20535. }
  20536. var canAdd = addPath && addPath.newPos + 1 < newLen,
  20537. canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
  20538. if (!canAdd && !canRemove) {
  20539. // If this path is a terminal then prune
  20540. bestPath[diagonalPath] = undefined;
  20541. continue;
  20542. } // Select the diagonal that we want to branch from. We select the prior
  20543. // path whose position in the new string is the farthest from the origin
  20544. // and does not pass the bounds of the diff graph
  20545. if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
  20546. basePath = clonePath(removePath);
  20547. self.pushComponent(basePath.components, undefined, true);
  20548. } else {
  20549. basePath = addPath; // No need to clone, we've pulled it from the list
  20550. basePath.newPos++;
  20551. self.pushComponent(basePath.components, true, undefined);
  20552. }
  20553. _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
  20554. if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
  20555. return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
  20556. } else {
  20557. // Otherwise track this path as a potential candidate and continue.
  20558. bestPath[diagonalPath] = basePath;
  20559. }
  20560. }
  20561. editLength++;
  20562. } // Performs the length of edit iteration. Is a bit fugly as this has to support the
  20563. // sync and async mode which is never fun. Loops over execEditLength until a value
  20564. // is produced.
  20565. if (callback) {
  20566. (function exec() {
  20567. setTimeout(function () {
  20568. // This should not happen, but we want to be safe.
  20569. /* istanbul ignore next */
  20570. if (editLength > maxEditLength) {
  20571. return callback();
  20572. }
  20573. if (!execEditLength()) {
  20574. exec();
  20575. }
  20576. }, 0);
  20577. })();
  20578. } else {
  20579. while (editLength <= maxEditLength) {
  20580. var ret = execEditLength();
  20581. if (ret) {
  20582. return ret;
  20583. }
  20584. }
  20585. }
  20586. },
  20587. pushComponent: function pushComponent(components, added, removed) {
  20588. var last = components[components.length - 1];
  20589. if (last && last.added === added && last.removed === removed) {
  20590. // We need to clone here as the component clone operation is just
  20591. // as shallow array clone
  20592. components[components.length - 1] = {
  20593. count: last.count + 1,
  20594. added: added,
  20595. removed: removed
  20596. };
  20597. } else {
  20598. components.push({
  20599. count: 1,
  20600. added: added,
  20601. removed: removed
  20602. });
  20603. }
  20604. },
  20605. extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
  20606. var newLen = newString.length,
  20607. oldLen = oldString.length,
  20608. newPos = basePath.newPos,
  20609. oldPos = newPos - diagonalPath,
  20610. commonCount = 0;
  20611. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
  20612. newPos++;
  20613. oldPos++;
  20614. commonCount++;
  20615. }
  20616. if (commonCount) {
  20617. basePath.components.push({
  20618. count: commonCount
  20619. });
  20620. }
  20621. basePath.newPos = newPos;
  20622. return oldPos;
  20623. },
  20624. equals: function equals(left, right) {
  20625. if (this.options.comparator) {
  20626. return this.options.comparator(left, right);
  20627. } else {
  20628. return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
  20629. }
  20630. },
  20631. removeEmpty: function removeEmpty(array) {
  20632. var ret = [];
  20633. for (var i = 0; i < array.length; i++) {
  20634. if (array[i]) {
  20635. ret.push(array[i]);
  20636. }
  20637. }
  20638. return ret;
  20639. },
  20640. castInput: function castInput(value) {
  20641. return value;
  20642. },
  20643. tokenize: function tokenize(value) {
  20644. return value.split('');
  20645. },
  20646. join: function join(chars) {
  20647. return chars.join('');
  20648. }
  20649. };
  20650. function buildValues(diff, components, newString, oldString, useLongestToken) {
  20651. var componentPos = 0,
  20652. componentLen = components.length,
  20653. newPos = 0,
  20654. oldPos = 0;
  20655. for (; componentPos < componentLen; componentPos++) {
  20656. var component = components[componentPos];
  20657. if (!component.removed) {
  20658. if (!component.added && useLongestToken) {
  20659. var value = newString.slice(newPos, newPos + component.count);
  20660. value = value.map(function (value, i) {
  20661. var oldValue = oldString[oldPos + i];
  20662. return oldValue.length > value.length ? oldValue : value;
  20663. });
  20664. component.value = diff.join(value);
  20665. } else {
  20666. component.value = diff.join(newString.slice(newPos, newPos + component.count));
  20667. }
  20668. newPos += component.count; // Common case
  20669. if (!component.added) {
  20670. oldPos += component.count;
  20671. }
  20672. } else {
  20673. component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
  20674. oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
  20675. // The diffing algorithm is tied to add then remove output and this is the simplest
  20676. // route to get the desired output with minimal overhead.
  20677. if (componentPos && components[componentPos - 1].added) {
  20678. var tmp = components[componentPos - 1];
  20679. components[componentPos - 1] = components[componentPos];
  20680. components[componentPos] = tmp;
  20681. }
  20682. }
  20683. } // Special case handle for when one terminal is ignored (i.e. whitespace).
  20684. // For this case we merge the terminal into the prior string and drop the change.
  20685. // This is only available for string mode.
  20686. var lastComponent = components[componentLen - 1];
  20687. if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
  20688. components[componentLen - 2].value += lastComponent.value;
  20689. components.pop();
  20690. }
  20691. return components;
  20692. }
  20693. function clonePath(path) {
  20694. return {
  20695. newPos: path.newPos,
  20696. components: path.components.slice(0)
  20697. };
  20698. }
  20699. var characterDiff = new Diff();
  20700. function diffChars(oldStr, newStr, options) {
  20701. return characterDiff.diff(oldStr, newStr, options);
  20702. }
  20703. function generateOptions(options, defaults) {
  20704. if (typeof options === 'function') {
  20705. defaults.callback = options;
  20706. } else if (options) {
  20707. for (var name in options) {
  20708. /* istanbul ignore else */
  20709. if (options.hasOwnProperty(name)) {
  20710. defaults[name] = options[name];
  20711. }
  20712. }
  20713. }
  20714. return defaults;
  20715. }
  20716. //
  20717. // Ranges and exceptions:
  20718. // Latin-1 Supplement, 0080–00FF
  20719. // - U+00D7 × Multiplication sign
  20720. // - U+00F7 ÷ Division sign
  20721. // Latin Extended-A, 0100–017F
  20722. // Latin Extended-B, 0180–024F
  20723. // IPA Extensions, 0250–02AF
  20724. // Spacing Modifier Letters, 02B0–02FF
  20725. // - U+02C7 ˇ &#711; Caron
  20726. // - U+02D8 ˘ &#728; Breve
  20727. // - U+02D9 ˙ &#729; Dot Above
  20728. // - U+02DA ˚ &#730; Ring Above
  20729. // - U+02DB ˛ &#731; Ogonek
  20730. // - U+02DC ˜ &#732; Small Tilde
  20731. // - U+02DD ˝ &#733; Double Acute Accent
  20732. // Latin Extended Additional, 1E00–1EFF
  20733. var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
  20734. var reWhitespace = /\S/;
  20735. var wordDiff = new Diff();
  20736. wordDiff.equals = function (left, right) {
  20737. if (this.options.ignoreCase) {
  20738. left = left.toLowerCase();
  20739. right = right.toLowerCase();
  20740. }
  20741. return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
  20742. };
  20743. wordDiff.tokenize = function (value) {
  20744. var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
  20745. for (var i = 0; i < tokens.length - 1; i++) {
  20746. // If we have an empty string in the next field and we have only word chars before and after, merge
  20747. if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
  20748. tokens[i] += tokens[i + 2];
  20749. tokens.splice(i + 1, 2);
  20750. i--;
  20751. }
  20752. }
  20753. return tokens;
  20754. };
  20755. function diffWords(oldStr, newStr, options) {
  20756. options = generateOptions(options, {
  20757. ignoreWhitespace: true
  20758. });
  20759. return wordDiff.diff(oldStr, newStr, options);
  20760. }
  20761. function diffWordsWithSpace(oldStr, newStr, options) {
  20762. return wordDiff.diff(oldStr, newStr, options);
  20763. }
  20764. var lineDiff = new Diff();
  20765. lineDiff.tokenize = function (value) {
  20766. var retLines = [],
  20767. linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
  20768. if (!linesAndNewlines[linesAndNewlines.length - 1]) {
  20769. linesAndNewlines.pop();
  20770. } // Merge the content and line separators into single tokens
  20771. for (var i = 0; i < linesAndNewlines.length; i++) {
  20772. var line = linesAndNewlines[i];
  20773. if (i % 2 && !this.options.newlineIsToken) {
  20774. retLines[retLines.length - 1] += line;
  20775. } else {
  20776. if (this.options.ignoreWhitespace) {
  20777. line = line.trim();
  20778. }
  20779. retLines.push(line);
  20780. }
  20781. }
  20782. return retLines;
  20783. };
  20784. function diffLines(oldStr, newStr, callback) {
  20785. return lineDiff.diff(oldStr, newStr, callback);
  20786. }
  20787. function diffTrimmedLines(oldStr, newStr, callback) {
  20788. var options = generateOptions(callback, {
  20789. ignoreWhitespace: true
  20790. });
  20791. return lineDiff.diff(oldStr, newStr, options);
  20792. }
  20793. var sentenceDiff = new Diff();
  20794. sentenceDiff.tokenize = function (value) {
  20795. return value.split(/(\S.+?[.!?])(?=\s+|$)/);
  20796. };
  20797. function diffSentences(oldStr, newStr, callback) {
  20798. return sentenceDiff.diff(oldStr, newStr, callback);
  20799. }
  20800. var cssDiff = new Diff();
  20801. cssDiff.tokenize = function (value) {
  20802. return value.split(/([{}:;,]|\s+)/);
  20803. };
  20804. function diffCss(oldStr, newStr, callback) {
  20805. return cssDiff.diff(oldStr, newStr, callback);
  20806. }
  20807. function _typeof(obj) {
  20808. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  20809. _typeof = function (obj) {
  20810. return typeof obj;
  20811. };
  20812. } else {
  20813. _typeof = function (obj) {
  20814. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  20815. };
  20816. }
  20817. return _typeof(obj);
  20818. }
  20819. function _toConsumableArray(arr) {
  20820. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
  20821. }
  20822. function _arrayWithoutHoles(arr) {
  20823. if (Array.isArray(arr)) {
  20824. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  20825. return arr2;
  20826. }
  20827. }
  20828. function _iterableToArray(iter) {
  20829. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  20830. }
  20831. function _nonIterableSpread() {
  20832. throw new TypeError("Invalid attempt to spread non-iterable instance");
  20833. }
  20834. var objectPrototypeToString = Object.prototype.toString;
  20835. var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
  20836. // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
  20837. jsonDiff.useLongestToken = true;
  20838. jsonDiff.tokenize = lineDiff.tokenize;
  20839. jsonDiff.castInput = function (value) {
  20840. var _this$options = this.options,
  20841. undefinedReplacement = _this$options.undefinedReplacement,
  20842. _this$options$stringi = _this$options.stringifyReplacer,
  20843. stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
  20844. return typeof v === 'undefined' ? undefinedReplacement : v;
  20845. } : _this$options$stringi;
  20846. return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
  20847. };
  20848. jsonDiff.equals = function (left, right) {
  20849. return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
  20850. };
  20851. function diffJson(oldObj, newObj, options) {
  20852. return jsonDiff.diff(oldObj, newObj, options);
  20853. } // This function handles the presence of circular references by bailing out when encountering an
  20854. // object that is already on the "stack" of items being processed. Accepts an optional replacer
  20855. function canonicalize(obj, stack, replacementStack, replacer, key) {
  20856. stack = stack || [];
  20857. replacementStack = replacementStack || [];
  20858. if (replacer) {
  20859. obj = replacer(key, obj);
  20860. }
  20861. var i;
  20862. for (i = 0; i < stack.length; i += 1) {
  20863. if (stack[i] === obj) {
  20864. return replacementStack[i];
  20865. }
  20866. }
  20867. var canonicalizedObj;
  20868. if ('[object Array]' === objectPrototypeToString.call(obj)) {
  20869. stack.push(obj);
  20870. canonicalizedObj = new Array(obj.length);
  20871. replacementStack.push(canonicalizedObj);
  20872. for (i = 0; i < obj.length; i += 1) {
  20873. canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
  20874. }
  20875. stack.pop();
  20876. replacementStack.pop();
  20877. return canonicalizedObj;
  20878. }
  20879. if (obj && obj.toJSON) {
  20880. obj = obj.toJSON();
  20881. }
  20882. if (_typeof(obj) === 'object' && obj !== null) {
  20883. stack.push(obj);
  20884. canonicalizedObj = {};
  20885. replacementStack.push(canonicalizedObj);
  20886. var sortedKeys = [],
  20887. _key;
  20888. for (_key in obj) {
  20889. /* istanbul ignore else */
  20890. if (obj.hasOwnProperty(_key)) {
  20891. sortedKeys.push(_key);
  20892. }
  20893. }
  20894. sortedKeys.sort();
  20895. for (i = 0; i < sortedKeys.length; i += 1) {
  20896. _key = sortedKeys[i];
  20897. canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
  20898. }
  20899. stack.pop();
  20900. replacementStack.pop();
  20901. } else {
  20902. canonicalizedObj = obj;
  20903. }
  20904. return canonicalizedObj;
  20905. }
  20906. var arrayDiff = new Diff();
  20907. arrayDiff.tokenize = function (value) {
  20908. return value.slice();
  20909. };
  20910. arrayDiff.join = arrayDiff.removeEmpty = function (value) {
  20911. return value;
  20912. };
  20913. function diffArrays(oldArr, newArr, callback) {
  20914. return arrayDiff.diff(oldArr, newArr, callback);
  20915. }
  20916. function parsePatch(uniDiff) {
  20917. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  20918. var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
  20919. delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  20920. list = [],
  20921. i = 0;
  20922. function parseIndex() {
  20923. var index = {};
  20924. list.push(index); // Parse diff metadata
  20925. while (i < diffstr.length) {
  20926. var line = diffstr[i]; // File header found, end parsing diff metadata
  20927. if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
  20928. break;
  20929. } // Diff index
  20930. var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
  20931. if (header) {
  20932. index.index = header[1];
  20933. }
  20934. i++;
  20935. } // Parse file headers if they are defined. Unified diff requires them, but
  20936. // there's no technical issues to have an isolated hunk without file header
  20937. parseFileHeader(index);
  20938. parseFileHeader(index); // Parse hunks
  20939. index.hunks = [];
  20940. while (i < diffstr.length) {
  20941. var _line = diffstr[i];
  20942. if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
  20943. break;
  20944. } else if (/^@@/.test(_line)) {
  20945. index.hunks.push(parseHunk());
  20946. } else if (_line && options.strict) {
  20947. // Ignore unexpected content unless in strict mode
  20948. throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
  20949. } else {
  20950. i++;
  20951. }
  20952. }
  20953. } // Parses the --- and +++ headers, if none are found, no lines
  20954. // are consumed.
  20955. function parseFileHeader(index) {
  20956. var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
  20957. if (fileHeader) {
  20958. var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
  20959. var data = fileHeader[2].split('\t', 2);
  20960. var fileName = data[0].replace(/\\\\/g, '\\');
  20961. if (/^".*"$/.test(fileName)) {
  20962. fileName = fileName.substr(1, fileName.length - 2);
  20963. }
  20964. index[keyPrefix + 'FileName'] = fileName;
  20965. index[keyPrefix + 'Header'] = (data[1] || '').trim();
  20966. i++;
  20967. }
  20968. } // Parses a hunk
  20969. // This assumes that we are at the start of a hunk.
  20970. function parseHunk() {
  20971. var chunkHeaderIndex = i,
  20972. chunkHeaderLine = diffstr[i++],
  20973. chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
  20974. var hunk = {
  20975. oldStart: +chunkHeader[1],
  20976. oldLines: +chunkHeader[2] || 1,
  20977. newStart: +chunkHeader[3],
  20978. newLines: +chunkHeader[4] || 1,
  20979. lines: [],
  20980. linedelimiters: []
  20981. };
  20982. var addCount = 0,
  20983. removeCount = 0;
  20984. for (; i < diffstr.length; i++) {
  20985. // Lines starting with '---' could be mistaken for the "remove line" operation
  20986. // But they could be the header for the next file. Therefore prune such cases out.
  20987. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
  20988. break;
  20989. }
  20990. var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
  20991. if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
  20992. hunk.lines.push(diffstr[i]);
  20993. hunk.linedelimiters.push(delimiters[i] || '\n');
  20994. if (operation === '+') {
  20995. addCount++;
  20996. } else if (operation === '-') {
  20997. removeCount++;
  20998. } else if (operation === ' ') {
  20999. addCount++;
  21000. removeCount++;
  21001. }
  21002. } else {
  21003. break;
  21004. }
  21005. } // Handle the empty block count case
  21006. if (!addCount && hunk.newLines === 1) {
  21007. hunk.newLines = 0;
  21008. }
  21009. if (!removeCount && hunk.oldLines === 1) {
  21010. hunk.oldLines = 0;
  21011. } // Perform optional sanity checking
  21012. if (options.strict) {
  21013. if (addCount !== hunk.newLines) {
  21014. throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  21015. }
  21016. if (removeCount !== hunk.oldLines) {
  21017. throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  21018. }
  21019. }
  21020. return hunk;
  21021. }
  21022. while (i < diffstr.length) {
  21023. parseIndex();
  21024. }
  21025. return list;
  21026. }
  21027. // Iterator that traverses in the range of [min, max], stepping
  21028. // by distance from a given start position. I.e. for [0, 4], with
  21029. // start of 2, this will iterate 2, 3, 1, 4, 0.
  21030. function distanceIterator (start, minLine, maxLine) {
  21031. var wantForward = true,
  21032. backwardExhausted = false,
  21033. forwardExhausted = false,
  21034. localOffset = 1;
  21035. return function iterator() {
  21036. if (wantForward && !forwardExhausted) {
  21037. if (backwardExhausted) {
  21038. localOffset++;
  21039. } else {
  21040. wantForward = false;
  21041. } // Check if trying to fit beyond text length, and if not, check it fits
  21042. // after offset location (or desired location on first iteration)
  21043. if (start + localOffset <= maxLine) {
  21044. return localOffset;
  21045. }
  21046. forwardExhausted = true;
  21047. }
  21048. if (!backwardExhausted) {
  21049. if (!forwardExhausted) {
  21050. wantForward = true;
  21051. } // Check if trying to fit before text beginning, and if not, check it fits
  21052. // before offset location
  21053. if (minLine <= start - localOffset) {
  21054. return -localOffset++;
  21055. }
  21056. backwardExhausted = true;
  21057. return iterator();
  21058. } // We tried to fit hunk before text beginning and beyond text length, then
  21059. // hunk can't fit on the text. Return undefined
  21060. };
  21061. }
  21062. function applyPatch(source, uniDiff) {
  21063. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  21064. if (typeof uniDiff === 'string') {
  21065. uniDiff = parsePatch(uniDiff);
  21066. }
  21067. if (Array.isArray(uniDiff)) {
  21068. if (uniDiff.length > 1) {
  21069. throw new Error('applyPatch only works with a single input.');
  21070. }
  21071. uniDiff = uniDiff[0];
  21072. } // Apply the diff to the input
  21073. var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
  21074. delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  21075. hunks = uniDiff.hunks,
  21076. compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
  21077. return line === patchContent;
  21078. },
  21079. errorCount = 0,
  21080. fuzzFactor = options.fuzzFactor || 0,
  21081. minLine = 0,
  21082. offset = 0,
  21083. removeEOFNL,
  21084. addEOFNL;
  21085. /**
  21086. * Checks if the hunk exactly fits on the provided location
  21087. */
  21088. function hunkFits(hunk, toPos) {
  21089. for (var j = 0; j < hunk.lines.length; j++) {
  21090. var line = hunk.lines[j],
  21091. operation = line.length > 0 ? line[0] : ' ',
  21092. content = line.length > 0 ? line.substr(1) : line;
  21093. if (operation === ' ' || operation === '-') {
  21094. // Context sanity check
  21095. if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
  21096. errorCount++;
  21097. if (errorCount > fuzzFactor) {
  21098. return false;
  21099. }
  21100. }
  21101. toPos++;
  21102. }
  21103. }
  21104. return true;
  21105. } // Search best fit offsets for each hunk based on the previous ones
  21106. for (var i = 0; i < hunks.length; i++) {
  21107. var hunk = hunks[i],
  21108. maxLine = lines.length - hunk.oldLines,
  21109. localOffset = 0,
  21110. toPos = offset + hunk.oldStart - 1;
  21111. var iterator = distanceIterator(toPos, minLine, maxLine);
  21112. for (; localOffset !== undefined; localOffset = iterator()) {
  21113. if (hunkFits(hunk, toPos + localOffset)) {
  21114. hunk.offset = offset += localOffset;
  21115. break;
  21116. }
  21117. }
  21118. if (localOffset === undefined) {
  21119. return false;
  21120. } // Set lower text limit to end of the current hunk, so next ones don't try
  21121. // to fit over already patched text
  21122. minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
  21123. } // Apply patch hunks
  21124. var diffOffset = 0;
  21125. for (var _i = 0; _i < hunks.length; _i++) {
  21126. var _hunk = hunks[_i],
  21127. _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
  21128. diffOffset += _hunk.newLines - _hunk.oldLines;
  21129. if (_toPos < 0) {
  21130. // Creating a new file
  21131. _toPos = 0;
  21132. }
  21133. for (var j = 0; j < _hunk.lines.length; j++) {
  21134. var line = _hunk.lines[j],
  21135. operation = line.length > 0 ? line[0] : ' ',
  21136. content = line.length > 0 ? line.substr(1) : line,
  21137. delimiter = _hunk.linedelimiters[j];
  21138. if (operation === ' ') {
  21139. _toPos++;
  21140. } else if (operation === '-') {
  21141. lines.splice(_toPos, 1);
  21142. delimiters.splice(_toPos, 1);
  21143. /* istanbul ignore else */
  21144. } else if (operation === '+') {
  21145. lines.splice(_toPos, 0, content);
  21146. delimiters.splice(_toPos, 0, delimiter);
  21147. _toPos++;
  21148. } else if (operation === '\\') {
  21149. var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
  21150. if (previousOperation === '+') {
  21151. removeEOFNL = true;
  21152. } else if (previousOperation === '-') {
  21153. addEOFNL = true;
  21154. }
  21155. }
  21156. }
  21157. } // Handle EOFNL insertion/removal
  21158. if (removeEOFNL) {
  21159. while (!lines[lines.length - 1]) {
  21160. lines.pop();
  21161. delimiters.pop();
  21162. }
  21163. } else if (addEOFNL) {
  21164. lines.push('');
  21165. delimiters.push('\n');
  21166. }
  21167. for (var _k = 0; _k < lines.length - 1; _k++) {
  21168. lines[_k] = lines[_k] + delimiters[_k];
  21169. }
  21170. return lines.join('');
  21171. } // Wrapper that supports multiple file patches via callbacks.
  21172. function applyPatches(uniDiff, options) {
  21173. if (typeof uniDiff === 'string') {
  21174. uniDiff = parsePatch(uniDiff);
  21175. }
  21176. var currentIndex = 0;
  21177. function processIndex() {
  21178. var index = uniDiff[currentIndex++];
  21179. if (!index) {
  21180. return options.complete();
  21181. }
  21182. options.loadFile(index, function (err, data) {
  21183. if (err) {
  21184. return options.complete(err);
  21185. }
  21186. var updatedContent = applyPatch(data, index, options);
  21187. options.patched(index, updatedContent, function (err) {
  21188. if (err) {
  21189. return options.complete(err);
  21190. }
  21191. processIndex();
  21192. });
  21193. });
  21194. }
  21195. processIndex();
  21196. }
  21197. function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  21198. if (!options) {
  21199. options = {};
  21200. }
  21201. if (typeof options.context === 'undefined') {
  21202. options.context = 4;
  21203. }
  21204. var diff = diffLines(oldStr, newStr, options);
  21205. diff.push({
  21206. value: '',
  21207. lines: []
  21208. }); // Append an empty value to make cleanup easier
  21209. function contextLines(lines) {
  21210. return lines.map(function (entry) {
  21211. return ' ' + entry;
  21212. });
  21213. }
  21214. var hunks = [];
  21215. var oldRangeStart = 0,
  21216. newRangeStart = 0,
  21217. curRange = [],
  21218. oldLine = 1,
  21219. newLine = 1;
  21220. var _loop = function _loop(i) {
  21221. var current = diff[i],
  21222. lines = current.lines || current.value.replace(/\n$/, '').split('\n');
  21223. current.lines = lines;
  21224. if (current.added || current.removed) {
  21225. var _curRange;
  21226. // If we have previous context, start with that
  21227. if (!oldRangeStart) {
  21228. var prev = diff[i - 1];
  21229. oldRangeStart = oldLine;
  21230. newRangeStart = newLine;
  21231. if (prev) {
  21232. curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
  21233. oldRangeStart -= curRange.length;
  21234. newRangeStart -= curRange.length;
  21235. }
  21236. } // Output our changes
  21237. (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
  21238. return (current.added ? '+' : '-') + entry;
  21239. }))); // Track the updated file position
  21240. if (current.added) {
  21241. newLine += lines.length;
  21242. } else {
  21243. oldLine += lines.length;
  21244. }
  21245. } else {
  21246. // Identical context lines. Track line changes
  21247. if (oldRangeStart) {
  21248. // Close out any changes that have been output (or join overlapping)
  21249. if (lines.length <= options.context * 2 && i < diff.length - 2) {
  21250. var _curRange2;
  21251. // Overlapping
  21252. (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
  21253. } else {
  21254. var _curRange3;
  21255. // end the range and output
  21256. var contextSize = Math.min(lines.length, options.context);
  21257. (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
  21258. var hunk = {
  21259. oldStart: oldRangeStart,
  21260. oldLines: oldLine - oldRangeStart + contextSize,
  21261. newStart: newRangeStart,
  21262. newLines: newLine - newRangeStart + contextSize,
  21263. lines: curRange
  21264. };
  21265. if (i >= diff.length - 2 && lines.length <= options.context) {
  21266. // EOF is inside this hunk
  21267. var oldEOFNewline = /\n$/.test(oldStr);
  21268. var newEOFNewline = /\n$/.test(newStr);
  21269. var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
  21270. if (!oldEOFNewline && noNlBeforeAdds) {
  21271. // special case: old has no eol and no trailing context; no-nl can end up before adds
  21272. curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
  21273. }
  21274. if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
  21275. curRange.push('\\ No newline at end of file');
  21276. }
  21277. }
  21278. hunks.push(hunk);
  21279. oldRangeStart = 0;
  21280. newRangeStart = 0;
  21281. curRange = [];
  21282. }
  21283. }
  21284. oldLine += lines.length;
  21285. newLine += lines.length;
  21286. }
  21287. };
  21288. for (var i = 0; i < diff.length; i++) {
  21289. _loop(i);
  21290. }
  21291. return {
  21292. oldFileName: oldFileName,
  21293. newFileName: newFileName,
  21294. oldHeader: oldHeader,
  21295. newHeader: newHeader,
  21296. hunks: hunks
  21297. };
  21298. }
  21299. function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  21300. var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
  21301. var ret = [];
  21302. if (oldFileName == newFileName) {
  21303. ret.push('Index: ' + oldFileName);
  21304. }
  21305. ret.push('===================================================================');
  21306. ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
  21307. ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
  21308. for (var i = 0; i < diff.hunks.length; i++) {
  21309. var hunk = diff.hunks[i];
  21310. ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
  21311. ret.push.apply(ret, hunk.lines);
  21312. }
  21313. return ret.join('\n') + '\n';
  21314. }
  21315. function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
  21316. return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
  21317. }
  21318. function arrayEqual(a, b) {
  21319. if (a.length !== b.length) {
  21320. return false;
  21321. }
  21322. return arrayStartsWith(a, b);
  21323. }
  21324. function arrayStartsWith(array, start) {
  21325. if (start.length > array.length) {
  21326. return false;
  21327. }
  21328. for (var i = 0; i < start.length; i++) {
  21329. if (start[i] !== array[i]) {
  21330. return false;
  21331. }
  21332. }
  21333. return true;
  21334. }
  21335. function calcLineCount(hunk) {
  21336. var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
  21337. oldLines = _calcOldNewLineCount.oldLines,
  21338. newLines = _calcOldNewLineCount.newLines;
  21339. if (oldLines !== undefined) {
  21340. hunk.oldLines = oldLines;
  21341. } else {
  21342. delete hunk.oldLines;
  21343. }
  21344. if (newLines !== undefined) {
  21345. hunk.newLines = newLines;
  21346. } else {
  21347. delete hunk.newLines;
  21348. }
  21349. }
  21350. function merge$1(mine, theirs, base) {
  21351. mine = loadPatch(mine, base);
  21352. theirs = loadPatch(theirs, base);
  21353. var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
  21354. // Leaving sanity checks on this to the API consumer that may know more about the
  21355. // meaning in their own context.
  21356. if (mine.index || theirs.index) {
  21357. ret.index = mine.index || theirs.index;
  21358. }
  21359. if (mine.newFileName || theirs.newFileName) {
  21360. if (!fileNameChanged(mine)) {
  21361. // No header or no change in ours, use theirs (and ours if theirs does not exist)
  21362. ret.oldFileName = theirs.oldFileName || mine.oldFileName;
  21363. ret.newFileName = theirs.newFileName || mine.newFileName;
  21364. ret.oldHeader = theirs.oldHeader || mine.oldHeader;
  21365. ret.newHeader = theirs.newHeader || mine.newHeader;
  21366. } else if (!fileNameChanged(theirs)) {
  21367. // No header or no change in theirs, use ours
  21368. ret.oldFileName = mine.oldFileName;
  21369. ret.newFileName = mine.newFileName;
  21370. ret.oldHeader = mine.oldHeader;
  21371. ret.newHeader = mine.newHeader;
  21372. } else {
  21373. // Both changed... figure it out
  21374. ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
  21375. ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
  21376. ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
  21377. ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
  21378. }
  21379. }
  21380. ret.hunks = [];
  21381. var mineIndex = 0,
  21382. theirsIndex = 0,
  21383. mineOffset = 0,
  21384. theirsOffset = 0;
  21385. while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
  21386. var mineCurrent = mine.hunks[mineIndex] || {
  21387. oldStart: Infinity
  21388. },
  21389. theirsCurrent = theirs.hunks[theirsIndex] || {
  21390. oldStart: Infinity
  21391. };
  21392. if (hunkBefore(mineCurrent, theirsCurrent)) {
  21393. // This patch does not overlap with any of the others, yay.
  21394. ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
  21395. mineIndex++;
  21396. theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
  21397. } else if (hunkBefore(theirsCurrent, mineCurrent)) {
  21398. // This patch does not overlap with any of the others, yay.
  21399. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
  21400. theirsIndex++;
  21401. mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
  21402. } else {
  21403. // Overlap, merge as best we can
  21404. var mergedHunk = {
  21405. oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
  21406. oldLines: 0,
  21407. newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
  21408. newLines: 0,
  21409. lines: []
  21410. };
  21411. mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
  21412. theirsIndex++;
  21413. mineIndex++;
  21414. ret.hunks.push(mergedHunk);
  21415. }
  21416. }
  21417. return ret;
  21418. }
  21419. function loadPatch(param, base) {
  21420. if (typeof param === 'string') {
  21421. if (/^@@/m.test(param) || /^Index:/m.test(param)) {
  21422. return parsePatch(param)[0];
  21423. }
  21424. if (!base) {
  21425. throw new Error('Must provide a base reference or pass in a patch');
  21426. }
  21427. return structuredPatch(undefined, undefined, base, param);
  21428. }
  21429. return param;
  21430. }
  21431. function fileNameChanged(patch) {
  21432. return patch.newFileName && patch.newFileName !== patch.oldFileName;
  21433. }
  21434. function selectField(index, mine, theirs) {
  21435. if (mine === theirs) {
  21436. return mine;
  21437. } else {
  21438. index.conflict = true;
  21439. return {
  21440. mine: mine,
  21441. theirs: theirs
  21442. };
  21443. }
  21444. }
  21445. function hunkBefore(test, check) {
  21446. return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
  21447. }
  21448. function cloneHunk(hunk, offset) {
  21449. return {
  21450. oldStart: hunk.oldStart,
  21451. oldLines: hunk.oldLines,
  21452. newStart: hunk.newStart + offset,
  21453. newLines: hunk.newLines,
  21454. lines: hunk.lines
  21455. };
  21456. }
  21457. function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
  21458. // This will generally result in a conflicted hunk, but there are cases where the context
  21459. // is the only overlap where we can successfully merge the content here.
  21460. var mine = {
  21461. offset: mineOffset,
  21462. lines: mineLines,
  21463. index: 0
  21464. },
  21465. their = {
  21466. offset: theirOffset,
  21467. lines: theirLines,
  21468. index: 0
  21469. }; // Handle any leading content
  21470. insertLeading(hunk, mine, their);
  21471. insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
  21472. while (mine.index < mine.lines.length && their.index < their.lines.length) {
  21473. var mineCurrent = mine.lines[mine.index],
  21474. theirCurrent = their.lines[their.index];
  21475. if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
  21476. // Both modified ...
  21477. mutualChange(hunk, mine, their);
  21478. } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
  21479. var _hunk$lines;
  21480. // Mine inserted
  21481. (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
  21482. } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
  21483. var _hunk$lines2;
  21484. // Theirs inserted
  21485. (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
  21486. } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
  21487. // Mine removed or edited
  21488. removal(hunk, mine, their);
  21489. } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
  21490. // Their removed or edited
  21491. removal(hunk, their, mine, true);
  21492. } else if (mineCurrent === theirCurrent) {
  21493. // Context identity
  21494. hunk.lines.push(mineCurrent);
  21495. mine.index++;
  21496. their.index++;
  21497. } else {
  21498. // Context mismatch
  21499. conflict(hunk, collectChange(mine), collectChange(their));
  21500. }
  21501. } // Now push anything that may be remaining
  21502. insertTrailing(hunk, mine);
  21503. insertTrailing(hunk, their);
  21504. calcLineCount(hunk);
  21505. }
  21506. function mutualChange(hunk, mine, their) {
  21507. var myChanges = collectChange(mine),
  21508. theirChanges = collectChange(their);
  21509. if (allRemoves(myChanges) && allRemoves(theirChanges)) {
  21510. // Special case for remove changes that are supersets of one another
  21511. if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
  21512. var _hunk$lines3;
  21513. (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
  21514. return;
  21515. } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
  21516. var _hunk$lines4;
  21517. (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
  21518. return;
  21519. }
  21520. } else if (arrayEqual(myChanges, theirChanges)) {
  21521. var _hunk$lines5;
  21522. (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
  21523. return;
  21524. }
  21525. conflict(hunk, myChanges, theirChanges);
  21526. }
  21527. function removal(hunk, mine, their, swap) {
  21528. var myChanges = collectChange(mine),
  21529. theirChanges = collectContext(their, myChanges);
  21530. if (theirChanges.merged) {
  21531. var _hunk$lines6;
  21532. (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
  21533. } else {
  21534. conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
  21535. }
  21536. }
  21537. function conflict(hunk, mine, their) {
  21538. hunk.conflict = true;
  21539. hunk.lines.push({
  21540. conflict: true,
  21541. mine: mine,
  21542. theirs: their
  21543. });
  21544. }
  21545. function insertLeading(hunk, insert, their) {
  21546. while (insert.offset < their.offset && insert.index < insert.lines.length) {
  21547. var line = insert.lines[insert.index++];
  21548. hunk.lines.push(line);
  21549. insert.offset++;
  21550. }
  21551. }
  21552. function insertTrailing(hunk, insert) {
  21553. while (insert.index < insert.lines.length) {
  21554. var line = insert.lines[insert.index++];
  21555. hunk.lines.push(line);
  21556. }
  21557. }
  21558. function collectChange(state) {
  21559. var ret = [],
  21560. operation = state.lines[state.index][0];
  21561. while (state.index < state.lines.length) {
  21562. var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
  21563. if (operation === '-' && line[0] === '+') {
  21564. operation = '+';
  21565. }
  21566. if (operation === line[0]) {
  21567. ret.push(line);
  21568. state.index++;
  21569. } else {
  21570. break;
  21571. }
  21572. }
  21573. return ret;
  21574. }
  21575. function collectContext(state, matchChanges) {
  21576. var changes = [],
  21577. merged = [],
  21578. matchIndex = 0,
  21579. contextChanges = false,
  21580. conflicted = false;
  21581. while (matchIndex < matchChanges.length && state.index < state.lines.length) {
  21582. var change = state.lines[state.index],
  21583. match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
  21584. if (match[0] === '+') {
  21585. break;
  21586. }
  21587. contextChanges = contextChanges || change[0] !== ' ';
  21588. merged.push(match);
  21589. matchIndex++; // Consume any additions in the other block as a conflict to attempt
  21590. // to pull in the remaining context after this
  21591. if (change[0] === '+') {
  21592. conflicted = true;
  21593. while (change[0] === '+') {
  21594. changes.push(change);
  21595. change = state.lines[++state.index];
  21596. }
  21597. }
  21598. if (match.substr(1) === change.substr(1)) {
  21599. changes.push(change);
  21600. state.index++;
  21601. } else {
  21602. conflicted = true;
  21603. }
  21604. }
  21605. if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
  21606. conflicted = true;
  21607. }
  21608. if (conflicted) {
  21609. return changes;
  21610. }
  21611. while (matchIndex < matchChanges.length) {
  21612. merged.push(matchChanges[matchIndex++]);
  21613. }
  21614. return {
  21615. merged: merged,
  21616. changes: changes
  21617. };
  21618. }
  21619. function allRemoves(changes) {
  21620. return changes.reduce(function (prev, change) {
  21621. return prev && change[0] === '-';
  21622. }, true);
  21623. }
  21624. function skipRemoveSuperset(state, removeChanges, delta) {
  21625. for (var i = 0; i < delta; i++) {
  21626. var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
  21627. if (state.lines[state.index + i] !== ' ' + changeContent) {
  21628. return false;
  21629. }
  21630. }
  21631. state.index += delta;
  21632. return true;
  21633. }
  21634. function calcOldNewLineCount(lines) {
  21635. var oldLines = 0;
  21636. var newLines = 0;
  21637. lines.forEach(function (line) {
  21638. if (typeof line !== 'string') {
  21639. var myCount = calcOldNewLineCount(line.mine);
  21640. var theirCount = calcOldNewLineCount(line.theirs);
  21641. if (oldLines !== undefined) {
  21642. if (myCount.oldLines === theirCount.oldLines) {
  21643. oldLines += myCount.oldLines;
  21644. } else {
  21645. oldLines = undefined;
  21646. }
  21647. }
  21648. if (newLines !== undefined) {
  21649. if (myCount.newLines === theirCount.newLines) {
  21650. newLines += myCount.newLines;
  21651. } else {
  21652. newLines = undefined;
  21653. }
  21654. }
  21655. } else {
  21656. if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
  21657. newLines++;
  21658. }
  21659. if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
  21660. oldLines++;
  21661. }
  21662. }
  21663. });
  21664. return {
  21665. oldLines: oldLines,
  21666. newLines: newLines
  21667. };
  21668. }
  21669. // See: http://code.google.com/p/google-diff-match-patch/wiki/API
  21670. function convertChangesToDMP(changes) {
  21671. var ret = [],
  21672. change,
  21673. operation;
  21674. for (var i = 0; i < changes.length; i++) {
  21675. change = changes[i];
  21676. if (change.added) {
  21677. operation = 1;
  21678. } else if (change.removed) {
  21679. operation = -1;
  21680. } else {
  21681. operation = 0;
  21682. }
  21683. ret.push([operation, change.value]);
  21684. }
  21685. return ret;
  21686. }
  21687. function convertChangesToXML(changes) {
  21688. var ret = [];
  21689. for (var i = 0; i < changes.length; i++) {
  21690. var change = changes[i];
  21691. if (change.added) {
  21692. ret.push('<ins>');
  21693. } else if (change.removed) {
  21694. ret.push('<del>');
  21695. }
  21696. ret.push(escapeHTML(change.value));
  21697. if (change.added) {
  21698. ret.push('</ins>');
  21699. } else if (change.removed) {
  21700. ret.push('</del>');
  21701. }
  21702. }
  21703. return ret.join('');
  21704. }
  21705. function escapeHTML(s) {
  21706. var n = s;
  21707. n = n.replace(/&/g, '&amp;');
  21708. n = n.replace(/</g, '&lt;');
  21709. n = n.replace(/>/g, '&gt;');
  21710. n = n.replace(/"/g, '&quot;');
  21711. return n;
  21712. }
  21713. var index_es6 = {
  21714. __proto__: null,
  21715. Diff: Diff,
  21716. diffChars: diffChars,
  21717. diffWords: diffWords,
  21718. diffWordsWithSpace: diffWordsWithSpace,
  21719. diffLines: diffLines,
  21720. diffTrimmedLines: diffTrimmedLines,
  21721. diffSentences: diffSentences,
  21722. diffCss: diffCss,
  21723. diffJson: diffJson,
  21724. diffArrays: diffArrays,
  21725. structuredPatch: structuredPatch,
  21726. createTwoFilesPatch: createTwoFilesPatch,
  21727. createPatch: createPatch,
  21728. applyPatch: applyPatch,
  21729. applyPatches: applyPatches,
  21730. parsePatch: parsePatch,
  21731. merge: merge$1,
  21732. convertChangesToDMP: convertChangesToDMP,
  21733. convertChangesToXML: convertChangesToXML,
  21734. canonicalize: canonicalize
  21735. };
  21736. var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(index_es6);
  21737. var nodePrimordials = {
  21738. ArrayFrom: Array.from,
  21739. ArrayIsArray: Array.isArray,
  21740. ArrayPrototypeJoin: (obj, separator) => Array.prototype.join.call(obj, separator),
  21741. ArrayPrototypeShift: (obj) => Array.prototype.shift.call(obj),
  21742. ArrayPrototypeForEach: (arr, ...rest) => Array.prototype.forEach.apply(arr, rest),
  21743. ArrayPrototypeIncludes: (arr, ...rest) => Array.prototype.includes.apply(arr, rest),
  21744. ArrayPrototypeJoin: (arr, ...rest) => Array.prototype.join.apply(arr, rest),
  21745. ArrayPrototypePop: (arr, ...rest) => Array.prototype.pop.apply(arr, rest),
  21746. ArrayPrototypePush: (arr, ...rest) => Array.prototype.push.apply(arr, rest),
  21747. FunctionPrototype: Function.prototype,
  21748. JSONParse: JSON.parse,
  21749. JSONStringify: JSON.stringify,
  21750. ObjectFreeze: Object.freeze,
  21751. ObjectKeys: Object.keys,
  21752. ObjectGetOwnPropertyNames: Object.getOwnPropertyNames,
  21753. ObjectDefineProperty: Object.defineProperty,
  21754. ObjectPrototypeHasOwnProperty: (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop),
  21755. RegExpPrototypeTest: (obj, string) => RegExp.prototype.test.call(obj, string),
  21756. RegExpPrototypeSymbolReplace: (obj, ...rest) => RegExp.prototype[Symbol.replace].apply(obj, rest),
  21757. SafeMap: Map,
  21758. SafeSet: Set,
  21759. StringPrototypeEndsWith: (str, ...rest) => String.prototype.endsWith.apply(str, rest),
  21760. StringPrototypeIncludes: (str, ...rest) => String.prototype.includes.apply(str, rest),
  21761. StringPrototypeLastIndexOf: (str, ...rest) => String.prototype.lastIndexOf.apply(str, rest),
  21762. StringPrototypeIndexOf: (str, ...rest) => String.prototype.indexOf.apply(str, rest),
  21763. StringPrototypeRepeat: (str, ...rest) => String.prototype.repeat.apply(str, rest),
  21764. StringPrototypeReplace: (str, ...rest) => String.prototype.replace.apply(str, rest),
  21765. StringPrototypeSlice: (str, ...rest) => String.prototype.slice.apply(str, rest),
  21766. StringPrototypeSplit: (str, ...rest) => String.prototype.split.apply(str, rest),
  21767. StringPrototypeStartsWith: (str, ...rest) => String.prototype.startsWith.apply(str, rest),
  21768. StringPrototypeSubstr: (str, ...rest) => String.prototype.substr.apply(str, rest),
  21769. SyntaxError: SyntaxError
  21770. };
  21771. var acorn$1 = {exports: {}};
  21772. (function (module, exports) {
  21773. (function (global, factory) {
  21774. factory(exports) ;
  21775. }(commonjsGlobal, (function (exports) {
  21776. // Reserved word lists for various dialects of the language
  21777. var reservedWords = {
  21778. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  21779. 5: "class enum extends super const export import",
  21780. 6: "enum",
  21781. strict: "implements interface let package private protected public static yield",
  21782. strictBind: "eval arguments"
  21783. };
  21784. // And the keywords
  21785. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  21786. var keywords = {
  21787. 5: ecma5AndLessKeywords,
  21788. "5module": ecma5AndLessKeywords + " export import",
  21789. 6: ecma5AndLessKeywords + " const class extends export import super"
  21790. };
  21791. var keywordRelationalOperator = /^in(stanceof)?$/;
  21792. // ## Character categories
  21793. // Big ugly regular expressions that match characters in the
  21794. // whitespace, identifier, and identifier-start categories. These
  21795. // are only applied when a character is found to actually have a
  21796. // code point above 128.
  21797. // Generated by `bin/generate-identifier-regex.js`.
  21798. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  21799. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  21800. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  21801. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  21802. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  21803. // These are a run-length and offset encoded representation of the
  21804. // >0xffff code points that are a valid part of identifiers. The
  21805. // offset starts at 0x10000, and each pair of numbers represents an
  21806. // offset to the next range, and then a size of the range. They were
  21807. // generated by bin/generate-identifier-regex.js
  21808. // eslint-disable-next-line comma-spacing
  21809. var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
  21810. // eslint-disable-next-line comma-spacing
  21811. var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];
  21812. // This has a complexity linear to the value of the code. The
  21813. // assumption is that looking up astral identifier characters is
  21814. // rare.
  21815. function isInAstralSet(code, set) {
  21816. var pos = 0x10000;
  21817. for (var i = 0; i < set.length; i += 2) {
  21818. pos += set[i];
  21819. if (pos > code) { return false }
  21820. pos += set[i + 1];
  21821. if (pos >= code) { return true }
  21822. }
  21823. }
  21824. // Test whether a given character code starts an identifier.
  21825. function isIdentifierStart(code, astral) {
  21826. if (code < 65) { return code === 36 }
  21827. if (code < 91) { return true }
  21828. if (code < 97) { return code === 95 }
  21829. if (code < 123) { return true }
  21830. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  21831. if (astral === false) { return false }
  21832. return isInAstralSet(code, astralIdentifierStartCodes)
  21833. }
  21834. // Test whether a given character is part of an identifier.
  21835. function isIdentifierChar(code, astral) {
  21836. if (code < 48) { return code === 36 }
  21837. if (code < 58) { return true }
  21838. if (code < 65) { return false }
  21839. if (code < 91) { return true }
  21840. if (code < 97) { return code === 95 }
  21841. if (code < 123) { return true }
  21842. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  21843. if (astral === false) { return false }
  21844. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  21845. }
  21846. // ## Token types
  21847. // The assignment of fine-grained, information-carrying type objects
  21848. // allows the tokenizer to store the information it has about a
  21849. // token in a way that is very cheap for the parser to look up.
  21850. // All token type variables start with an underscore, to make them
  21851. // easy to recognize.
  21852. // The `beforeExpr` property is used to disambiguate between regular
  21853. // expressions and divisions. It is set on all token types that can
  21854. // be followed by an expression (thus, a slash after them would be a
  21855. // regular expression).
  21856. //
  21857. // The `startsExpr` property is used to check if the token ends a
  21858. // `yield` expression. It is set on all token types that either can
  21859. // directly start an expression (like a quotation mark) or can
  21860. // continue an expression (like the body of a string).
  21861. //
  21862. // `isLoop` marks a keyword as starting a loop, which is important
  21863. // to know when parsing a label, in order to allow or disallow
  21864. // continue jumps to that label.
  21865. var TokenType = function TokenType(label, conf) {
  21866. if ( conf === void 0 ) conf = {};
  21867. this.label = label;
  21868. this.keyword = conf.keyword;
  21869. this.beforeExpr = !!conf.beforeExpr;
  21870. this.startsExpr = !!conf.startsExpr;
  21871. this.isLoop = !!conf.isLoop;
  21872. this.isAssign = !!conf.isAssign;
  21873. this.prefix = !!conf.prefix;
  21874. this.postfix = !!conf.postfix;
  21875. this.binop = conf.binop || null;
  21876. this.updateContext = null;
  21877. };
  21878. function binop(name, prec) {
  21879. return new TokenType(name, {beforeExpr: true, binop: prec})
  21880. }
  21881. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  21882. // Map keyword names to token types.
  21883. var keywords$1 = {};
  21884. // Succinct definitions of keyword token types
  21885. function kw(name, options) {
  21886. if ( options === void 0 ) options = {};
  21887. options.keyword = name;
  21888. return keywords$1[name] = new TokenType(name, options)
  21889. }
  21890. var types = {
  21891. num: new TokenType("num", startsExpr),
  21892. regexp: new TokenType("regexp", startsExpr),
  21893. string: new TokenType("string", startsExpr),
  21894. name: new TokenType("name", startsExpr),
  21895. privateId: new TokenType("privateId", startsExpr),
  21896. eof: new TokenType("eof"),
  21897. // Punctuation token types.
  21898. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  21899. bracketR: new TokenType("]"),
  21900. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  21901. braceR: new TokenType("}"),
  21902. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  21903. parenR: new TokenType(")"),
  21904. comma: new TokenType(",", beforeExpr),
  21905. semi: new TokenType(";", beforeExpr),
  21906. colon: new TokenType(":", beforeExpr),
  21907. dot: new TokenType("."),
  21908. question: new TokenType("?", beforeExpr),
  21909. questionDot: new TokenType("?."),
  21910. arrow: new TokenType("=>", beforeExpr),
  21911. template: new TokenType("template"),
  21912. invalidTemplate: new TokenType("invalidTemplate"),
  21913. ellipsis: new TokenType("...", beforeExpr),
  21914. backQuote: new TokenType("`", startsExpr),
  21915. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  21916. // Operators. These carry several kinds of properties to help the
  21917. // parser use them properly (the presence of these properties is
  21918. // what categorizes them as operators).
  21919. //
  21920. // `binop`, when present, specifies that this operator is a binary
  21921. // operator, and will refer to its precedence.
  21922. //
  21923. // `prefix` and `postfix` mark the operator as a prefix or postfix
  21924. // unary operator.
  21925. //
  21926. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  21927. // binary operators with a very low precedence, that should result
  21928. // in AssignmentExpression nodes.
  21929. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  21930. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  21931. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  21932. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  21933. logicalOR: binop("||", 1),
  21934. logicalAND: binop("&&", 2),
  21935. bitwiseOR: binop("|", 3),
  21936. bitwiseXOR: binop("^", 4),
  21937. bitwiseAND: binop("&", 5),
  21938. equality: binop("==/!=/===/!==", 6),
  21939. relational: binop("</>/<=/>=", 7),
  21940. bitShift: binop("<</>>/>>>", 8),
  21941. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  21942. modulo: binop("%", 10),
  21943. star: binop("*", 10),
  21944. slash: binop("/", 10),
  21945. starstar: new TokenType("**", {beforeExpr: true}),
  21946. coalesce: binop("??", 1),
  21947. // Keyword token types.
  21948. _break: kw("break"),
  21949. _case: kw("case", beforeExpr),
  21950. _catch: kw("catch"),
  21951. _continue: kw("continue"),
  21952. _debugger: kw("debugger"),
  21953. _default: kw("default", beforeExpr),
  21954. _do: kw("do", {isLoop: true, beforeExpr: true}),
  21955. _else: kw("else", beforeExpr),
  21956. _finally: kw("finally"),
  21957. _for: kw("for", {isLoop: true}),
  21958. _function: kw("function", startsExpr),
  21959. _if: kw("if"),
  21960. _return: kw("return", beforeExpr),
  21961. _switch: kw("switch"),
  21962. _throw: kw("throw", beforeExpr),
  21963. _try: kw("try"),
  21964. _var: kw("var"),
  21965. _const: kw("const"),
  21966. _while: kw("while", {isLoop: true}),
  21967. _with: kw("with"),
  21968. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  21969. _this: kw("this", startsExpr),
  21970. _super: kw("super", startsExpr),
  21971. _class: kw("class", startsExpr),
  21972. _extends: kw("extends", beforeExpr),
  21973. _export: kw("export"),
  21974. _import: kw("import", startsExpr),
  21975. _null: kw("null", startsExpr),
  21976. _true: kw("true", startsExpr),
  21977. _false: kw("false", startsExpr),
  21978. _in: kw("in", {beforeExpr: true, binop: 7}),
  21979. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  21980. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  21981. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  21982. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  21983. };
  21984. // Matches a whole line break (where CRLF is considered a single
  21985. // line break). Used to count lines.
  21986. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  21987. var lineBreakG = new RegExp(lineBreak.source, "g");
  21988. function isNewLine(code, ecma2019String) {
  21989. return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
  21990. }
  21991. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  21992. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  21993. var ref = Object.prototype;
  21994. var hasOwnProperty = ref.hasOwnProperty;
  21995. var toString = ref.toString;
  21996. // Checks if an object has a property.
  21997. function has(obj, propName) {
  21998. return hasOwnProperty.call(obj, propName)
  21999. }
  22000. var isArray = Array.isArray || (function (obj) { return (
  22001. toString.call(obj) === "[object Array]"
  22002. ); });
  22003. function wordsRegexp(words) {
  22004. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  22005. }
  22006. // These are used when `options.locations` is on, for the
  22007. // `startLoc` and `endLoc` properties.
  22008. var Position = function Position(line, col) {
  22009. this.line = line;
  22010. this.column = col;
  22011. };
  22012. Position.prototype.offset = function offset (n) {
  22013. return new Position(this.line, this.column + n)
  22014. };
  22015. var SourceLocation = function SourceLocation(p, start, end) {
  22016. this.start = start;
  22017. this.end = end;
  22018. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  22019. };
  22020. // The `getLineInfo` function is mostly useful when the
  22021. // `locations` option is off (for performance reasons) and you
  22022. // want to find the line/column position for a given character
  22023. // offset. `input` should be the code string that the offset refers
  22024. // into.
  22025. function getLineInfo(input, offset) {
  22026. for (var line = 1, cur = 0;;) {
  22027. lineBreakG.lastIndex = cur;
  22028. var match = lineBreakG.exec(input);
  22029. if (match && match.index < offset) {
  22030. ++line;
  22031. cur = match.index + match[0].length;
  22032. } else {
  22033. return new Position(line, offset - cur)
  22034. }
  22035. }
  22036. }
  22037. // A second argument must be given to configure the parser process.
  22038. // These options are recognized (only `ecmaVersion` is required):
  22039. var defaultOptions = {
  22040. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  22041. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  22042. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  22043. // latest version the library supports). This influences support
  22044. // for strict mode, the set of reserved words, and support for
  22045. // new syntax features.
  22046. ecmaVersion: null,
  22047. // `sourceType` indicates the mode the code should be parsed in.
  22048. // Can be either `"script"` or `"module"`. This influences global
  22049. // strict mode and parsing of `import` and `export` declarations.
  22050. sourceType: "script",
  22051. // `onInsertedSemicolon` can be a callback that will be called
  22052. // when a semicolon is automatically inserted. It will be passed
  22053. // the position of the comma as an offset, and if `locations` is
  22054. // enabled, it is given the location as a `{line, column}` object
  22055. // as second argument.
  22056. onInsertedSemicolon: null,
  22057. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  22058. // trailing commas.
  22059. onTrailingComma: null,
  22060. // By default, reserved words are only enforced if ecmaVersion >= 5.
  22061. // Set `allowReserved` to a boolean value to explicitly turn this on
  22062. // an off. When this option has the value "never", reserved words
  22063. // and keywords can also not be used as property names.
  22064. allowReserved: null,
  22065. // When enabled, a return at the top level is not considered an
  22066. // error.
  22067. allowReturnOutsideFunction: false,
  22068. // When enabled, import/export statements are not constrained to
  22069. // appearing at the top of the program, and an import.meta expression
  22070. // in a script isn't considered an error.
  22071. allowImportExportEverywhere: false,
  22072. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  22073. // When enabled, await identifiers are allowed to appear at the top-level scope,
  22074. // but they are still not allowed in non-async functions.
  22075. allowAwaitOutsideFunction: null,
  22076. // When enabled, super identifiers are not constrained to
  22077. // appearing in methods and do not raise an error when they appear elsewhere.
  22078. allowSuperOutsideMethod: null,
  22079. // When enabled, hashbang directive in the beginning of file
  22080. // is allowed and treated as a line comment.
  22081. allowHashBang: false,
  22082. // When `locations` is on, `loc` properties holding objects with
  22083. // `start` and `end` properties in `{line, column}` form (with
  22084. // line being 1-based and column 0-based) will be attached to the
  22085. // nodes.
  22086. locations: false,
  22087. // A function can be passed as `onToken` option, which will
  22088. // cause Acorn to call that function with object in the same
  22089. // format as tokens returned from `tokenizer().getToken()`. Note
  22090. // that you are not allowed to call the parser from the
  22091. // callback—that will corrupt its internal state.
  22092. onToken: null,
  22093. // A function can be passed as `onComment` option, which will
  22094. // cause Acorn to call that function with `(block, text, start,
  22095. // end)` parameters whenever a comment is skipped. `block` is a
  22096. // boolean indicating whether this is a block (`/* */`) comment,
  22097. // `text` is the content of the comment, and `start` and `end` are
  22098. // character offsets that denote the start and end of the comment.
  22099. // When the `locations` option is on, two more parameters are
  22100. // passed, the full `{line, column}` locations of the start and
  22101. // end of the comments. Note that you are not allowed to call the
  22102. // parser from the callback—that will corrupt its internal state.
  22103. onComment: null,
  22104. // Nodes have their start and end characters offsets recorded in
  22105. // `start` and `end` properties (directly on the node, rather than
  22106. // the `loc` object, which holds line/column data. To also add a
  22107. // [semi-standardized][range] `range` property holding a `[start,
  22108. // end]` array with the same numbers, set the `ranges` option to
  22109. // `true`.
  22110. //
  22111. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  22112. ranges: false,
  22113. // It is possible to parse multiple files into a single AST by
  22114. // passing the tree produced by parsing the first file as
  22115. // `program` option in subsequent parses. This will add the
  22116. // toplevel forms of the parsed file to the `Program` (top) node
  22117. // of an existing parse tree.
  22118. program: null,
  22119. // When `locations` is on, you can pass this to record the source
  22120. // file in every node's `loc` object.
  22121. sourceFile: null,
  22122. // This value, if given, is stored in every node, whether
  22123. // `locations` is on or off.
  22124. directSourceFile: null,
  22125. // When enabled, parenthesized expressions are represented by
  22126. // (non-standard) ParenthesizedExpression nodes
  22127. preserveParens: false
  22128. };
  22129. // Interpret and default an options object
  22130. var warnedAboutEcmaVersion = false;
  22131. function getOptions(opts) {
  22132. var options = {};
  22133. for (var opt in defaultOptions)
  22134. { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  22135. if (options.ecmaVersion === "latest") {
  22136. options.ecmaVersion = 1e8;
  22137. } else if (options.ecmaVersion == null) {
  22138. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  22139. warnedAboutEcmaVersion = true;
  22140. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  22141. }
  22142. options.ecmaVersion = 11;
  22143. } else if (options.ecmaVersion >= 2015) {
  22144. options.ecmaVersion -= 2009;
  22145. }
  22146. if (options.allowReserved == null)
  22147. { options.allowReserved = options.ecmaVersion < 5; }
  22148. if (isArray(options.onToken)) {
  22149. var tokens = options.onToken;
  22150. options.onToken = function (token) { return tokens.push(token); };
  22151. }
  22152. if (isArray(options.onComment))
  22153. { options.onComment = pushComment(options, options.onComment); }
  22154. return options
  22155. }
  22156. function pushComment(options, array) {
  22157. return function(block, text, start, end, startLoc, endLoc) {
  22158. var comment = {
  22159. type: block ? "Block" : "Line",
  22160. value: text,
  22161. start: start,
  22162. end: end
  22163. };
  22164. if (options.locations)
  22165. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  22166. if (options.ranges)
  22167. { comment.range = [start, end]; }
  22168. array.push(comment);
  22169. }
  22170. }
  22171. // Each scope gets a bitset that may contain these flags
  22172. var
  22173. SCOPE_TOP = 1,
  22174. SCOPE_FUNCTION = 2,
  22175. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
  22176. SCOPE_ASYNC = 4,
  22177. SCOPE_GENERATOR = 8,
  22178. SCOPE_ARROW = 16,
  22179. SCOPE_SIMPLE_CATCH = 32,
  22180. SCOPE_SUPER = 64,
  22181. SCOPE_DIRECT_SUPER = 128;
  22182. function functionFlags(async, generator) {
  22183. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  22184. }
  22185. // Used in checkLVal* and declareName to determine the type of a binding
  22186. var
  22187. BIND_NONE = 0, // Not a binding
  22188. BIND_VAR = 1, // Var-style binding
  22189. BIND_LEXICAL = 2, // Let- or const-style binding
  22190. BIND_FUNCTION = 3, // Function declaration
  22191. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  22192. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  22193. var Parser = function Parser(options, input, startPos) {
  22194. this.options = options = getOptions(options);
  22195. this.sourceFile = options.sourceFile;
  22196. this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  22197. var reserved = "";
  22198. if (options.allowReserved !== true) {
  22199. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  22200. if (options.sourceType === "module") { reserved += " await"; }
  22201. }
  22202. this.reservedWords = wordsRegexp(reserved);
  22203. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  22204. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  22205. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  22206. this.input = String(input);
  22207. // Used to signal to callers of `readWord1` whether the word
  22208. // contained any escape sequences. This is needed because words with
  22209. // escape sequences must not be interpreted as keywords.
  22210. this.containsEsc = false;
  22211. // Set up token state
  22212. // The current position of the tokenizer in the input.
  22213. if (startPos) {
  22214. this.pos = startPos;
  22215. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  22216. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  22217. } else {
  22218. this.pos = this.lineStart = 0;
  22219. this.curLine = 1;
  22220. }
  22221. // Properties of the current token:
  22222. // Its type
  22223. this.type = types.eof;
  22224. // For tokens that include more information than their type, the value
  22225. this.value = null;
  22226. // Its start and end offset
  22227. this.start = this.end = this.pos;
  22228. // And, if locations are used, the {line, column} object
  22229. // corresponding to those offsets
  22230. this.startLoc = this.endLoc = this.curPosition();
  22231. // Position information for the previous token
  22232. this.lastTokEndLoc = this.lastTokStartLoc = null;
  22233. this.lastTokStart = this.lastTokEnd = this.pos;
  22234. // The context stack is used to superficially track syntactic
  22235. // context to predict whether a regular expression is allowed in a
  22236. // given position.
  22237. this.context = this.initialContext();
  22238. this.exprAllowed = true;
  22239. // Figure out if it's a module code.
  22240. this.inModule = options.sourceType === "module";
  22241. this.strict = this.inModule || this.strictDirective(this.pos);
  22242. // Used to signify the start of a potential arrow function
  22243. this.potentialArrowAt = -1;
  22244. this.potentialArrowInForAwait = false;
  22245. // Positions to delayed-check that yield/await does not exist in default parameters.
  22246. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  22247. // Labels in scope.
  22248. this.labels = [];
  22249. // Thus-far undefined exports.
  22250. this.undefinedExports = Object.create(null);
  22251. // If enabled, skip leading hashbang line.
  22252. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  22253. { this.skipLineComment(2); }
  22254. // Scope tracking for duplicate variable names (see scope.js)
  22255. this.scopeStack = [];
  22256. this.enterScope(SCOPE_TOP);
  22257. // For RegExp validation
  22258. this.regexpState = null;
  22259. // The stack of private names.
  22260. // Each element has two properties: 'declared' and 'used'.
  22261. // When it exited from the outermost class definition, all used private names must be declared.
  22262. this.privateNameStack = [];
  22263. };
  22264. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
  22265. Parser.prototype.parse = function parse () {
  22266. var node = this.options.program || this.startNode();
  22267. this.nextToken();
  22268. return this.parseTopLevel(node)
  22269. };
  22270. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  22271. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  22272. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  22273. prototypeAccessors.canAwait.get = function () {
  22274. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  22275. var scope = this.scopeStack[i];
  22276. if (scope.inClassFieldInit) { return false }
  22277. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  22278. }
  22279. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  22280. };
  22281. prototypeAccessors.allowSuper.get = function () {
  22282. var ref = this.currentThisScope();
  22283. var flags = ref.flags;
  22284. var inClassFieldInit = ref.inClassFieldInit;
  22285. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  22286. };
  22287. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  22288. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  22289. prototypeAccessors.inNonArrowFunction.get = function () {
  22290. var ref = this.currentThisScope();
  22291. var flags = ref.flags;
  22292. var inClassFieldInit = ref.inClassFieldInit;
  22293. return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit
  22294. };
  22295. Parser.extend = function extend () {
  22296. var plugins = [], len = arguments.length;
  22297. while ( len-- ) plugins[ len ] = arguments[ len ];
  22298. var cls = this;
  22299. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  22300. return cls
  22301. };
  22302. Parser.parse = function parse (input, options) {
  22303. return new this(options, input).parse()
  22304. };
  22305. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  22306. var parser = new this(options, input, pos);
  22307. parser.nextToken();
  22308. return parser.parseExpression()
  22309. };
  22310. Parser.tokenizer = function tokenizer (input, options) {
  22311. return new this(options, input)
  22312. };
  22313. Object.defineProperties( Parser.prototype, prototypeAccessors );
  22314. var pp = Parser.prototype;
  22315. // ## Parser utilities
  22316. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  22317. pp.strictDirective = function(start) {
  22318. for (;;) {
  22319. // Try to find string literal.
  22320. skipWhiteSpace.lastIndex = start;
  22321. start += skipWhiteSpace.exec(this.input)[0].length;
  22322. var match = literal.exec(this.input.slice(start));
  22323. if (!match) { return false }
  22324. if ((match[1] || match[2]) === "use strict") {
  22325. skipWhiteSpace.lastIndex = start + match[0].length;
  22326. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  22327. var next = this.input.charAt(end);
  22328. return next === ";" || next === "}" ||
  22329. (lineBreak.test(spaceAfter[0]) &&
  22330. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  22331. }
  22332. start += match[0].length;
  22333. // Skip semicolon, if any.
  22334. skipWhiteSpace.lastIndex = start;
  22335. start += skipWhiteSpace.exec(this.input)[0].length;
  22336. if (this.input[start] === ";")
  22337. { start++; }
  22338. }
  22339. };
  22340. // Predicate that tests whether the next token is of the given
  22341. // type, and if yes, consumes it as a side effect.
  22342. pp.eat = function(type) {
  22343. if (this.type === type) {
  22344. this.next();
  22345. return true
  22346. } else {
  22347. return false
  22348. }
  22349. };
  22350. // Tests whether parsed token is a contextual keyword.
  22351. pp.isContextual = function(name) {
  22352. return this.type === types.name && this.value === name && !this.containsEsc
  22353. };
  22354. // Consumes contextual keyword if possible.
  22355. pp.eatContextual = function(name) {
  22356. if (!this.isContextual(name)) { return false }
  22357. this.next();
  22358. return true
  22359. };
  22360. // Asserts that following token is given contextual keyword.
  22361. pp.expectContextual = function(name) {
  22362. if (!this.eatContextual(name)) { this.unexpected(); }
  22363. };
  22364. // Test whether a semicolon can be inserted at the current position.
  22365. pp.canInsertSemicolon = function() {
  22366. return this.type === types.eof ||
  22367. this.type === types.braceR ||
  22368. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  22369. };
  22370. pp.insertSemicolon = function() {
  22371. if (this.canInsertSemicolon()) {
  22372. if (this.options.onInsertedSemicolon)
  22373. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  22374. return true
  22375. }
  22376. };
  22377. // Consume a semicolon, or, failing that, see if we are allowed to
  22378. // pretend that there is a semicolon at this position.
  22379. pp.semicolon = function() {
  22380. if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
  22381. };
  22382. pp.afterTrailingComma = function(tokType, notNext) {
  22383. if (this.type === tokType) {
  22384. if (this.options.onTrailingComma)
  22385. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  22386. if (!notNext)
  22387. { this.next(); }
  22388. return true
  22389. }
  22390. };
  22391. // Expect a token of a given type. If found, consume it, otherwise,
  22392. // raise an unexpected token error.
  22393. pp.expect = function(type) {
  22394. this.eat(type) || this.unexpected();
  22395. };
  22396. // Raise an unexpected token error.
  22397. pp.unexpected = function(pos) {
  22398. this.raise(pos != null ? pos : this.start, "Unexpected token");
  22399. };
  22400. function DestructuringErrors() {
  22401. this.shorthandAssign =
  22402. this.trailingComma =
  22403. this.parenthesizedAssign =
  22404. this.parenthesizedBind =
  22405. this.doubleProto =
  22406. -1;
  22407. }
  22408. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  22409. if (!refDestructuringErrors) { return }
  22410. if (refDestructuringErrors.trailingComma > -1)
  22411. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  22412. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  22413. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  22414. };
  22415. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  22416. if (!refDestructuringErrors) { return false }
  22417. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  22418. var doubleProto = refDestructuringErrors.doubleProto;
  22419. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  22420. if (shorthandAssign >= 0)
  22421. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  22422. if (doubleProto >= 0)
  22423. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  22424. };
  22425. pp.checkYieldAwaitInDefaultParams = function() {
  22426. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  22427. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  22428. if (this.awaitPos)
  22429. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  22430. };
  22431. pp.isSimpleAssignTarget = function(expr) {
  22432. if (expr.type === "ParenthesizedExpression")
  22433. { return this.isSimpleAssignTarget(expr.expression) }
  22434. return expr.type === "Identifier" || expr.type === "MemberExpression"
  22435. };
  22436. var pp$1 = Parser.prototype;
  22437. // ### Statement parsing
  22438. // Parse a program. Initializes the parser, reads any number of
  22439. // statements, and wraps them in a Program node. Optionally takes a
  22440. // `program` argument. If present, the statements will be appended
  22441. // to its body instead of creating a new node.
  22442. pp$1.parseTopLevel = function(node) {
  22443. var exports = Object.create(null);
  22444. if (!node.body) { node.body = []; }
  22445. while (this.type !== types.eof) {
  22446. var stmt = this.parseStatement(null, true, exports);
  22447. node.body.push(stmt);
  22448. }
  22449. if (this.inModule)
  22450. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  22451. {
  22452. var name = list[i];
  22453. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  22454. } }
  22455. this.adaptDirectivePrologue(node.body);
  22456. this.next();
  22457. node.sourceType = this.options.sourceType;
  22458. return this.finishNode(node, "Program")
  22459. };
  22460. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  22461. pp$1.isLet = function(context) {
  22462. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  22463. skipWhiteSpace.lastIndex = this.pos;
  22464. var skip = skipWhiteSpace.exec(this.input);
  22465. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  22466. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  22467. // Statement) is allowed here. If context is not empty then only a Statement
  22468. // is allowed. However, `let [` is an explicit negative lookahead for
  22469. // ExpressionStatement, so special-case it first.
  22470. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  22471. if (context) { return false }
  22472. if (nextCh === 123) { return true } // '{'
  22473. if (isIdentifierStart(nextCh, true)) {
  22474. var pos = next + 1;
  22475. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  22476. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  22477. var ident = this.input.slice(next, pos);
  22478. if (!keywordRelationalOperator.test(ident)) { return true }
  22479. }
  22480. return false
  22481. };
  22482. // check 'async [no LineTerminator here] function'
  22483. // - 'async /*foo*/ function' is OK.
  22484. // - 'async /*\n*/ function' is invalid.
  22485. pp$1.isAsyncFunction = function() {
  22486. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  22487. { return false }
  22488. skipWhiteSpace.lastIndex = this.pos;
  22489. var skip = skipWhiteSpace.exec(this.input);
  22490. var next = this.pos + skip[0].length, after;
  22491. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  22492. this.input.slice(next, next + 8) === "function" &&
  22493. (next + 8 === this.input.length ||
  22494. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  22495. };
  22496. // Parse a single statement.
  22497. //
  22498. // If expecting a statement and finding a slash operator, parse a
  22499. // regular expression literal. This is to handle cases like
  22500. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  22501. // does not help.
  22502. pp$1.parseStatement = function(context, topLevel, exports) {
  22503. var starttype = this.type, node = this.startNode(), kind;
  22504. if (this.isLet(context)) {
  22505. starttype = types._var;
  22506. kind = "let";
  22507. }
  22508. // Most types of statements are recognized by the keyword they
  22509. // start with. Many are trivial to parse, some require a bit of
  22510. // complexity.
  22511. switch (starttype) {
  22512. case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  22513. case types._debugger: return this.parseDebuggerStatement(node)
  22514. case types._do: return this.parseDoStatement(node)
  22515. case types._for: return this.parseForStatement(node)
  22516. case types._function:
  22517. // Function as sole body of either an if statement or a labeled statement
  22518. // works, but not when it is part of a labeled statement that is the sole
  22519. // body of an if statement.
  22520. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  22521. return this.parseFunctionStatement(node, false, !context)
  22522. case types._class:
  22523. if (context) { this.unexpected(); }
  22524. return this.parseClass(node, true)
  22525. case types._if: return this.parseIfStatement(node)
  22526. case types._return: return this.parseReturnStatement(node)
  22527. case types._switch: return this.parseSwitchStatement(node)
  22528. case types._throw: return this.parseThrowStatement(node)
  22529. case types._try: return this.parseTryStatement(node)
  22530. case types._const: case types._var:
  22531. kind = kind || this.value;
  22532. if (context && kind !== "var") { this.unexpected(); }
  22533. return this.parseVarStatement(node, kind)
  22534. case types._while: return this.parseWhileStatement(node)
  22535. case types._with: return this.parseWithStatement(node)
  22536. case types.braceL: return this.parseBlock(true, node)
  22537. case types.semi: return this.parseEmptyStatement(node)
  22538. case types._export:
  22539. case types._import:
  22540. if (this.options.ecmaVersion > 10 && starttype === types._import) {
  22541. skipWhiteSpace.lastIndex = this.pos;
  22542. var skip = skipWhiteSpace.exec(this.input);
  22543. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  22544. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  22545. { return this.parseExpressionStatement(node, this.parseExpression()) }
  22546. }
  22547. if (!this.options.allowImportExportEverywhere) {
  22548. if (!topLevel)
  22549. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  22550. if (!this.inModule)
  22551. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  22552. }
  22553. return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
  22554. // If the statement does not start with a statement keyword or a
  22555. // brace, it's an ExpressionStatement or LabeledStatement. We
  22556. // simply start parsing an expression, and afterwards, if the
  22557. // next token is a colon and the expression was a simple
  22558. // Identifier node, we switch to interpreting it as a label.
  22559. default:
  22560. if (this.isAsyncFunction()) {
  22561. if (context) { this.unexpected(); }
  22562. this.next();
  22563. return this.parseFunctionStatement(node, true, !context)
  22564. }
  22565. var maybeName = this.value, expr = this.parseExpression();
  22566. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
  22567. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  22568. else { return this.parseExpressionStatement(node, expr) }
  22569. }
  22570. };
  22571. pp$1.parseBreakContinueStatement = function(node, keyword) {
  22572. var isBreak = keyword === "break";
  22573. this.next();
  22574. if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
  22575. else if (this.type !== types.name) { this.unexpected(); }
  22576. else {
  22577. node.label = this.parseIdent();
  22578. this.semicolon();
  22579. }
  22580. // Verify that there is an actual destination to break or
  22581. // continue to.
  22582. var i = 0;
  22583. for (; i < this.labels.length; ++i) {
  22584. var lab = this.labels[i];
  22585. if (node.label == null || lab.name === node.label.name) {
  22586. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  22587. if (node.label && isBreak) { break }
  22588. }
  22589. }
  22590. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  22591. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  22592. };
  22593. pp$1.parseDebuggerStatement = function(node) {
  22594. this.next();
  22595. this.semicolon();
  22596. return this.finishNode(node, "DebuggerStatement")
  22597. };
  22598. pp$1.parseDoStatement = function(node) {
  22599. this.next();
  22600. this.labels.push(loopLabel);
  22601. node.body = this.parseStatement("do");
  22602. this.labels.pop();
  22603. this.expect(types._while);
  22604. node.test = this.parseParenExpression();
  22605. if (this.options.ecmaVersion >= 6)
  22606. { this.eat(types.semi); }
  22607. else
  22608. { this.semicolon(); }
  22609. return this.finishNode(node, "DoWhileStatement")
  22610. };
  22611. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  22612. // loop is non-trivial. Basically, we have to parse the init `var`
  22613. // statement or expression, disallowing the `in` operator (see
  22614. // the second parameter to `parseExpression`), and then check
  22615. // whether the next token is `in` or `of`. When there is no init
  22616. // part (semicolon immediately after the opening parenthesis), it
  22617. // is a regular `for` loop.
  22618. pp$1.parseForStatement = function(node) {
  22619. this.next();
  22620. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  22621. this.labels.push(loopLabel);
  22622. this.enterScope(0);
  22623. this.expect(types.parenL);
  22624. if (this.type === types.semi) {
  22625. if (awaitAt > -1) { this.unexpected(awaitAt); }
  22626. return this.parseFor(node, null)
  22627. }
  22628. var isLet = this.isLet();
  22629. if (this.type === types._var || this.type === types._const || isLet) {
  22630. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  22631. this.next();
  22632. this.parseVar(init$1, true, kind);
  22633. this.finishNode(init$1, "VariableDeclaration");
  22634. if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  22635. if (this.options.ecmaVersion >= 9) {
  22636. if (this.type === types._in) {
  22637. if (awaitAt > -1) { this.unexpected(awaitAt); }
  22638. } else { node.await = awaitAt > -1; }
  22639. }
  22640. return this.parseForIn(node, init$1)
  22641. }
  22642. if (awaitAt > -1) { this.unexpected(awaitAt); }
  22643. return this.parseFor(node, init$1)
  22644. }
  22645. var refDestructuringErrors = new DestructuringErrors;
  22646. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  22647. if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  22648. if (this.options.ecmaVersion >= 9) {
  22649. if (this.type === types._in) {
  22650. if (awaitAt > -1) { this.unexpected(awaitAt); }
  22651. } else { node.await = awaitAt > -1; }
  22652. }
  22653. this.toAssignable(init, false, refDestructuringErrors);
  22654. this.checkLValPattern(init);
  22655. return this.parseForIn(node, init)
  22656. } else {
  22657. this.checkExpressionErrors(refDestructuringErrors, true);
  22658. }
  22659. if (awaitAt > -1) { this.unexpected(awaitAt); }
  22660. return this.parseFor(node, init)
  22661. };
  22662. pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  22663. this.next();
  22664. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  22665. };
  22666. pp$1.parseIfStatement = function(node) {
  22667. this.next();
  22668. node.test = this.parseParenExpression();
  22669. // allow function declarations in branches, but only in non-strict mode
  22670. node.consequent = this.parseStatement("if");
  22671. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  22672. return this.finishNode(node, "IfStatement")
  22673. };
  22674. pp$1.parseReturnStatement = function(node) {
  22675. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  22676. { this.raise(this.start, "'return' outside of function"); }
  22677. this.next();
  22678. // In `return` (and `break`/`continue`), the keywords with
  22679. // optional arguments, we eagerly look for a semicolon or the
  22680. // possibility to insert one.
  22681. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
  22682. else { node.argument = this.parseExpression(); this.semicolon(); }
  22683. return this.finishNode(node, "ReturnStatement")
  22684. };
  22685. pp$1.parseSwitchStatement = function(node) {
  22686. this.next();
  22687. node.discriminant = this.parseParenExpression();
  22688. node.cases = [];
  22689. this.expect(types.braceL);
  22690. this.labels.push(switchLabel);
  22691. this.enterScope(0);
  22692. // Statements under must be grouped (by label) in SwitchCase
  22693. // nodes. `cur` is used to keep the node that we are currently
  22694. // adding statements to.
  22695. var cur;
  22696. for (var sawDefault = false; this.type !== types.braceR;) {
  22697. if (this.type === types._case || this.type === types._default) {
  22698. var isCase = this.type === types._case;
  22699. if (cur) { this.finishNode(cur, "SwitchCase"); }
  22700. node.cases.push(cur = this.startNode());
  22701. cur.consequent = [];
  22702. this.next();
  22703. if (isCase) {
  22704. cur.test = this.parseExpression();
  22705. } else {
  22706. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  22707. sawDefault = true;
  22708. cur.test = null;
  22709. }
  22710. this.expect(types.colon);
  22711. } else {
  22712. if (!cur) { this.unexpected(); }
  22713. cur.consequent.push(this.parseStatement(null));
  22714. }
  22715. }
  22716. this.exitScope();
  22717. if (cur) { this.finishNode(cur, "SwitchCase"); }
  22718. this.next(); // Closing brace
  22719. this.labels.pop();
  22720. return this.finishNode(node, "SwitchStatement")
  22721. };
  22722. pp$1.parseThrowStatement = function(node) {
  22723. this.next();
  22724. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  22725. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  22726. node.argument = this.parseExpression();
  22727. this.semicolon();
  22728. return this.finishNode(node, "ThrowStatement")
  22729. };
  22730. // Reused empty array added for node fields that are always empty.
  22731. var empty = [];
  22732. pp$1.parseTryStatement = function(node) {
  22733. this.next();
  22734. node.block = this.parseBlock();
  22735. node.handler = null;
  22736. if (this.type === types._catch) {
  22737. var clause = this.startNode();
  22738. this.next();
  22739. if (this.eat(types.parenL)) {
  22740. clause.param = this.parseBindingAtom();
  22741. var simple = clause.param.type === "Identifier";
  22742. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  22743. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  22744. this.expect(types.parenR);
  22745. } else {
  22746. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  22747. clause.param = null;
  22748. this.enterScope(0);
  22749. }
  22750. clause.body = this.parseBlock(false);
  22751. this.exitScope();
  22752. node.handler = this.finishNode(clause, "CatchClause");
  22753. }
  22754. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  22755. if (!node.handler && !node.finalizer)
  22756. { this.raise(node.start, "Missing catch or finally clause"); }
  22757. return this.finishNode(node, "TryStatement")
  22758. };
  22759. pp$1.parseVarStatement = function(node, kind) {
  22760. this.next();
  22761. this.parseVar(node, false, kind);
  22762. this.semicolon();
  22763. return this.finishNode(node, "VariableDeclaration")
  22764. };
  22765. pp$1.parseWhileStatement = function(node) {
  22766. this.next();
  22767. node.test = this.parseParenExpression();
  22768. this.labels.push(loopLabel);
  22769. node.body = this.parseStatement("while");
  22770. this.labels.pop();
  22771. return this.finishNode(node, "WhileStatement")
  22772. };
  22773. pp$1.parseWithStatement = function(node) {
  22774. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  22775. this.next();
  22776. node.object = this.parseParenExpression();
  22777. node.body = this.parseStatement("with");
  22778. return this.finishNode(node, "WithStatement")
  22779. };
  22780. pp$1.parseEmptyStatement = function(node) {
  22781. this.next();
  22782. return this.finishNode(node, "EmptyStatement")
  22783. };
  22784. pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  22785. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  22786. {
  22787. var label = list[i$1];
  22788. if (label.name === maybeName)
  22789. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  22790. } }
  22791. var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
  22792. for (var i = this.labels.length - 1; i >= 0; i--) {
  22793. var label$1 = this.labels[i];
  22794. if (label$1.statementStart === node.start) {
  22795. // Update information about previous labels on this node
  22796. label$1.statementStart = this.start;
  22797. label$1.kind = kind;
  22798. } else { break }
  22799. }
  22800. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  22801. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  22802. this.labels.pop();
  22803. node.label = expr;
  22804. return this.finishNode(node, "LabeledStatement")
  22805. };
  22806. pp$1.parseExpressionStatement = function(node, expr) {
  22807. node.expression = expr;
  22808. this.semicolon();
  22809. return this.finishNode(node, "ExpressionStatement")
  22810. };
  22811. // Parse a semicolon-enclosed block of statements, handling `"use
  22812. // strict"` declarations when `allowStrict` is true (used for
  22813. // function bodies).
  22814. pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  22815. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  22816. if ( node === void 0 ) node = this.startNode();
  22817. node.body = [];
  22818. this.expect(types.braceL);
  22819. if (createNewLexicalScope) { this.enterScope(0); }
  22820. while (this.type !== types.braceR) {
  22821. var stmt = this.parseStatement(null);
  22822. node.body.push(stmt);
  22823. }
  22824. if (exitStrict) { this.strict = false; }
  22825. this.next();
  22826. if (createNewLexicalScope) { this.exitScope(); }
  22827. return this.finishNode(node, "BlockStatement")
  22828. };
  22829. // Parse a regular `for` loop. The disambiguation code in
  22830. // `parseStatement` will already have parsed the init statement or
  22831. // expression.
  22832. pp$1.parseFor = function(node, init) {
  22833. node.init = init;
  22834. this.expect(types.semi);
  22835. node.test = this.type === types.semi ? null : this.parseExpression();
  22836. this.expect(types.semi);
  22837. node.update = this.type === types.parenR ? null : this.parseExpression();
  22838. this.expect(types.parenR);
  22839. node.body = this.parseStatement("for");
  22840. this.exitScope();
  22841. this.labels.pop();
  22842. return this.finishNode(node, "ForStatement")
  22843. };
  22844. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  22845. // same from parser's perspective.
  22846. pp$1.parseForIn = function(node, init) {
  22847. var isForIn = this.type === types._in;
  22848. this.next();
  22849. if (
  22850. init.type === "VariableDeclaration" &&
  22851. init.declarations[0].init != null &&
  22852. (
  22853. !isForIn ||
  22854. this.options.ecmaVersion < 8 ||
  22855. this.strict ||
  22856. init.kind !== "var" ||
  22857. init.declarations[0].id.type !== "Identifier"
  22858. )
  22859. ) {
  22860. this.raise(
  22861. init.start,
  22862. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  22863. );
  22864. }
  22865. node.left = init;
  22866. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  22867. this.expect(types.parenR);
  22868. node.body = this.parseStatement("for");
  22869. this.exitScope();
  22870. this.labels.pop();
  22871. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  22872. };
  22873. // Parse a list of variable declarations.
  22874. pp$1.parseVar = function(node, isFor, kind) {
  22875. node.declarations = [];
  22876. node.kind = kind;
  22877. for (;;) {
  22878. var decl = this.startNode();
  22879. this.parseVarId(decl, kind);
  22880. if (this.eat(types.eq)) {
  22881. decl.init = this.parseMaybeAssign(isFor);
  22882. } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  22883. this.unexpected();
  22884. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
  22885. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  22886. } else {
  22887. decl.init = null;
  22888. }
  22889. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  22890. if (!this.eat(types.comma)) { break }
  22891. }
  22892. return node
  22893. };
  22894. pp$1.parseVarId = function(decl, kind) {
  22895. decl.id = this.parseBindingAtom();
  22896. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  22897. };
  22898. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  22899. // Parse a function declaration or literal (depending on the
  22900. // `statement & FUNC_STATEMENT`).
  22901. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  22902. pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
  22903. this.initFunction(node);
  22904. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  22905. if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
  22906. { this.unexpected(); }
  22907. node.generator = this.eat(types.star);
  22908. }
  22909. if (this.options.ecmaVersion >= 8)
  22910. { node.async = !!isAsync; }
  22911. if (statement & FUNC_STATEMENT) {
  22912. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
  22913. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  22914. // If it is a regular function declaration in sloppy mode, then it is
  22915. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  22916. // mode depends on properties of the current scope (see
  22917. // treatFunctionsAsVar).
  22918. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  22919. }
  22920. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  22921. this.yieldPos = 0;
  22922. this.awaitPos = 0;
  22923. this.awaitIdentPos = 0;
  22924. this.enterScope(functionFlags(node.async, node.generator));
  22925. if (!(statement & FUNC_STATEMENT))
  22926. { node.id = this.type === types.name ? this.parseIdent() : null; }
  22927. this.parseFunctionParams(node);
  22928. this.parseFunctionBody(node, allowExpressionBody, false);
  22929. this.yieldPos = oldYieldPos;
  22930. this.awaitPos = oldAwaitPos;
  22931. this.awaitIdentPos = oldAwaitIdentPos;
  22932. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  22933. };
  22934. pp$1.parseFunctionParams = function(node) {
  22935. this.expect(types.parenL);
  22936. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  22937. this.checkYieldAwaitInDefaultParams();
  22938. };
  22939. // Parse a class declaration or literal (depending on the
  22940. // `isStatement` parameter).
  22941. pp$1.parseClass = function(node, isStatement) {
  22942. this.next();
  22943. // ecma-262 14.6 Class Definitions
  22944. // A class definition is always strict mode code.
  22945. var oldStrict = this.strict;
  22946. this.strict = true;
  22947. this.parseClassId(node, isStatement);
  22948. this.parseClassSuper(node);
  22949. var privateNameMap = this.enterClassBody();
  22950. var classBody = this.startNode();
  22951. var hadConstructor = false;
  22952. classBody.body = [];
  22953. this.expect(types.braceL);
  22954. while (this.type !== types.braceR) {
  22955. var element = this.parseClassElement(node.superClass !== null);
  22956. if (element) {
  22957. classBody.body.push(element);
  22958. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  22959. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  22960. hadConstructor = true;
  22961. } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  22962. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  22963. }
  22964. }
  22965. }
  22966. this.strict = oldStrict;
  22967. this.next();
  22968. node.body = this.finishNode(classBody, "ClassBody");
  22969. this.exitClassBody();
  22970. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  22971. };
  22972. pp$1.parseClassElement = function(constructorAllowsSuper) {
  22973. if (this.eat(types.semi)) { return null }
  22974. var ecmaVersion = this.options.ecmaVersion;
  22975. var node = this.startNode();
  22976. var keyName = "";
  22977. var isGenerator = false;
  22978. var isAsync = false;
  22979. var kind = "method";
  22980. // Parse modifiers
  22981. node.static = false;
  22982. if (this.eatContextual("static")) {
  22983. if (this.isClassElementNameStart() || this.type === types.star) {
  22984. node.static = true;
  22985. } else {
  22986. keyName = "static";
  22987. }
  22988. }
  22989. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  22990. if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) {
  22991. isAsync = true;
  22992. } else {
  22993. keyName = "async";
  22994. }
  22995. }
  22996. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) {
  22997. isGenerator = true;
  22998. }
  22999. if (!keyName && !isAsync && !isGenerator) {
  23000. var lastValue = this.value;
  23001. if (this.eatContextual("get") || this.eatContextual("set")) {
  23002. if (this.isClassElementNameStart()) {
  23003. kind = lastValue;
  23004. } else {
  23005. keyName = lastValue;
  23006. }
  23007. }
  23008. }
  23009. // Parse element name
  23010. if (keyName) {
  23011. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  23012. // The last token is any of those. Make it the element name.
  23013. node.computed = false;
  23014. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  23015. node.key.name = keyName;
  23016. this.finishNode(node.key, "Identifier");
  23017. } else {
  23018. this.parseClassElementName(node);
  23019. }
  23020. // Parse element value
  23021. if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) {
  23022. var isConstructor = !node.static && checkKeyName(node, "constructor");
  23023. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  23024. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  23025. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  23026. node.kind = isConstructor ? "constructor" : kind;
  23027. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  23028. } else {
  23029. this.parseClassField(node);
  23030. }
  23031. return node
  23032. };
  23033. pp$1.isClassElementNameStart = function() {
  23034. return (
  23035. this.type === types.name ||
  23036. this.type === types.privateId ||
  23037. this.type === types.num ||
  23038. this.type === types.string ||
  23039. this.type === types.bracketL ||
  23040. this.type.keyword
  23041. )
  23042. };
  23043. pp$1.parseClassElementName = function(element) {
  23044. if (this.type === types.privateId) {
  23045. if (this.value === "constructor") {
  23046. this.raise(this.start, "Classes can't have an element named '#constructor'");
  23047. }
  23048. element.computed = false;
  23049. element.key = this.parsePrivateIdent();
  23050. } else {
  23051. this.parsePropertyName(element);
  23052. }
  23053. };
  23054. pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  23055. // Check key and flags
  23056. var key = method.key;
  23057. if (method.kind === "constructor") {
  23058. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  23059. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  23060. } else if (method.static && checkKeyName(method, "prototype")) {
  23061. this.raise(key.start, "Classes may not have a static property named prototype");
  23062. }
  23063. // Parse value
  23064. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  23065. // Check value
  23066. if (method.kind === "get" && value.params.length !== 0)
  23067. { this.raiseRecoverable(value.start, "getter should have no params"); }
  23068. if (method.kind === "set" && value.params.length !== 1)
  23069. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  23070. if (method.kind === "set" && value.params[0].type === "RestElement")
  23071. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  23072. return this.finishNode(method, "MethodDefinition")
  23073. };
  23074. pp$1.parseClassField = function(field) {
  23075. if (checkKeyName(field, "constructor")) {
  23076. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  23077. } else if (field.static && checkKeyName(field, "prototype")) {
  23078. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  23079. }
  23080. if (this.eat(types.eq)) {
  23081. // To raise SyntaxError if 'arguments' exists in the initializer.
  23082. var scope = this.currentThisScope();
  23083. var inClassFieldInit = scope.inClassFieldInit;
  23084. scope.inClassFieldInit = true;
  23085. field.value = this.parseMaybeAssign();
  23086. scope.inClassFieldInit = inClassFieldInit;
  23087. } else {
  23088. field.value = null;
  23089. }
  23090. this.semicolon();
  23091. return this.finishNode(field, "PropertyDefinition")
  23092. };
  23093. pp$1.parseClassId = function(node, isStatement) {
  23094. if (this.type === types.name) {
  23095. node.id = this.parseIdent();
  23096. if (isStatement)
  23097. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  23098. } else {
  23099. if (isStatement === true)
  23100. { this.unexpected(); }
  23101. node.id = null;
  23102. }
  23103. };
  23104. pp$1.parseClassSuper = function(node) {
  23105. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  23106. };
  23107. pp$1.enterClassBody = function() {
  23108. var element = {declared: Object.create(null), used: []};
  23109. this.privateNameStack.push(element);
  23110. return element.declared
  23111. };
  23112. pp$1.exitClassBody = function() {
  23113. var ref = this.privateNameStack.pop();
  23114. var declared = ref.declared;
  23115. var used = ref.used;
  23116. var len = this.privateNameStack.length;
  23117. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  23118. for (var i = 0; i < used.length; ++i) {
  23119. var id = used[i];
  23120. if (!has(declared, id.name)) {
  23121. if (parent) {
  23122. parent.used.push(id);
  23123. } else {
  23124. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  23125. }
  23126. }
  23127. }
  23128. };
  23129. function isPrivateNameConflicted(privateNameMap, element) {
  23130. var name = element.key.name;
  23131. var curr = privateNameMap[name];
  23132. var next = "true";
  23133. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  23134. next = (element.static ? "s" : "i") + element.kind;
  23135. }
  23136. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  23137. if (
  23138. curr === "iget" && next === "iset" ||
  23139. curr === "iset" && next === "iget" ||
  23140. curr === "sget" && next === "sset" ||
  23141. curr === "sset" && next === "sget"
  23142. ) {
  23143. privateNameMap[name] = "true";
  23144. return false
  23145. } else if (!curr) {
  23146. privateNameMap[name] = next;
  23147. return false
  23148. } else {
  23149. return true
  23150. }
  23151. }
  23152. function checkKeyName(node, name) {
  23153. var computed = node.computed;
  23154. var key = node.key;
  23155. return !computed && (
  23156. key.type === "Identifier" && key.name === name ||
  23157. key.type === "Literal" && key.value === name
  23158. )
  23159. }
  23160. // Parses module export declaration.
  23161. pp$1.parseExport = function(node, exports) {
  23162. this.next();
  23163. // export * from '...'
  23164. if (this.eat(types.star)) {
  23165. if (this.options.ecmaVersion >= 11) {
  23166. if (this.eatContextual("as")) {
  23167. node.exported = this.parseIdent(true);
  23168. this.checkExport(exports, node.exported.name, this.lastTokStart);
  23169. } else {
  23170. node.exported = null;
  23171. }
  23172. }
  23173. this.expectContextual("from");
  23174. if (this.type !== types.string) { this.unexpected(); }
  23175. node.source = this.parseExprAtom();
  23176. this.semicolon();
  23177. return this.finishNode(node, "ExportAllDeclaration")
  23178. }
  23179. if (this.eat(types._default)) { // export default ...
  23180. this.checkExport(exports, "default", this.lastTokStart);
  23181. var isAsync;
  23182. if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
  23183. var fNode = this.startNode();
  23184. this.next();
  23185. if (isAsync) { this.next(); }
  23186. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  23187. } else if (this.type === types._class) {
  23188. var cNode = this.startNode();
  23189. node.declaration = this.parseClass(cNode, "nullableID");
  23190. } else {
  23191. node.declaration = this.parseMaybeAssign();
  23192. this.semicolon();
  23193. }
  23194. return this.finishNode(node, "ExportDefaultDeclaration")
  23195. }
  23196. // export var|const|let|function|class ...
  23197. if (this.shouldParseExportStatement()) {
  23198. node.declaration = this.parseStatement(null);
  23199. if (node.declaration.type === "VariableDeclaration")
  23200. { this.checkVariableExport(exports, node.declaration.declarations); }
  23201. else
  23202. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  23203. node.specifiers = [];
  23204. node.source = null;
  23205. } else { // export { x, y as z } [from '...']
  23206. node.declaration = null;
  23207. node.specifiers = this.parseExportSpecifiers(exports);
  23208. if (this.eatContextual("from")) {
  23209. if (this.type !== types.string) { this.unexpected(); }
  23210. node.source = this.parseExprAtom();
  23211. } else {
  23212. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  23213. // check for keywords used as local names
  23214. var spec = list[i];
  23215. this.checkUnreserved(spec.local);
  23216. // check if export is defined
  23217. this.checkLocalExport(spec.local);
  23218. }
  23219. node.source = null;
  23220. }
  23221. this.semicolon();
  23222. }
  23223. return this.finishNode(node, "ExportNamedDeclaration")
  23224. };
  23225. pp$1.checkExport = function(exports, name, pos) {
  23226. if (!exports) { return }
  23227. if (has(exports, name))
  23228. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  23229. exports[name] = true;
  23230. };
  23231. pp$1.checkPatternExport = function(exports, pat) {
  23232. var type = pat.type;
  23233. if (type === "Identifier")
  23234. { this.checkExport(exports, pat.name, pat.start); }
  23235. else if (type === "ObjectPattern")
  23236. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  23237. {
  23238. var prop = list[i];
  23239. this.checkPatternExport(exports, prop);
  23240. } }
  23241. else if (type === "ArrayPattern")
  23242. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  23243. var elt = list$1[i$1];
  23244. if (elt) { this.checkPatternExport(exports, elt); }
  23245. } }
  23246. else if (type === "Property")
  23247. { this.checkPatternExport(exports, pat.value); }
  23248. else if (type === "AssignmentPattern")
  23249. { this.checkPatternExport(exports, pat.left); }
  23250. else if (type === "RestElement")
  23251. { this.checkPatternExport(exports, pat.argument); }
  23252. else if (type === "ParenthesizedExpression")
  23253. { this.checkPatternExport(exports, pat.expression); }
  23254. };
  23255. pp$1.checkVariableExport = function(exports, decls) {
  23256. if (!exports) { return }
  23257. for (var i = 0, list = decls; i < list.length; i += 1)
  23258. {
  23259. var decl = list[i];
  23260. this.checkPatternExport(exports, decl.id);
  23261. }
  23262. };
  23263. pp$1.shouldParseExportStatement = function() {
  23264. return this.type.keyword === "var" ||
  23265. this.type.keyword === "const" ||
  23266. this.type.keyword === "class" ||
  23267. this.type.keyword === "function" ||
  23268. this.isLet() ||
  23269. this.isAsyncFunction()
  23270. };
  23271. // Parses a comma-separated list of module exports.
  23272. pp$1.parseExportSpecifiers = function(exports) {
  23273. var nodes = [], first = true;
  23274. // export { x, y as z } [from '...']
  23275. this.expect(types.braceL);
  23276. while (!this.eat(types.braceR)) {
  23277. if (!first) {
  23278. this.expect(types.comma);
  23279. if (this.afterTrailingComma(types.braceR)) { break }
  23280. } else { first = false; }
  23281. var node = this.startNode();
  23282. node.local = this.parseIdent(true);
  23283. node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
  23284. this.checkExport(exports, node.exported.name, node.exported.start);
  23285. nodes.push(this.finishNode(node, "ExportSpecifier"));
  23286. }
  23287. return nodes
  23288. };
  23289. // Parses import declaration.
  23290. pp$1.parseImport = function(node) {
  23291. this.next();
  23292. // import '...'
  23293. if (this.type === types.string) {
  23294. node.specifiers = empty;
  23295. node.source = this.parseExprAtom();
  23296. } else {
  23297. node.specifiers = this.parseImportSpecifiers();
  23298. this.expectContextual("from");
  23299. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  23300. }
  23301. this.semicolon();
  23302. return this.finishNode(node, "ImportDeclaration")
  23303. };
  23304. // Parses a comma-separated list of module imports.
  23305. pp$1.parseImportSpecifiers = function() {
  23306. var nodes = [], first = true;
  23307. if (this.type === types.name) {
  23308. // import defaultObj, { x, y as z } from '...'
  23309. var node = this.startNode();
  23310. node.local = this.parseIdent();
  23311. this.checkLValSimple(node.local, BIND_LEXICAL);
  23312. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  23313. if (!this.eat(types.comma)) { return nodes }
  23314. }
  23315. if (this.type === types.star) {
  23316. var node$1 = this.startNode();
  23317. this.next();
  23318. this.expectContextual("as");
  23319. node$1.local = this.parseIdent();
  23320. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  23321. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  23322. return nodes
  23323. }
  23324. this.expect(types.braceL);
  23325. while (!this.eat(types.braceR)) {
  23326. if (!first) {
  23327. this.expect(types.comma);
  23328. if (this.afterTrailingComma(types.braceR)) { break }
  23329. } else { first = false; }
  23330. var node$2 = this.startNode();
  23331. node$2.imported = this.parseIdent(true);
  23332. if (this.eatContextual("as")) {
  23333. node$2.local = this.parseIdent();
  23334. } else {
  23335. this.checkUnreserved(node$2.imported);
  23336. node$2.local = node$2.imported;
  23337. }
  23338. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  23339. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  23340. }
  23341. return nodes
  23342. };
  23343. // Set `ExpressionStatement#directive` property for directive prologues.
  23344. pp$1.adaptDirectivePrologue = function(statements) {
  23345. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  23346. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  23347. }
  23348. };
  23349. pp$1.isDirectiveCandidate = function(statement) {
  23350. return (
  23351. statement.type === "ExpressionStatement" &&
  23352. statement.expression.type === "Literal" &&
  23353. typeof statement.expression.value === "string" &&
  23354. // Reject parenthesized strings.
  23355. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  23356. )
  23357. };
  23358. var pp$2 = Parser.prototype;
  23359. // Convert existing expression atom to assignable pattern
  23360. // if possible.
  23361. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  23362. if (this.options.ecmaVersion >= 6 && node) {
  23363. switch (node.type) {
  23364. case "Identifier":
  23365. if (this.inAsync && node.name === "await")
  23366. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  23367. break
  23368. case "ObjectPattern":
  23369. case "ArrayPattern":
  23370. case "AssignmentPattern":
  23371. case "RestElement":
  23372. break
  23373. case "ObjectExpression":
  23374. node.type = "ObjectPattern";
  23375. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  23376. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  23377. var prop = list[i];
  23378. this.toAssignable(prop, isBinding);
  23379. // Early error:
  23380. // AssignmentRestProperty[Yield, Await] :
  23381. // `...` DestructuringAssignmentTarget[Yield, Await]
  23382. //
  23383. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  23384. if (
  23385. prop.type === "RestElement" &&
  23386. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  23387. ) {
  23388. this.raise(prop.argument.start, "Unexpected token");
  23389. }
  23390. }
  23391. break
  23392. case "Property":
  23393. // AssignmentProperty has type === "Property"
  23394. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  23395. this.toAssignable(node.value, isBinding);
  23396. break
  23397. case "ArrayExpression":
  23398. node.type = "ArrayPattern";
  23399. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  23400. this.toAssignableList(node.elements, isBinding);
  23401. break
  23402. case "SpreadElement":
  23403. node.type = "RestElement";
  23404. this.toAssignable(node.argument, isBinding);
  23405. if (node.argument.type === "AssignmentPattern")
  23406. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  23407. break
  23408. case "AssignmentExpression":
  23409. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  23410. node.type = "AssignmentPattern";
  23411. delete node.operator;
  23412. this.toAssignable(node.left, isBinding);
  23413. break
  23414. case "ParenthesizedExpression":
  23415. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  23416. break
  23417. case "ChainExpression":
  23418. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  23419. break
  23420. case "MemberExpression":
  23421. if (!isBinding) { break }
  23422. default:
  23423. this.raise(node.start, "Assigning to rvalue");
  23424. }
  23425. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  23426. return node
  23427. };
  23428. // Convert list of expression atoms to binding list.
  23429. pp$2.toAssignableList = function(exprList, isBinding) {
  23430. var end = exprList.length;
  23431. for (var i = 0; i < end; i++) {
  23432. var elt = exprList[i];
  23433. if (elt) { this.toAssignable(elt, isBinding); }
  23434. }
  23435. if (end) {
  23436. var last = exprList[end - 1];
  23437. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  23438. { this.unexpected(last.argument.start); }
  23439. }
  23440. return exprList
  23441. };
  23442. // Parses spread element.
  23443. pp$2.parseSpread = function(refDestructuringErrors) {
  23444. var node = this.startNode();
  23445. this.next();
  23446. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  23447. return this.finishNode(node, "SpreadElement")
  23448. };
  23449. pp$2.parseRestBinding = function() {
  23450. var node = this.startNode();
  23451. this.next();
  23452. // RestElement inside of a function parameter must be an identifier
  23453. if (this.options.ecmaVersion === 6 && this.type !== types.name)
  23454. { this.unexpected(); }
  23455. node.argument = this.parseBindingAtom();
  23456. return this.finishNode(node, "RestElement")
  23457. };
  23458. // Parses lvalue (assignable) atom.
  23459. pp$2.parseBindingAtom = function() {
  23460. if (this.options.ecmaVersion >= 6) {
  23461. switch (this.type) {
  23462. case types.bracketL:
  23463. var node = this.startNode();
  23464. this.next();
  23465. node.elements = this.parseBindingList(types.bracketR, true, true);
  23466. return this.finishNode(node, "ArrayPattern")
  23467. case types.braceL:
  23468. return this.parseObj(true)
  23469. }
  23470. }
  23471. return this.parseIdent()
  23472. };
  23473. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  23474. var elts = [], first = true;
  23475. while (!this.eat(close)) {
  23476. if (first) { first = false; }
  23477. else { this.expect(types.comma); }
  23478. if (allowEmpty && this.type === types.comma) {
  23479. elts.push(null);
  23480. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  23481. break
  23482. } else if (this.type === types.ellipsis) {
  23483. var rest = this.parseRestBinding();
  23484. this.parseBindingListItem(rest);
  23485. elts.push(rest);
  23486. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  23487. this.expect(close);
  23488. break
  23489. } else {
  23490. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  23491. this.parseBindingListItem(elem);
  23492. elts.push(elem);
  23493. }
  23494. }
  23495. return elts
  23496. };
  23497. pp$2.parseBindingListItem = function(param) {
  23498. return param
  23499. };
  23500. // Parses assignment pattern around given atom if possible.
  23501. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  23502. left = left || this.parseBindingAtom();
  23503. if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
  23504. var node = this.startNodeAt(startPos, startLoc);
  23505. node.left = left;
  23506. node.right = this.parseMaybeAssign();
  23507. return this.finishNode(node, "AssignmentPattern")
  23508. };
  23509. // The following three functions all verify that a node is an lvalue —
  23510. // something that can be bound, or assigned to. In order to do so, they perform
  23511. // a variety of checks:
  23512. //
  23513. // - Check that none of the bound/assigned-to identifiers are reserved words.
  23514. // - Record name declarations for bindings in the appropriate scope.
  23515. // - Check duplicate argument names, if checkClashes is set.
  23516. //
  23517. // If a complex binding pattern is encountered (e.g., object and array
  23518. // destructuring), the entire pattern is recursively checked.
  23519. //
  23520. // There are three versions of checkLVal*() appropriate for different
  23521. // circumstances:
  23522. //
  23523. // - checkLValSimple() shall be used if the syntactic construct supports
  23524. // nothing other than identifiers and member expressions. Parenthesized
  23525. // expressions are also correctly handled. This is generally appropriate for
  23526. // constructs for which the spec says
  23527. //
  23528. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  23529. // > simple.
  23530. //
  23531. // It is also appropriate for checking if an identifier is valid and not
  23532. // defined elsewhere, like import declarations or function/class identifiers.
  23533. //
  23534. // Examples where this is used include:
  23535. // a += …;
  23536. // import a from '…';
  23537. // where a is the node to be checked.
  23538. //
  23539. // - checkLValPattern() shall be used if the syntactic construct supports
  23540. // anything checkLValSimple() supports, as well as object and array
  23541. // destructuring patterns. This is generally appropriate for constructs for
  23542. // which the spec says
  23543. //
  23544. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  23545. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  23546. // > simple.
  23547. //
  23548. // Examples where this is used include:
  23549. // (a = …);
  23550. // const a = …;
  23551. // try { … } catch (a) { … }
  23552. // where a is the node to be checked.
  23553. //
  23554. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  23555. // anything checkLValPattern() supports, as well as default assignment
  23556. // patterns, rest elements, and other constructs that may appear within an
  23557. // object or array destructuring pattern.
  23558. //
  23559. // As a special case, function parameters also use checkLValInnerPattern(),
  23560. // as they also support defaults and rest constructs.
  23561. //
  23562. // These functions deliberately support both assignment and binding constructs,
  23563. // as the logic for both is exceedingly similar. If the node is the target of
  23564. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  23565. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  23566. // BIND_LEXICAL.
  23567. //
  23568. // If the function is called with a non-BIND_NONE bindingType, then
  23569. // additionally a checkClashes object may be specified to allow checking for
  23570. // duplicate argument names. checkClashes is ignored if the provided construct
  23571. // is an assignment (i.e., bindingType is BIND_NONE).
  23572. pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
  23573. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  23574. var isBind = bindingType !== BIND_NONE;
  23575. switch (expr.type) {
  23576. case "Identifier":
  23577. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  23578. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  23579. if (isBind) {
  23580. if (bindingType === BIND_LEXICAL && expr.name === "let")
  23581. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  23582. if (checkClashes) {
  23583. if (has(checkClashes, expr.name))
  23584. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  23585. checkClashes[expr.name] = true;
  23586. }
  23587. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  23588. }
  23589. break
  23590. case "ChainExpression":
  23591. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  23592. break
  23593. case "MemberExpression":
  23594. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  23595. break
  23596. case "ParenthesizedExpression":
  23597. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  23598. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  23599. default:
  23600. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  23601. }
  23602. };
  23603. pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
  23604. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  23605. switch (expr.type) {
  23606. case "ObjectPattern":
  23607. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  23608. var prop = list[i];
  23609. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  23610. }
  23611. break
  23612. case "ArrayPattern":
  23613. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  23614. var elem = list$1[i$1];
  23615. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  23616. }
  23617. break
  23618. default:
  23619. this.checkLValSimple(expr, bindingType, checkClashes);
  23620. }
  23621. };
  23622. pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  23623. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  23624. switch (expr.type) {
  23625. case "Property":
  23626. // AssignmentProperty has type === "Property"
  23627. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  23628. break
  23629. case "AssignmentPattern":
  23630. this.checkLValPattern(expr.left, bindingType, checkClashes);
  23631. break
  23632. case "RestElement":
  23633. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  23634. break
  23635. default:
  23636. this.checkLValPattern(expr, bindingType, checkClashes);
  23637. }
  23638. };
  23639. // A recursive descent parser operates by defining functions for all
  23640. var pp$3 = Parser.prototype;
  23641. // Check if property name clashes with already added.
  23642. // Object/class getters and setters are not allowed to clash —
  23643. // either with each other or with an init property — and in
  23644. // strict mode, init properties are also not allowed to be repeated.
  23645. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  23646. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  23647. { return }
  23648. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  23649. { return }
  23650. var key = prop.key;
  23651. var name;
  23652. switch (key.type) {
  23653. case "Identifier": name = key.name; break
  23654. case "Literal": name = String(key.value); break
  23655. default: return
  23656. }
  23657. var kind = prop.kind;
  23658. if (this.options.ecmaVersion >= 6) {
  23659. if (name === "__proto__" && kind === "init") {
  23660. if (propHash.proto) {
  23661. if (refDestructuringErrors) {
  23662. if (refDestructuringErrors.doubleProto < 0)
  23663. { refDestructuringErrors.doubleProto = key.start; }
  23664. // Backwards-compat kludge. Can be removed in version 6.0
  23665. } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  23666. }
  23667. propHash.proto = true;
  23668. }
  23669. return
  23670. }
  23671. name = "$" + name;
  23672. var other = propHash[name];
  23673. if (other) {
  23674. var redefinition;
  23675. if (kind === "init") {
  23676. redefinition = this.strict && other.init || other.get || other.set;
  23677. } else {
  23678. redefinition = other.init || other[kind];
  23679. }
  23680. if (redefinition)
  23681. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  23682. } else {
  23683. other = propHash[name] = {
  23684. init: false,
  23685. get: false,
  23686. set: false
  23687. };
  23688. }
  23689. other[kind] = true;
  23690. };
  23691. // ### Expression parsing
  23692. // These nest, from the most general expression type at the top to
  23693. // 'atomic', nondivisible expression types at the bottom. Most of
  23694. // the functions will simply let the function(s) below them parse,
  23695. // and, *if* the syntactic construct they handle is present, wrap
  23696. // the AST node that the inner parser gave them in another node.
  23697. // Parse a full expression. The optional arguments are used to
  23698. // forbid the `in` operator (in for loops initalization expressions)
  23699. // and provide reference for storing '=' operator inside shorthand
  23700. // property assignment in contexts where both object expression
  23701. // and object pattern might appear (so it's possible to raise
  23702. // delayed syntax error at correct position).
  23703. pp$3.parseExpression = function(forInit, refDestructuringErrors) {
  23704. var startPos = this.start, startLoc = this.startLoc;
  23705. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  23706. if (this.type === types.comma) {
  23707. var node = this.startNodeAt(startPos, startLoc);
  23708. node.expressions = [expr];
  23709. while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  23710. return this.finishNode(node, "SequenceExpression")
  23711. }
  23712. return expr
  23713. };
  23714. // Parse an assignment expression. This includes applications of
  23715. // operators like `+=`.
  23716. pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  23717. if (this.isContextual("yield")) {
  23718. if (this.inGenerator) { return this.parseYield(forInit) }
  23719. // The tokenizer will assume an expression is allowed after
  23720. // `yield`, but this isn't that kind of yield
  23721. else { this.exprAllowed = false; }
  23722. }
  23723. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  23724. if (refDestructuringErrors) {
  23725. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  23726. oldTrailingComma = refDestructuringErrors.trailingComma;
  23727. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  23728. } else {
  23729. refDestructuringErrors = new DestructuringErrors;
  23730. ownDestructuringErrors = true;
  23731. }
  23732. var startPos = this.start, startLoc = this.startLoc;
  23733. if (this.type === types.parenL || this.type === types.name) {
  23734. this.potentialArrowAt = this.start;
  23735. this.potentialArrowInForAwait = forInit === "await";
  23736. }
  23737. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  23738. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  23739. if (this.type.isAssign) {
  23740. var node = this.startNodeAt(startPos, startLoc);
  23741. node.operator = this.value;
  23742. if (this.type === types.eq)
  23743. { left = this.toAssignable(left, false, refDestructuringErrors); }
  23744. if (!ownDestructuringErrors) {
  23745. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  23746. }
  23747. if (refDestructuringErrors.shorthandAssign >= left.start)
  23748. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  23749. if (this.type === types.eq)
  23750. { this.checkLValPattern(left); }
  23751. else
  23752. { this.checkLValSimple(left); }
  23753. node.left = left;
  23754. this.next();
  23755. node.right = this.parseMaybeAssign(forInit);
  23756. return this.finishNode(node, "AssignmentExpression")
  23757. } else {
  23758. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  23759. }
  23760. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  23761. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  23762. return left
  23763. };
  23764. // Parse a ternary conditional (`?:`) operator.
  23765. pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  23766. var startPos = this.start, startLoc = this.startLoc;
  23767. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  23768. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  23769. if (this.eat(types.question)) {
  23770. var node = this.startNodeAt(startPos, startLoc);
  23771. node.test = expr;
  23772. node.consequent = this.parseMaybeAssign();
  23773. this.expect(types.colon);
  23774. node.alternate = this.parseMaybeAssign(forInit);
  23775. return this.finishNode(node, "ConditionalExpression")
  23776. }
  23777. return expr
  23778. };
  23779. // Start the precedence parser.
  23780. pp$3.parseExprOps = function(forInit, refDestructuringErrors) {
  23781. var startPos = this.start, startLoc = this.startLoc;
  23782. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  23783. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  23784. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  23785. };
  23786. // Parse binary operators with the operator precedence parsing
  23787. // algorithm. `left` is the left-hand side of the operator.
  23788. // `minPrec` provides context that allows the function to stop and
  23789. // defer further parser to one of its callers when it encounters an
  23790. // operator that has a lower precedence than the set it is parsing.
  23791. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  23792. var prec = this.type.binop;
  23793. if (prec != null && (!forInit || this.type !== types._in)) {
  23794. if (prec > minPrec) {
  23795. var logical = this.type === types.logicalOR || this.type === types.logicalAND;
  23796. var coalesce = this.type === types.coalesce;
  23797. if (coalesce) {
  23798. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  23799. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  23800. prec = types.logicalAND.binop;
  23801. }
  23802. var op = this.value;
  23803. this.next();
  23804. var startPos = this.start, startLoc = this.startLoc;
  23805. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);
  23806. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  23807. if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
  23808. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  23809. }
  23810. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  23811. }
  23812. }
  23813. return left
  23814. };
  23815. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  23816. var node = this.startNodeAt(startPos, startLoc);
  23817. node.left = left;
  23818. node.operator = op;
  23819. node.right = right;
  23820. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  23821. };
  23822. // Parse unary operators, both prefix and postfix.
  23823. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
  23824. var startPos = this.start, startLoc = this.startLoc, expr;
  23825. if (this.isContextual("await") && this.canAwait) {
  23826. expr = this.parseAwait();
  23827. sawUnary = true;
  23828. } else if (this.type.prefix) {
  23829. var node = this.startNode(), update = this.type === types.incDec;
  23830. node.operator = this.value;
  23831. node.prefix = true;
  23832. this.next();
  23833. node.argument = this.parseMaybeUnary(null, true, update);
  23834. this.checkExpressionErrors(refDestructuringErrors, true);
  23835. if (update) { this.checkLValSimple(node.argument); }
  23836. else if (this.strict && node.operator === "delete" &&
  23837. node.argument.type === "Identifier")
  23838. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  23839. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  23840. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  23841. else { sawUnary = true; }
  23842. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  23843. } else {
  23844. expr = this.parseExprSubscripts(refDestructuringErrors);
  23845. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  23846. while (this.type.postfix && !this.canInsertSemicolon()) {
  23847. var node$1 = this.startNodeAt(startPos, startLoc);
  23848. node$1.operator = this.value;
  23849. node$1.prefix = false;
  23850. node$1.argument = expr;
  23851. this.checkLValSimple(expr);
  23852. this.next();
  23853. expr = this.finishNode(node$1, "UpdateExpression");
  23854. }
  23855. }
  23856. if (!incDec && this.eat(types.starstar)) {
  23857. if (sawUnary)
  23858. { this.unexpected(this.lastTokStart); }
  23859. else
  23860. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  23861. } else {
  23862. return expr
  23863. }
  23864. };
  23865. function isPrivateFieldAccess(node) {
  23866. return (
  23867. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  23868. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  23869. )
  23870. }
  23871. // Parse call, dot, and `[]`-subscript expressions.
  23872. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  23873. var startPos = this.start, startLoc = this.startLoc;
  23874. var expr = this.parseExprAtom(refDestructuringErrors);
  23875. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  23876. { return expr }
  23877. var result = this.parseSubscripts(expr, startPos, startLoc);
  23878. if (refDestructuringErrors && result.type === "MemberExpression") {
  23879. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  23880. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  23881. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  23882. }
  23883. return result
  23884. };
  23885. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  23886. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  23887. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  23888. this.potentialArrowAt === base.start;
  23889. var optionalChained = false;
  23890. while (true) {
  23891. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
  23892. if (element.optional) { optionalChained = true; }
  23893. if (element === base || element.type === "ArrowFunctionExpression") {
  23894. if (optionalChained) {
  23895. var chainNode = this.startNodeAt(startPos, startLoc);
  23896. chainNode.expression = element;
  23897. element = this.finishNode(chainNode, "ChainExpression");
  23898. }
  23899. return element
  23900. }
  23901. base = element;
  23902. }
  23903. };
  23904. pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  23905. var optionalSupported = this.options.ecmaVersion >= 11;
  23906. var optional = optionalSupported && this.eat(types.questionDot);
  23907. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  23908. var computed = this.eat(types.bracketL);
  23909. if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
  23910. var node = this.startNodeAt(startPos, startLoc);
  23911. node.object = base;
  23912. if (computed) {
  23913. node.property = this.parseExpression();
  23914. this.expect(types.bracketR);
  23915. } else if (this.type === types.privateId && base.type !== "Super") {
  23916. node.property = this.parsePrivateIdent();
  23917. } else {
  23918. node.property = this.parseIdent(this.options.allowReserved !== "never");
  23919. }
  23920. node.computed = !!computed;
  23921. if (optionalSupported) {
  23922. node.optional = optional;
  23923. }
  23924. base = this.finishNode(node, "MemberExpression");
  23925. } else if (!noCalls && this.eat(types.parenL)) {
  23926. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  23927. this.yieldPos = 0;
  23928. this.awaitPos = 0;
  23929. this.awaitIdentPos = 0;
  23930. var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  23931. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  23932. this.checkPatternErrors(refDestructuringErrors, false);
  23933. this.checkYieldAwaitInDefaultParams();
  23934. if (this.awaitIdentPos > 0)
  23935. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  23936. this.yieldPos = oldYieldPos;
  23937. this.awaitPos = oldAwaitPos;
  23938. this.awaitIdentPos = oldAwaitIdentPos;
  23939. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  23940. }
  23941. this.checkExpressionErrors(refDestructuringErrors, true);
  23942. this.yieldPos = oldYieldPos || this.yieldPos;
  23943. this.awaitPos = oldAwaitPos || this.awaitPos;
  23944. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  23945. var node$1 = this.startNodeAt(startPos, startLoc);
  23946. node$1.callee = base;
  23947. node$1.arguments = exprList;
  23948. if (optionalSupported) {
  23949. node$1.optional = optional;
  23950. }
  23951. base = this.finishNode(node$1, "CallExpression");
  23952. } else if (this.type === types.backQuote) {
  23953. if (optional || optionalChained) {
  23954. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  23955. }
  23956. var node$2 = this.startNodeAt(startPos, startLoc);
  23957. node$2.tag = base;
  23958. node$2.quasi = this.parseTemplate({isTagged: true});
  23959. base = this.finishNode(node$2, "TaggedTemplateExpression");
  23960. }
  23961. return base
  23962. };
  23963. // Parse an atomic expression — either a single token that is an
  23964. // expression, an expression started by a keyword like `function` or
  23965. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  23966. // or `{}`.
  23967. pp$3.parseExprAtom = function(refDestructuringErrors) {
  23968. // If a division operator appears in an expression position, the
  23969. // tokenizer got confused, and we force it to read a regexp instead.
  23970. if (this.type === types.slash) { this.readRegexp(); }
  23971. var node, canBeArrow = this.potentialArrowAt === this.start;
  23972. switch (this.type) {
  23973. case types._super:
  23974. if (!this.allowSuper)
  23975. { this.raise(this.start, "'super' keyword outside a method"); }
  23976. node = this.startNode();
  23977. this.next();
  23978. if (this.type === types.parenL && !this.allowDirectSuper)
  23979. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  23980. // The `super` keyword can appear at below:
  23981. // SuperProperty:
  23982. // super [ Expression ]
  23983. // super . IdentifierName
  23984. // SuperCall:
  23985. // super ( Arguments )
  23986. if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
  23987. { this.unexpected(); }
  23988. return this.finishNode(node, "Super")
  23989. case types._this:
  23990. node = this.startNode();
  23991. this.next();
  23992. return this.finishNode(node, "ThisExpression")
  23993. case types.name:
  23994. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  23995. var id = this.parseIdent(false);
  23996. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
  23997. { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
  23998. if (canBeArrow && !this.canInsertSemicolon()) {
  23999. if (this.eat(types.arrow))
  24000. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  24001. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc &&
  24002. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  24003. id = this.parseIdent(false);
  24004. if (this.canInsertSemicolon() || !this.eat(types.arrow))
  24005. { this.unexpected(); }
  24006. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  24007. }
  24008. }
  24009. return id
  24010. case types.regexp:
  24011. var value = this.value;
  24012. node = this.parseLiteral(value.value);
  24013. node.regex = {pattern: value.pattern, flags: value.flags};
  24014. return node
  24015. case types.num: case types.string:
  24016. return this.parseLiteral(this.value)
  24017. case types._null: case types._true: case types._false:
  24018. node = this.startNode();
  24019. node.value = this.type === types._null ? null : this.type === types._true;
  24020. node.raw = this.type.keyword;
  24021. this.next();
  24022. return this.finishNode(node, "Literal")
  24023. case types.parenL:
  24024. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  24025. if (refDestructuringErrors) {
  24026. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  24027. { refDestructuringErrors.parenthesizedAssign = start; }
  24028. if (refDestructuringErrors.parenthesizedBind < 0)
  24029. { refDestructuringErrors.parenthesizedBind = start; }
  24030. }
  24031. return expr
  24032. case types.bracketL:
  24033. node = this.startNode();
  24034. this.next();
  24035. node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
  24036. return this.finishNode(node, "ArrayExpression")
  24037. case types.braceL:
  24038. return this.parseObj(false, refDestructuringErrors)
  24039. case types._function:
  24040. node = this.startNode();
  24041. this.next();
  24042. return this.parseFunction(node, 0)
  24043. case types._class:
  24044. return this.parseClass(this.startNode(), false)
  24045. case types._new:
  24046. return this.parseNew()
  24047. case types.backQuote:
  24048. return this.parseTemplate()
  24049. case types._import:
  24050. if (this.options.ecmaVersion >= 11) {
  24051. return this.parseExprImport()
  24052. } else {
  24053. return this.unexpected()
  24054. }
  24055. default:
  24056. this.unexpected();
  24057. }
  24058. };
  24059. pp$3.parseExprImport = function() {
  24060. var node = this.startNode();
  24061. // Consume `import` as an identifier for `import.meta`.
  24062. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  24063. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  24064. var meta = this.parseIdent(true);
  24065. switch (this.type) {
  24066. case types.parenL:
  24067. return this.parseDynamicImport(node)
  24068. case types.dot:
  24069. node.meta = meta;
  24070. return this.parseImportMeta(node)
  24071. default:
  24072. this.unexpected();
  24073. }
  24074. };
  24075. pp$3.parseDynamicImport = function(node) {
  24076. this.next(); // skip `(`
  24077. // Parse node.source.
  24078. node.source = this.parseMaybeAssign();
  24079. // Verify ending.
  24080. if (!this.eat(types.parenR)) {
  24081. var errorPos = this.start;
  24082. if (this.eat(types.comma) && this.eat(types.parenR)) {
  24083. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  24084. } else {
  24085. this.unexpected(errorPos);
  24086. }
  24087. }
  24088. return this.finishNode(node, "ImportExpression")
  24089. };
  24090. pp$3.parseImportMeta = function(node) {
  24091. this.next(); // skip `.`
  24092. var containsEsc = this.containsEsc;
  24093. node.property = this.parseIdent(true);
  24094. if (node.property.name !== "meta")
  24095. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  24096. if (containsEsc)
  24097. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  24098. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  24099. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  24100. return this.finishNode(node, "MetaProperty")
  24101. };
  24102. pp$3.parseLiteral = function(value) {
  24103. var node = this.startNode();
  24104. node.value = value;
  24105. node.raw = this.input.slice(this.start, this.end);
  24106. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  24107. this.next();
  24108. return this.finishNode(node, "Literal")
  24109. };
  24110. pp$3.parseParenExpression = function() {
  24111. this.expect(types.parenL);
  24112. var val = this.parseExpression();
  24113. this.expect(types.parenR);
  24114. return val
  24115. };
  24116. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  24117. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  24118. if (this.options.ecmaVersion >= 6) {
  24119. this.next();
  24120. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  24121. var exprList = [], first = true, lastIsComma = false;
  24122. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  24123. this.yieldPos = 0;
  24124. this.awaitPos = 0;
  24125. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  24126. while (this.type !== types.parenR) {
  24127. first ? first = false : this.expect(types.comma);
  24128. if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
  24129. lastIsComma = true;
  24130. break
  24131. } else if (this.type === types.ellipsis) {
  24132. spreadStart = this.start;
  24133. exprList.push(this.parseParenItem(this.parseRestBinding()));
  24134. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  24135. break
  24136. } else {
  24137. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  24138. }
  24139. }
  24140. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  24141. this.expect(types.parenR);
  24142. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  24143. this.checkPatternErrors(refDestructuringErrors, false);
  24144. this.checkYieldAwaitInDefaultParams();
  24145. this.yieldPos = oldYieldPos;
  24146. this.awaitPos = oldAwaitPos;
  24147. return this.parseParenArrowList(startPos, startLoc, exprList)
  24148. }
  24149. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  24150. if (spreadStart) { this.unexpected(spreadStart); }
  24151. this.checkExpressionErrors(refDestructuringErrors, true);
  24152. this.yieldPos = oldYieldPos || this.yieldPos;
  24153. this.awaitPos = oldAwaitPos || this.awaitPos;
  24154. if (exprList.length > 1) {
  24155. val = this.startNodeAt(innerStartPos, innerStartLoc);
  24156. val.expressions = exprList;
  24157. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  24158. } else {
  24159. val = exprList[0];
  24160. }
  24161. } else {
  24162. val = this.parseParenExpression();
  24163. }
  24164. if (this.options.preserveParens) {
  24165. var par = this.startNodeAt(startPos, startLoc);
  24166. par.expression = val;
  24167. return this.finishNode(par, "ParenthesizedExpression")
  24168. } else {
  24169. return val
  24170. }
  24171. };
  24172. pp$3.parseParenItem = function(item) {
  24173. return item
  24174. };
  24175. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  24176. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  24177. };
  24178. // New's precedence is slightly tricky. It must allow its argument to
  24179. // be a `[]` or dot subscript expression, but not a call — at least,
  24180. // not without wrapping it in parentheses. Thus, it uses the noCalls
  24181. // argument to parseSubscripts to prevent it from consuming the
  24182. // argument list.
  24183. var empty$1 = [];
  24184. pp$3.parseNew = function() {
  24185. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  24186. var node = this.startNode();
  24187. var meta = this.parseIdent(true);
  24188. if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
  24189. node.meta = meta;
  24190. var containsEsc = this.containsEsc;
  24191. node.property = this.parseIdent(true);
  24192. if (node.property.name !== "target")
  24193. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  24194. if (containsEsc)
  24195. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  24196. if (!this.inNonArrowFunction)
  24197. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
  24198. return this.finishNode(node, "MetaProperty")
  24199. }
  24200. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
  24201. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  24202. if (isImport && node.callee.type === "ImportExpression") {
  24203. this.raise(startPos, "Cannot use new with import()");
  24204. }
  24205. if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
  24206. else { node.arguments = empty$1; }
  24207. return this.finishNode(node, "NewExpression")
  24208. };
  24209. // Parse template expression.
  24210. pp$3.parseTemplateElement = function(ref) {
  24211. var isTagged = ref.isTagged;
  24212. var elem = this.startNode();
  24213. if (this.type === types.invalidTemplate) {
  24214. if (!isTagged) {
  24215. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  24216. }
  24217. elem.value = {
  24218. raw: this.value,
  24219. cooked: null
  24220. };
  24221. } else {
  24222. elem.value = {
  24223. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  24224. cooked: this.value
  24225. };
  24226. }
  24227. this.next();
  24228. elem.tail = this.type === types.backQuote;
  24229. return this.finishNode(elem, "TemplateElement")
  24230. };
  24231. pp$3.parseTemplate = function(ref) {
  24232. if ( ref === void 0 ) ref = {};
  24233. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  24234. var node = this.startNode();
  24235. this.next();
  24236. node.expressions = [];
  24237. var curElt = this.parseTemplateElement({isTagged: isTagged});
  24238. node.quasis = [curElt];
  24239. while (!curElt.tail) {
  24240. if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
  24241. this.expect(types.dollarBraceL);
  24242. node.expressions.push(this.parseExpression());
  24243. this.expect(types.braceR);
  24244. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  24245. }
  24246. this.next();
  24247. return this.finishNode(node, "TemplateLiteral")
  24248. };
  24249. pp$3.isAsyncProp = function(prop) {
  24250. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  24251. (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
  24252. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  24253. };
  24254. // Parse an object literal or binding pattern.
  24255. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  24256. var node = this.startNode(), first = true, propHash = {};
  24257. node.properties = [];
  24258. this.next();
  24259. while (!this.eat(types.braceR)) {
  24260. if (!first) {
  24261. this.expect(types.comma);
  24262. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
  24263. } else { first = false; }
  24264. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  24265. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  24266. node.properties.push(prop);
  24267. }
  24268. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  24269. };
  24270. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  24271. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  24272. if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
  24273. if (isPattern) {
  24274. prop.argument = this.parseIdent(false);
  24275. if (this.type === types.comma) {
  24276. this.raise(this.start, "Comma is not permitted after the rest element");
  24277. }
  24278. return this.finishNode(prop, "RestElement")
  24279. }
  24280. // To disallow parenthesized identifier via `this.toAssignable()`.
  24281. if (this.type === types.parenL && refDestructuringErrors) {
  24282. if (refDestructuringErrors.parenthesizedAssign < 0) {
  24283. refDestructuringErrors.parenthesizedAssign = this.start;
  24284. }
  24285. if (refDestructuringErrors.parenthesizedBind < 0) {
  24286. refDestructuringErrors.parenthesizedBind = this.start;
  24287. }
  24288. }
  24289. // Parse argument.
  24290. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  24291. // To disallow trailing comma via `this.toAssignable()`.
  24292. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  24293. refDestructuringErrors.trailingComma = this.start;
  24294. }
  24295. // Finish
  24296. return this.finishNode(prop, "SpreadElement")
  24297. }
  24298. if (this.options.ecmaVersion >= 6) {
  24299. prop.method = false;
  24300. prop.shorthand = false;
  24301. if (isPattern || refDestructuringErrors) {
  24302. startPos = this.start;
  24303. startLoc = this.startLoc;
  24304. }
  24305. if (!isPattern)
  24306. { isGenerator = this.eat(types.star); }
  24307. }
  24308. var containsEsc = this.containsEsc;
  24309. this.parsePropertyName(prop);
  24310. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  24311. isAsync = true;
  24312. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  24313. this.parsePropertyName(prop, refDestructuringErrors);
  24314. } else {
  24315. isAsync = false;
  24316. }
  24317. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  24318. return this.finishNode(prop, "Property")
  24319. };
  24320. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  24321. if ((isGenerator || isAsync) && this.type === types.colon)
  24322. { this.unexpected(); }
  24323. if (this.eat(types.colon)) {
  24324. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  24325. prop.kind = "init";
  24326. } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
  24327. if (isPattern) { this.unexpected(); }
  24328. prop.kind = "init";
  24329. prop.method = true;
  24330. prop.value = this.parseMethod(isGenerator, isAsync);
  24331. } else if (!isPattern && !containsEsc &&
  24332. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  24333. (prop.key.name === "get" || prop.key.name === "set") &&
  24334. (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
  24335. if (isGenerator || isAsync) { this.unexpected(); }
  24336. prop.kind = prop.key.name;
  24337. this.parsePropertyName(prop);
  24338. prop.value = this.parseMethod(false);
  24339. var paramCount = prop.kind === "get" ? 0 : 1;
  24340. if (prop.value.params.length !== paramCount) {
  24341. var start = prop.value.start;
  24342. if (prop.kind === "get")
  24343. { this.raiseRecoverable(start, "getter should have no params"); }
  24344. else
  24345. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  24346. } else {
  24347. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  24348. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  24349. }
  24350. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  24351. if (isGenerator || isAsync) { this.unexpected(); }
  24352. this.checkUnreserved(prop.key);
  24353. if (prop.key.name === "await" && !this.awaitIdentPos)
  24354. { this.awaitIdentPos = startPos; }
  24355. prop.kind = "init";
  24356. if (isPattern) {
  24357. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  24358. } else if (this.type === types.eq && refDestructuringErrors) {
  24359. if (refDestructuringErrors.shorthandAssign < 0)
  24360. { refDestructuringErrors.shorthandAssign = this.start; }
  24361. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  24362. } else {
  24363. prop.value = this.copyNode(prop.key);
  24364. }
  24365. prop.shorthand = true;
  24366. } else { this.unexpected(); }
  24367. };
  24368. pp$3.parsePropertyName = function(prop) {
  24369. if (this.options.ecmaVersion >= 6) {
  24370. if (this.eat(types.bracketL)) {
  24371. prop.computed = true;
  24372. prop.key = this.parseMaybeAssign();
  24373. this.expect(types.bracketR);
  24374. return prop.key
  24375. } else {
  24376. prop.computed = false;
  24377. }
  24378. }
  24379. return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  24380. };
  24381. // Initialize empty function node.
  24382. pp$3.initFunction = function(node) {
  24383. node.id = null;
  24384. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  24385. if (this.options.ecmaVersion >= 8) { node.async = false; }
  24386. };
  24387. // Parse object or class method.
  24388. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  24389. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  24390. this.initFunction(node);
  24391. if (this.options.ecmaVersion >= 6)
  24392. { node.generator = isGenerator; }
  24393. if (this.options.ecmaVersion >= 8)
  24394. { node.async = !!isAsync; }
  24395. this.yieldPos = 0;
  24396. this.awaitPos = 0;
  24397. this.awaitIdentPos = 0;
  24398. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  24399. this.expect(types.parenL);
  24400. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  24401. this.checkYieldAwaitInDefaultParams();
  24402. this.parseFunctionBody(node, false, true);
  24403. this.yieldPos = oldYieldPos;
  24404. this.awaitPos = oldAwaitPos;
  24405. this.awaitIdentPos = oldAwaitIdentPos;
  24406. return this.finishNode(node, "FunctionExpression")
  24407. };
  24408. // Parse arrow function expression with given parameters.
  24409. pp$3.parseArrowExpression = function(node, params, isAsync) {
  24410. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  24411. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  24412. this.initFunction(node);
  24413. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  24414. this.yieldPos = 0;
  24415. this.awaitPos = 0;
  24416. this.awaitIdentPos = 0;
  24417. node.params = this.toAssignableList(params, true);
  24418. this.parseFunctionBody(node, true, false);
  24419. this.yieldPos = oldYieldPos;
  24420. this.awaitPos = oldAwaitPos;
  24421. this.awaitIdentPos = oldAwaitIdentPos;
  24422. return this.finishNode(node, "ArrowFunctionExpression")
  24423. };
  24424. // Parse function body and check parameters.
  24425. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  24426. var isExpression = isArrowFunction && this.type !== types.braceL;
  24427. var oldStrict = this.strict, useStrict = false;
  24428. if (isExpression) {
  24429. node.body = this.parseMaybeAssign();
  24430. node.expression = true;
  24431. this.checkParams(node, false);
  24432. } else {
  24433. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  24434. if (!oldStrict || nonSimple) {
  24435. useStrict = this.strictDirective(this.end);
  24436. // If this is a strict mode function, verify that argument names
  24437. // are not repeated, and it does not try to bind the words `eval`
  24438. // or `arguments`.
  24439. if (useStrict && nonSimple)
  24440. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  24441. }
  24442. // Start a new scope with regard to labels and the `inFunction`
  24443. // flag (restore them to their old value afterwards).
  24444. var oldLabels = this.labels;
  24445. this.labels = [];
  24446. if (useStrict) { this.strict = true; }
  24447. // Add the params to varDeclaredNames to ensure that an error is thrown
  24448. // if a let/const declaration in the function clashes with one of the params.
  24449. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  24450. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  24451. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  24452. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  24453. node.expression = false;
  24454. this.adaptDirectivePrologue(node.body.body);
  24455. this.labels = oldLabels;
  24456. }
  24457. this.exitScope();
  24458. };
  24459. pp$3.isSimpleParamList = function(params) {
  24460. for (var i = 0, list = params; i < list.length; i += 1)
  24461. {
  24462. var param = list[i];
  24463. if (param.type !== "Identifier") { return false
  24464. } }
  24465. return true
  24466. };
  24467. // Checks function params for various disallowed patterns such as using "eval"
  24468. // or "arguments" and duplicate parameters.
  24469. pp$3.checkParams = function(node, allowDuplicates) {
  24470. var nameHash = Object.create(null);
  24471. for (var i = 0, list = node.params; i < list.length; i += 1)
  24472. {
  24473. var param = list[i];
  24474. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  24475. }
  24476. };
  24477. // Parses a comma-separated list of expressions, and returns them as
  24478. // an array. `close` is the token type that ends the list, and
  24479. // `allowEmpty` can be turned on to allow subsequent commas with
  24480. // nothing in between them to be parsed as `null` (which is needed
  24481. // for array literals).
  24482. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  24483. var elts = [], first = true;
  24484. while (!this.eat(close)) {
  24485. if (!first) {
  24486. this.expect(types.comma);
  24487. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  24488. } else { first = false; }
  24489. var elt = (void 0);
  24490. if (allowEmpty && this.type === types.comma)
  24491. { elt = null; }
  24492. else if (this.type === types.ellipsis) {
  24493. elt = this.parseSpread(refDestructuringErrors);
  24494. if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
  24495. { refDestructuringErrors.trailingComma = this.start; }
  24496. } else {
  24497. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  24498. }
  24499. elts.push(elt);
  24500. }
  24501. return elts
  24502. };
  24503. pp$3.checkUnreserved = function(ref) {
  24504. var start = ref.start;
  24505. var end = ref.end;
  24506. var name = ref.name;
  24507. if (this.inGenerator && name === "yield")
  24508. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  24509. if (this.inAsync && name === "await")
  24510. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  24511. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  24512. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  24513. if (this.keywords.test(name))
  24514. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  24515. if (this.options.ecmaVersion < 6 &&
  24516. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  24517. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  24518. if (re.test(name)) {
  24519. if (!this.inAsync && name === "await")
  24520. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  24521. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  24522. }
  24523. };
  24524. // Parse the next token as an identifier. If `liberal` is true (used
  24525. // when parsing properties), it will also convert keywords into
  24526. // identifiers.
  24527. pp$3.parseIdent = function(liberal, isBinding) {
  24528. var node = this.startNode();
  24529. if (this.type === types.name) {
  24530. node.name = this.value;
  24531. } else if (this.type.keyword) {
  24532. node.name = this.type.keyword;
  24533. // To fix https://github.com/acornjs/acorn/issues/575
  24534. // `class` and `function` keywords push new context into this.context.
  24535. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  24536. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  24537. if ((node.name === "class" || node.name === "function") &&
  24538. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  24539. this.context.pop();
  24540. }
  24541. } else {
  24542. this.unexpected();
  24543. }
  24544. this.next(!!liberal);
  24545. this.finishNode(node, "Identifier");
  24546. if (!liberal) {
  24547. this.checkUnreserved(node);
  24548. if (node.name === "await" && !this.awaitIdentPos)
  24549. { this.awaitIdentPos = node.start; }
  24550. }
  24551. return node
  24552. };
  24553. pp$3.parsePrivateIdent = function() {
  24554. var node = this.startNode();
  24555. if (this.type === types.privateId) {
  24556. node.name = this.value;
  24557. } else {
  24558. this.unexpected();
  24559. }
  24560. this.next();
  24561. this.finishNode(node, "PrivateIdentifier");
  24562. // For validating existence
  24563. if (this.privateNameStack.length === 0) {
  24564. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  24565. } else {
  24566. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  24567. }
  24568. return node
  24569. };
  24570. // Parses yield expression inside generator.
  24571. pp$3.parseYield = function(forInit) {
  24572. if (!this.yieldPos) { this.yieldPos = this.start; }
  24573. var node = this.startNode();
  24574. this.next();
  24575. if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
  24576. node.delegate = false;
  24577. node.argument = null;
  24578. } else {
  24579. node.delegate = this.eat(types.star);
  24580. node.argument = this.parseMaybeAssign(forInit);
  24581. }
  24582. return this.finishNode(node, "YieldExpression")
  24583. };
  24584. pp$3.parseAwait = function() {
  24585. if (!this.awaitPos) { this.awaitPos = this.start; }
  24586. var node = this.startNode();
  24587. this.next();
  24588. node.argument = this.parseMaybeUnary(null, true);
  24589. return this.finishNode(node, "AwaitExpression")
  24590. };
  24591. var pp$4 = Parser.prototype;
  24592. // This function is used to raise exceptions on parse errors. It
  24593. // takes an offset integer (into the current `input`) to indicate
  24594. // the location of the error, attaches the position to the end
  24595. // of the error message, and then raises a `SyntaxError` with that
  24596. // message.
  24597. pp$4.raise = function(pos, message) {
  24598. var loc = getLineInfo(this.input, pos);
  24599. message += " (" + loc.line + ":" + loc.column + ")";
  24600. var err = new SyntaxError(message);
  24601. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  24602. throw err
  24603. };
  24604. pp$4.raiseRecoverable = pp$4.raise;
  24605. pp$4.curPosition = function() {
  24606. if (this.options.locations) {
  24607. return new Position(this.curLine, this.pos - this.lineStart)
  24608. }
  24609. };
  24610. var pp$5 = Parser.prototype;
  24611. var Scope = function Scope(flags) {
  24612. this.flags = flags;
  24613. // A list of var-declared names in the current lexical scope
  24614. this.var = [];
  24615. // A list of lexically-declared names in the current lexical scope
  24616. this.lexical = [];
  24617. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  24618. this.functions = [];
  24619. // A switch to disallow the identifier reference 'arguments'
  24620. this.inClassFieldInit = false;
  24621. };
  24622. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  24623. pp$5.enterScope = function(flags) {
  24624. this.scopeStack.push(new Scope(flags));
  24625. };
  24626. pp$5.exitScope = function() {
  24627. this.scopeStack.pop();
  24628. };
  24629. // The spec says:
  24630. // > At the top level of a function, or script, function declarations are
  24631. // > treated like var declarations rather than like lexical declarations.
  24632. pp$5.treatFunctionsAsVarInScope = function(scope) {
  24633. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  24634. };
  24635. pp$5.declareName = function(name, bindingType, pos) {
  24636. var redeclared = false;
  24637. if (bindingType === BIND_LEXICAL) {
  24638. var scope = this.currentScope();
  24639. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  24640. scope.lexical.push(name);
  24641. if (this.inModule && (scope.flags & SCOPE_TOP))
  24642. { delete this.undefinedExports[name]; }
  24643. } else if (bindingType === BIND_SIMPLE_CATCH) {
  24644. var scope$1 = this.currentScope();
  24645. scope$1.lexical.push(name);
  24646. } else if (bindingType === BIND_FUNCTION) {
  24647. var scope$2 = this.currentScope();
  24648. if (this.treatFunctionsAsVar)
  24649. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  24650. else
  24651. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  24652. scope$2.functions.push(name);
  24653. } else {
  24654. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  24655. var scope$3 = this.scopeStack[i];
  24656. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  24657. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  24658. redeclared = true;
  24659. break
  24660. }
  24661. scope$3.var.push(name);
  24662. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  24663. { delete this.undefinedExports[name]; }
  24664. if (scope$3.flags & SCOPE_VAR) { break }
  24665. }
  24666. }
  24667. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  24668. };
  24669. pp$5.checkLocalExport = function(id) {
  24670. // scope.functions must be empty as Module code is always strict.
  24671. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  24672. this.scopeStack[0].var.indexOf(id.name) === -1) {
  24673. this.undefinedExports[id.name] = id;
  24674. }
  24675. };
  24676. pp$5.currentScope = function() {
  24677. return this.scopeStack[this.scopeStack.length - 1]
  24678. };
  24679. pp$5.currentVarScope = function() {
  24680. for (var i = this.scopeStack.length - 1;; i--) {
  24681. var scope = this.scopeStack[i];
  24682. if (scope.flags & SCOPE_VAR) { return scope }
  24683. }
  24684. };
  24685. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  24686. pp$5.currentThisScope = function() {
  24687. for (var i = this.scopeStack.length - 1;; i--) {
  24688. var scope = this.scopeStack[i];
  24689. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  24690. }
  24691. };
  24692. var Node = function Node(parser, pos, loc) {
  24693. this.type = "";
  24694. this.start = pos;
  24695. this.end = 0;
  24696. if (parser.options.locations)
  24697. { this.loc = new SourceLocation(parser, loc); }
  24698. if (parser.options.directSourceFile)
  24699. { this.sourceFile = parser.options.directSourceFile; }
  24700. if (parser.options.ranges)
  24701. { this.range = [pos, 0]; }
  24702. };
  24703. // Start an AST node, attaching a start offset.
  24704. var pp$6 = Parser.prototype;
  24705. pp$6.startNode = function() {
  24706. return new Node(this, this.start, this.startLoc)
  24707. };
  24708. pp$6.startNodeAt = function(pos, loc) {
  24709. return new Node(this, pos, loc)
  24710. };
  24711. // Finish an AST node, adding `type` and `end` properties.
  24712. function finishNodeAt(node, type, pos, loc) {
  24713. node.type = type;
  24714. node.end = pos;
  24715. if (this.options.locations)
  24716. { node.loc.end = loc; }
  24717. if (this.options.ranges)
  24718. { node.range[1] = pos; }
  24719. return node
  24720. }
  24721. pp$6.finishNode = function(node, type) {
  24722. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  24723. };
  24724. // Finish node at given position
  24725. pp$6.finishNodeAt = function(node, type, pos, loc) {
  24726. return finishNodeAt.call(this, node, type, pos, loc)
  24727. };
  24728. pp$6.copyNode = function(node) {
  24729. var newNode = new Node(this, node.start, this.startLoc);
  24730. for (var prop in node) { newNode[prop] = node[prop]; }
  24731. return newNode
  24732. };
  24733. // The algorithm used to determine whether a regexp can appear at a
  24734. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  24735. this.token = token;
  24736. this.isExpr = !!isExpr;
  24737. this.preserveSpace = !!preserveSpace;
  24738. this.override = override;
  24739. this.generator = !!generator;
  24740. };
  24741. var types$1 = {
  24742. b_stat: new TokContext("{", false),
  24743. b_expr: new TokContext("{", true),
  24744. b_tmpl: new TokContext("${", false),
  24745. p_stat: new TokContext("(", false),
  24746. p_expr: new TokContext("(", true),
  24747. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  24748. f_stat: new TokContext("function", false),
  24749. f_expr: new TokContext("function", true),
  24750. f_expr_gen: new TokContext("function", true, false, null, true),
  24751. f_gen: new TokContext("function", false, false, null, true)
  24752. };
  24753. var pp$7 = Parser.prototype;
  24754. pp$7.initialContext = function() {
  24755. return [types$1.b_stat]
  24756. };
  24757. pp$7.braceIsBlock = function(prevType) {
  24758. var parent = this.curContext();
  24759. if (parent === types$1.f_expr || parent === types$1.f_stat)
  24760. { return true }
  24761. if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
  24762. { return !parent.isExpr }
  24763. // The check for `tt.name && exprAllowed` detects whether we are
  24764. // after a `yield` or `of` construct. See the `updateContext` for
  24765. // `tt.name`.
  24766. if (prevType === types._return || prevType === types.name && this.exprAllowed)
  24767. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  24768. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
  24769. { return true }
  24770. if (prevType === types.braceL)
  24771. { return parent === types$1.b_stat }
  24772. if (prevType === types._var || prevType === types._const || prevType === types.name)
  24773. { return false }
  24774. return !this.exprAllowed
  24775. };
  24776. pp$7.inGeneratorContext = function() {
  24777. for (var i = this.context.length - 1; i >= 1; i--) {
  24778. var context = this.context[i];
  24779. if (context.token === "function")
  24780. { return context.generator }
  24781. }
  24782. return false
  24783. };
  24784. pp$7.updateContext = function(prevType) {
  24785. var update, type = this.type;
  24786. if (type.keyword && prevType === types.dot)
  24787. { this.exprAllowed = false; }
  24788. else if (update = type.updateContext)
  24789. { update.call(this, prevType); }
  24790. else
  24791. { this.exprAllowed = type.beforeExpr; }
  24792. };
  24793. // Token-specific context update code
  24794. types.parenR.updateContext = types.braceR.updateContext = function() {
  24795. if (this.context.length === 1) {
  24796. this.exprAllowed = true;
  24797. return
  24798. }
  24799. var out = this.context.pop();
  24800. if (out === types$1.b_stat && this.curContext().token === "function") {
  24801. out = this.context.pop();
  24802. }
  24803. this.exprAllowed = !out.isExpr;
  24804. };
  24805. types.braceL.updateContext = function(prevType) {
  24806. this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  24807. this.exprAllowed = true;
  24808. };
  24809. types.dollarBraceL.updateContext = function() {
  24810. this.context.push(types$1.b_tmpl);
  24811. this.exprAllowed = true;
  24812. };
  24813. types.parenL.updateContext = function(prevType) {
  24814. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  24815. this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  24816. this.exprAllowed = true;
  24817. };
  24818. types.incDec.updateContext = function() {
  24819. // tokExprAllowed stays unchanged
  24820. };
  24821. types._function.updateContext = types._class.updateContext = function(prevType) {
  24822. if (prevType.beforeExpr && prevType !== types._else &&
  24823. !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
  24824. !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  24825. !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
  24826. { this.context.push(types$1.f_expr); }
  24827. else
  24828. { this.context.push(types$1.f_stat); }
  24829. this.exprAllowed = false;
  24830. };
  24831. types.backQuote.updateContext = function() {
  24832. if (this.curContext() === types$1.q_tmpl)
  24833. { this.context.pop(); }
  24834. else
  24835. { this.context.push(types$1.q_tmpl); }
  24836. this.exprAllowed = false;
  24837. };
  24838. types.star.updateContext = function(prevType) {
  24839. if (prevType === types._function) {
  24840. var index = this.context.length - 1;
  24841. if (this.context[index] === types$1.f_expr)
  24842. { this.context[index] = types$1.f_expr_gen; }
  24843. else
  24844. { this.context[index] = types$1.f_gen; }
  24845. }
  24846. this.exprAllowed = true;
  24847. };
  24848. types.name.updateContext = function(prevType) {
  24849. var allowed = false;
  24850. if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
  24851. if (this.value === "of" && !this.exprAllowed ||
  24852. this.value === "yield" && this.inGeneratorContext())
  24853. { allowed = true; }
  24854. }
  24855. this.exprAllowed = allowed;
  24856. };
  24857. // This file contains Unicode properties extracted from the ECMAScript
  24858. // specification. The lists are extracted like so:
  24859. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  24860. // #table-binary-unicode-properties
  24861. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  24862. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  24863. var ecma11BinaryProperties = ecma10BinaryProperties;
  24864. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  24865. var unicodeBinaryProperties = {
  24866. 9: ecma9BinaryProperties,
  24867. 10: ecma10BinaryProperties,
  24868. 11: ecma11BinaryProperties,
  24869. 12: ecma12BinaryProperties
  24870. };
  24871. // #table-unicode-general-category-values
  24872. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  24873. // #table-unicode-script-values
  24874. var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  24875. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  24876. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  24877. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  24878. var unicodeScriptValues = {
  24879. 9: ecma9ScriptValues,
  24880. 10: ecma10ScriptValues,
  24881. 11: ecma11ScriptValues,
  24882. 12: ecma12ScriptValues
  24883. };
  24884. var data = {};
  24885. function buildUnicodeData(ecmaVersion) {
  24886. var d = data[ecmaVersion] = {
  24887. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  24888. nonBinary: {
  24889. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  24890. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  24891. }
  24892. };
  24893. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  24894. d.nonBinary.gc = d.nonBinary.General_Category;
  24895. d.nonBinary.sc = d.nonBinary.Script;
  24896. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  24897. }
  24898. buildUnicodeData(9);
  24899. buildUnicodeData(10);
  24900. buildUnicodeData(11);
  24901. buildUnicodeData(12);
  24902. var pp$8 = Parser.prototype;
  24903. var RegExpValidationState = function RegExpValidationState(parser) {
  24904. this.parser = parser;
  24905. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  24906. this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
  24907. this.source = "";
  24908. this.flags = "";
  24909. this.start = 0;
  24910. this.switchU = false;
  24911. this.switchN = false;
  24912. this.pos = 0;
  24913. this.lastIntValue = 0;
  24914. this.lastStringValue = "";
  24915. this.lastAssertionIsQuantifiable = false;
  24916. this.numCapturingParens = 0;
  24917. this.maxBackReference = 0;
  24918. this.groupNames = [];
  24919. this.backReferenceNames = [];
  24920. };
  24921. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  24922. var unicode = flags.indexOf("u") !== -1;
  24923. this.start = start | 0;
  24924. this.source = pattern + "";
  24925. this.flags = flags;
  24926. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  24927. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  24928. };
  24929. RegExpValidationState.prototype.raise = function raise (message) {
  24930. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  24931. };
  24932. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  24933. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  24934. RegExpValidationState.prototype.at = function at (i, forceU) {
  24935. if ( forceU === void 0 ) forceU = false;
  24936. var s = this.source;
  24937. var l = s.length;
  24938. if (i >= l) {
  24939. return -1
  24940. }
  24941. var c = s.charCodeAt(i);
  24942. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  24943. return c
  24944. }
  24945. var next = s.charCodeAt(i + 1);
  24946. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  24947. };
  24948. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  24949. if ( forceU === void 0 ) forceU = false;
  24950. var s = this.source;
  24951. var l = s.length;
  24952. if (i >= l) {
  24953. return l
  24954. }
  24955. var c = s.charCodeAt(i), next;
  24956. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  24957. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  24958. return i + 1
  24959. }
  24960. return i + 2
  24961. };
  24962. RegExpValidationState.prototype.current = function current (forceU) {
  24963. if ( forceU === void 0 ) forceU = false;
  24964. return this.at(this.pos, forceU)
  24965. };
  24966. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  24967. if ( forceU === void 0 ) forceU = false;
  24968. return this.at(this.nextIndex(this.pos, forceU), forceU)
  24969. };
  24970. RegExpValidationState.prototype.advance = function advance (forceU) {
  24971. if ( forceU === void 0 ) forceU = false;
  24972. this.pos = this.nextIndex(this.pos, forceU);
  24973. };
  24974. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  24975. if ( forceU === void 0 ) forceU = false;
  24976. if (this.current(forceU) === ch) {
  24977. this.advance(forceU);
  24978. return true
  24979. }
  24980. return false
  24981. };
  24982. function codePointToString(ch) {
  24983. if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
  24984. ch -= 0x10000;
  24985. return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
  24986. }
  24987. /**
  24988. * Validate the flags part of a given RegExpLiteral.
  24989. *
  24990. * @param {RegExpValidationState} state The state to validate RegExp.
  24991. * @returns {void}
  24992. */
  24993. pp$8.validateRegExpFlags = function(state) {
  24994. var validFlags = state.validFlags;
  24995. var flags = state.flags;
  24996. for (var i = 0; i < flags.length; i++) {
  24997. var flag = flags.charAt(i);
  24998. if (validFlags.indexOf(flag) === -1) {
  24999. this.raise(state.start, "Invalid regular expression flag");
  25000. }
  25001. if (flags.indexOf(flag, i + 1) > -1) {
  25002. this.raise(state.start, "Duplicate regular expression flag");
  25003. }
  25004. }
  25005. };
  25006. /**
  25007. * Validate the pattern part of a given RegExpLiteral.
  25008. *
  25009. * @param {RegExpValidationState} state The state to validate RegExp.
  25010. * @returns {void}
  25011. */
  25012. pp$8.validateRegExpPattern = function(state) {
  25013. this.regexp_pattern(state);
  25014. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  25015. // parsing contains a |GroupName|, reparse with the goal symbol
  25016. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  25017. // exception if _P_ did not conform to the grammar, if any elements of _P_
  25018. // were not matched by the parse, or if any Early Error conditions exist.
  25019. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  25020. state.switchN = true;
  25021. this.regexp_pattern(state);
  25022. }
  25023. };
  25024. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  25025. pp$8.regexp_pattern = function(state) {
  25026. state.pos = 0;
  25027. state.lastIntValue = 0;
  25028. state.lastStringValue = "";
  25029. state.lastAssertionIsQuantifiable = false;
  25030. state.numCapturingParens = 0;
  25031. state.maxBackReference = 0;
  25032. state.groupNames.length = 0;
  25033. state.backReferenceNames.length = 0;
  25034. this.regexp_disjunction(state);
  25035. if (state.pos !== state.source.length) {
  25036. // Make the same messages as V8.
  25037. if (state.eat(0x29 /* ) */)) {
  25038. state.raise("Unmatched ')'");
  25039. }
  25040. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  25041. state.raise("Lone quantifier brackets");
  25042. }
  25043. }
  25044. if (state.maxBackReference > state.numCapturingParens) {
  25045. state.raise("Invalid escape");
  25046. }
  25047. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  25048. var name = list[i];
  25049. if (state.groupNames.indexOf(name) === -1) {
  25050. state.raise("Invalid named capture referenced");
  25051. }
  25052. }
  25053. };
  25054. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  25055. pp$8.regexp_disjunction = function(state) {
  25056. this.regexp_alternative(state);
  25057. while (state.eat(0x7C /* | */)) {
  25058. this.regexp_alternative(state);
  25059. }
  25060. // Make the same message as V8.
  25061. if (this.regexp_eatQuantifier(state, true)) {
  25062. state.raise("Nothing to repeat");
  25063. }
  25064. if (state.eat(0x7B /* { */)) {
  25065. state.raise("Lone quantifier brackets");
  25066. }
  25067. };
  25068. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  25069. pp$8.regexp_alternative = function(state) {
  25070. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  25071. { }
  25072. };
  25073. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  25074. pp$8.regexp_eatTerm = function(state) {
  25075. if (this.regexp_eatAssertion(state)) {
  25076. // Handle `QuantifiableAssertion Quantifier` alternative.
  25077. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  25078. // is a QuantifiableAssertion.
  25079. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  25080. // Make the same message as V8.
  25081. if (state.switchU) {
  25082. state.raise("Invalid quantifier");
  25083. }
  25084. }
  25085. return true
  25086. }
  25087. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  25088. this.regexp_eatQuantifier(state);
  25089. return true
  25090. }
  25091. return false
  25092. };
  25093. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  25094. pp$8.regexp_eatAssertion = function(state) {
  25095. var start = state.pos;
  25096. state.lastAssertionIsQuantifiable = false;
  25097. // ^, $
  25098. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  25099. return true
  25100. }
  25101. // \b \B
  25102. if (state.eat(0x5C /* \ */)) {
  25103. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  25104. return true
  25105. }
  25106. state.pos = start;
  25107. }
  25108. // Lookahead / Lookbehind
  25109. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  25110. var lookbehind = false;
  25111. if (this.options.ecmaVersion >= 9) {
  25112. lookbehind = state.eat(0x3C /* < */);
  25113. }
  25114. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  25115. this.regexp_disjunction(state);
  25116. if (!state.eat(0x29 /* ) */)) {
  25117. state.raise("Unterminated group");
  25118. }
  25119. state.lastAssertionIsQuantifiable = !lookbehind;
  25120. return true
  25121. }
  25122. }
  25123. state.pos = start;
  25124. return false
  25125. };
  25126. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  25127. pp$8.regexp_eatQuantifier = function(state, noError) {
  25128. if ( noError === void 0 ) noError = false;
  25129. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  25130. state.eat(0x3F /* ? */);
  25131. return true
  25132. }
  25133. return false
  25134. };
  25135. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  25136. pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
  25137. return (
  25138. state.eat(0x2A /* * */) ||
  25139. state.eat(0x2B /* + */) ||
  25140. state.eat(0x3F /* ? */) ||
  25141. this.regexp_eatBracedQuantifier(state, noError)
  25142. )
  25143. };
  25144. pp$8.regexp_eatBracedQuantifier = function(state, noError) {
  25145. var start = state.pos;
  25146. if (state.eat(0x7B /* { */)) {
  25147. var min = 0, max = -1;
  25148. if (this.regexp_eatDecimalDigits(state)) {
  25149. min = state.lastIntValue;
  25150. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  25151. max = state.lastIntValue;
  25152. }
  25153. if (state.eat(0x7D /* } */)) {
  25154. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  25155. if (max !== -1 && max < min && !noError) {
  25156. state.raise("numbers out of order in {} quantifier");
  25157. }
  25158. return true
  25159. }
  25160. }
  25161. if (state.switchU && !noError) {
  25162. state.raise("Incomplete quantifier");
  25163. }
  25164. state.pos = start;
  25165. }
  25166. return false
  25167. };
  25168. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  25169. pp$8.regexp_eatAtom = function(state) {
  25170. return (
  25171. this.regexp_eatPatternCharacters(state) ||
  25172. state.eat(0x2E /* . */) ||
  25173. this.regexp_eatReverseSolidusAtomEscape(state) ||
  25174. this.regexp_eatCharacterClass(state) ||
  25175. this.regexp_eatUncapturingGroup(state) ||
  25176. this.regexp_eatCapturingGroup(state)
  25177. )
  25178. };
  25179. pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
  25180. var start = state.pos;
  25181. if (state.eat(0x5C /* \ */)) {
  25182. if (this.regexp_eatAtomEscape(state)) {
  25183. return true
  25184. }
  25185. state.pos = start;
  25186. }
  25187. return false
  25188. };
  25189. pp$8.regexp_eatUncapturingGroup = function(state) {
  25190. var start = state.pos;
  25191. if (state.eat(0x28 /* ( */)) {
  25192. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  25193. this.regexp_disjunction(state);
  25194. if (state.eat(0x29 /* ) */)) {
  25195. return true
  25196. }
  25197. state.raise("Unterminated group");
  25198. }
  25199. state.pos = start;
  25200. }
  25201. return false
  25202. };
  25203. pp$8.regexp_eatCapturingGroup = function(state) {
  25204. if (state.eat(0x28 /* ( */)) {
  25205. if (this.options.ecmaVersion >= 9) {
  25206. this.regexp_groupSpecifier(state);
  25207. } else if (state.current() === 0x3F /* ? */) {
  25208. state.raise("Invalid group");
  25209. }
  25210. this.regexp_disjunction(state);
  25211. if (state.eat(0x29 /* ) */)) {
  25212. state.numCapturingParens += 1;
  25213. return true
  25214. }
  25215. state.raise("Unterminated group");
  25216. }
  25217. return false
  25218. };
  25219. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  25220. pp$8.regexp_eatExtendedAtom = function(state) {
  25221. return (
  25222. state.eat(0x2E /* . */) ||
  25223. this.regexp_eatReverseSolidusAtomEscape(state) ||
  25224. this.regexp_eatCharacterClass(state) ||
  25225. this.regexp_eatUncapturingGroup(state) ||
  25226. this.regexp_eatCapturingGroup(state) ||
  25227. this.regexp_eatInvalidBracedQuantifier(state) ||
  25228. this.regexp_eatExtendedPatternCharacter(state)
  25229. )
  25230. };
  25231. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  25232. pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
  25233. if (this.regexp_eatBracedQuantifier(state, true)) {
  25234. state.raise("Nothing to repeat");
  25235. }
  25236. return false
  25237. };
  25238. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  25239. pp$8.regexp_eatSyntaxCharacter = function(state) {
  25240. var ch = state.current();
  25241. if (isSyntaxCharacter(ch)) {
  25242. state.lastIntValue = ch;
  25243. state.advance();
  25244. return true
  25245. }
  25246. return false
  25247. };
  25248. function isSyntaxCharacter(ch) {
  25249. return (
  25250. ch === 0x24 /* $ */ ||
  25251. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  25252. ch === 0x2E /* . */ ||
  25253. ch === 0x3F /* ? */ ||
  25254. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  25255. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  25256. )
  25257. }
  25258. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  25259. // But eat eager.
  25260. pp$8.regexp_eatPatternCharacters = function(state) {
  25261. var start = state.pos;
  25262. var ch = 0;
  25263. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  25264. state.advance();
  25265. }
  25266. return state.pos !== start
  25267. };
  25268. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  25269. pp$8.regexp_eatExtendedPatternCharacter = function(state) {
  25270. var ch = state.current();
  25271. if (
  25272. ch !== -1 &&
  25273. ch !== 0x24 /* $ */ &&
  25274. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  25275. ch !== 0x2E /* . */ &&
  25276. ch !== 0x3F /* ? */ &&
  25277. ch !== 0x5B /* [ */ &&
  25278. ch !== 0x5E /* ^ */ &&
  25279. ch !== 0x7C /* | */
  25280. ) {
  25281. state.advance();
  25282. return true
  25283. }
  25284. return false
  25285. };
  25286. // GroupSpecifier ::
  25287. // [empty]
  25288. // `?` GroupName
  25289. pp$8.regexp_groupSpecifier = function(state) {
  25290. if (state.eat(0x3F /* ? */)) {
  25291. if (this.regexp_eatGroupName(state)) {
  25292. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  25293. state.raise("Duplicate capture group name");
  25294. }
  25295. state.groupNames.push(state.lastStringValue);
  25296. return
  25297. }
  25298. state.raise("Invalid group");
  25299. }
  25300. };
  25301. // GroupName ::
  25302. // `<` RegExpIdentifierName `>`
  25303. // Note: this updates `state.lastStringValue` property with the eaten name.
  25304. pp$8.regexp_eatGroupName = function(state) {
  25305. state.lastStringValue = "";
  25306. if (state.eat(0x3C /* < */)) {
  25307. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  25308. return true
  25309. }
  25310. state.raise("Invalid capture group name");
  25311. }
  25312. return false
  25313. };
  25314. // RegExpIdentifierName ::
  25315. // RegExpIdentifierStart
  25316. // RegExpIdentifierName RegExpIdentifierPart
  25317. // Note: this updates `state.lastStringValue` property with the eaten name.
  25318. pp$8.regexp_eatRegExpIdentifierName = function(state) {
  25319. state.lastStringValue = "";
  25320. if (this.regexp_eatRegExpIdentifierStart(state)) {
  25321. state.lastStringValue += codePointToString(state.lastIntValue);
  25322. while (this.regexp_eatRegExpIdentifierPart(state)) {
  25323. state.lastStringValue += codePointToString(state.lastIntValue);
  25324. }
  25325. return true
  25326. }
  25327. return false
  25328. };
  25329. // RegExpIdentifierStart ::
  25330. // UnicodeIDStart
  25331. // `$`
  25332. // `_`
  25333. // `\` RegExpUnicodeEscapeSequence[+U]
  25334. pp$8.regexp_eatRegExpIdentifierStart = function(state) {
  25335. var start = state.pos;
  25336. var forceU = this.options.ecmaVersion >= 11;
  25337. var ch = state.current(forceU);
  25338. state.advance(forceU);
  25339. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  25340. ch = state.lastIntValue;
  25341. }
  25342. if (isRegExpIdentifierStart(ch)) {
  25343. state.lastIntValue = ch;
  25344. return true
  25345. }
  25346. state.pos = start;
  25347. return false
  25348. };
  25349. function isRegExpIdentifierStart(ch) {
  25350. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  25351. }
  25352. // RegExpIdentifierPart ::
  25353. // UnicodeIDContinue
  25354. // `$`
  25355. // `_`
  25356. // `\` RegExpUnicodeEscapeSequence[+U]
  25357. // <ZWNJ>
  25358. // <ZWJ>
  25359. pp$8.regexp_eatRegExpIdentifierPart = function(state) {
  25360. var start = state.pos;
  25361. var forceU = this.options.ecmaVersion >= 11;
  25362. var ch = state.current(forceU);
  25363. state.advance(forceU);
  25364. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  25365. ch = state.lastIntValue;
  25366. }
  25367. if (isRegExpIdentifierPart(ch)) {
  25368. state.lastIntValue = ch;
  25369. return true
  25370. }
  25371. state.pos = start;
  25372. return false
  25373. };
  25374. function isRegExpIdentifierPart(ch) {
  25375. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  25376. }
  25377. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  25378. pp$8.regexp_eatAtomEscape = function(state) {
  25379. if (
  25380. this.regexp_eatBackReference(state) ||
  25381. this.regexp_eatCharacterClassEscape(state) ||
  25382. this.regexp_eatCharacterEscape(state) ||
  25383. (state.switchN && this.regexp_eatKGroupName(state))
  25384. ) {
  25385. return true
  25386. }
  25387. if (state.switchU) {
  25388. // Make the same message as V8.
  25389. if (state.current() === 0x63 /* c */) {
  25390. state.raise("Invalid unicode escape");
  25391. }
  25392. state.raise("Invalid escape");
  25393. }
  25394. return false
  25395. };
  25396. pp$8.regexp_eatBackReference = function(state) {
  25397. var start = state.pos;
  25398. if (this.regexp_eatDecimalEscape(state)) {
  25399. var n = state.lastIntValue;
  25400. if (state.switchU) {
  25401. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  25402. if (n > state.maxBackReference) {
  25403. state.maxBackReference = n;
  25404. }
  25405. return true
  25406. }
  25407. if (n <= state.numCapturingParens) {
  25408. return true
  25409. }
  25410. state.pos = start;
  25411. }
  25412. return false
  25413. };
  25414. pp$8.regexp_eatKGroupName = function(state) {
  25415. if (state.eat(0x6B /* k */)) {
  25416. if (this.regexp_eatGroupName(state)) {
  25417. state.backReferenceNames.push(state.lastStringValue);
  25418. return true
  25419. }
  25420. state.raise("Invalid named reference");
  25421. }
  25422. return false
  25423. };
  25424. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  25425. pp$8.regexp_eatCharacterEscape = function(state) {
  25426. return (
  25427. this.regexp_eatControlEscape(state) ||
  25428. this.regexp_eatCControlLetter(state) ||
  25429. this.regexp_eatZero(state) ||
  25430. this.regexp_eatHexEscapeSequence(state) ||
  25431. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  25432. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  25433. this.regexp_eatIdentityEscape(state)
  25434. )
  25435. };
  25436. pp$8.regexp_eatCControlLetter = function(state) {
  25437. var start = state.pos;
  25438. if (state.eat(0x63 /* c */)) {
  25439. if (this.regexp_eatControlLetter(state)) {
  25440. return true
  25441. }
  25442. state.pos = start;
  25443. }
  25444. return false
  25445. };
  25446. pp$8.regexp_eatZero = function(state) {
  25447. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  25448. state.lastIntValue = 0;
  25449. state.advance();
  25450. return true
  25451. }
  25452. return false
  25453. };
  25454. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  25455. pp$8.regexp_eatControlEscape = function(state) {
  25456. var ch = state.current();
  25457. if (ch === 0x74 /* t */) {
  25458. state.lastIntValue = 0x09; /* \t */
  25459. state.advance();
  25460. return true
  25461. }
  25462. if (ch === 0x6E /* n */) {
  25463. state.lastIntValue = 0x0A; /* \n */
  25464. state.advance();
  25465. return true
  25466. }
  25467. if (ch === 0x76 /* v */) {
  25468. state.lastIntValue = 0x0B; /* \v */
  25469. state.advance();
  25470. return true
  25471. }
  25472. if (ch === 0x66 /* f */) {
  25473. state.lastIntValue = 0x0C; /* \f */
  25474. state.advance();
  25475. return true
  25476. }
  25477. if (ch === 0x72 /* r */) {
  25478. state.lastIntValue = 0x0D; /* \r */
  25479. state.advance();
  25480. return true
  25481. }
  25482. return false
  25483. };
  25484. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  25485. pp$8.regexp_eatControlLetter = function(state) {
  25486. var ch = state.current();
  25487. if (isControlLetter(ch)) {
  25488. state.lastIntValue = ch % 0x20;
  25489. state.advance();
  25490. return true
  25491. }
  25492. return false
  25493. };
  25494. function isControlLetter(ch) {
  25495. return (
  25496. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  25497. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  25498. )
  25499. }
  25500. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  25501. pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  25502. if ( forceU === void 0 ) forceU = false;
  25503. var start = state.pos;
  25504. var switchU = forceU || state.switchU;
  25505. if (state.eat(0x75 /* u */)) {
  25506. if (this.regexp_eatFixedHexDigits(state, 4)) {
  25507. var lead = state.lastIntValue;
  25508. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  25509. var leadSurrogateEnd = state.pos;
  25510. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  25511. var trail = state.lastIntValue;
  25512. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  25513. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  25514. return true
  25515. }
  25516. }
  25517. state.pos = leadSurrogateEnd;
  25518. state.lastIntValue = lead;
  25519. }
  25520. return true
  25521. }
  25522. if (
  25523. switchU &&
  25524. state.eat(0x7B /* { */) &&
  25525. this.regexp_eatHexDigits(state) &&
  25526. state.eat(0x7D /* } */) &&
  25527. isValidUnicode(state.lastIntValue)
  25528. ) {
  25529. return true
  25530. }
  25531. if (switchU) {
  25532. state.raise("Invalid unicode escape");
  25533. }
  25534. state.pos = start;
  25535. }
  25536. return false
  25537. };
  25538. function isValidUnicode(ch) {
  25539. return ch >= 0 && ch <= 0x10FFFF
  25540. }
  25541. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  25542. pp$8.regexp_eatIdentityEscape = function(state) {
  25543. if (state.switchU) {
  25544. if (this.regexp_eatSyntaxCharacter(state)) {
  25545. return true
  25546. }
  25547. if (state.eat(0x2F /* / */)) {
  25548. state.lastIntValue = 0x2F; /* / */
  25549. return true
  25550. }
  25551. return false
  25552. }
  25553. var ch = state.current();
  25554. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  25555. state.lastIntValue = ch;
  25556. state.advance();
  25557. return true
  25558. }
  25559. return false
  25560. };
  25561. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  25562. pp$8.regexp_eatDecimalEscape = function(state) {
  25563. state.lastIntValue = 0;
  25564. var ch = state.current();
  25565. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  25566. do {
  25567. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  25568. state.advance();
  25569. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  25570. return true
  25571. }
  25572. return false
  25573. };
  25574. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  25575. pp$8.regexp_eatCharacterClassEscape = function(state) {
  25576. var ch = state.current();
  25577. if (isCharacterClassEscape(ch)) {
  25578. state.lastIntValue = -1;
  25579. state.advance();
  25580. return true
  25581. }
  25582. if (
  25583. state.switchU &&
  25584. this.options.ecmaVersion >= 9 &&
  25585. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  25586. ) {
  25587. state.lastIntValue = -1;
  25588. state.advance();
  25589. if (
  25590. state.eat(0x7B /* { */) &&
  25591. this.regexp_eatUnicodePropertyValueExpression(state) &&
  25592. state.eat(0x7D /* } */)
  25593. ) {
  25594. return true
  25595. }
  25596. state.raise("Invalid property name");
  25597. }
  25598. return false
  25599. };
  25600. function isCharacterClassEscape(ch) {
  25601. return (
  25602. ch === 0x64 /* d */ ||
  25603. ch === 0x44 /* D */ ||
  25604. ch === 0x73 /* s */ ||
  25605. ch === 0x53 /* S */ ||
  25606. ch === 0x77 /* w */ ||
  25607. ch === 0x57 /* W */
  25608. )
  25609. }
  25610. // UnicodePropertyValueExpression ::
  25611. // UnicodePropertyName `=` UnicodePropertyValue
  25612. // LoneUnicodePropertyNameOrValue
  25613. pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
  25614. var start = state.pos;
  25615. // UnicodePropertyName `=` UnicodePropertyValue
  25616. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  25617. var name = state.lastStringValue;
  25618. if (this.regexp_eatUnicodePropertyValue(state)) {
  25619. var value = state.lastStringValue;
  25620. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  25621. return true
  25622. }
  25623. }
  25624. state.pos = start;
  25625. // LoneUnicodePropertyNameOrValue
  25626. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  25627. var nameOrValue = state.lastStringValue;
  25628. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  25629. return true
  25630. }
  25631. return false
  25632. };
  25633. pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  25634. if (!has(state.unicodeProperties.nonBinary, name))
  25635. { state.raise("Invalid property name"); }
  25636. if (!state.unicodeProperties.nonBinary[name].test(value))
  25637. { state.raise("Invalid property value"); }
  25638. };
  25639. pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  25640. if (!state.unicodeProperties.binary.test(nameOrValue))
  25641. { state.raise("Invalid property name"); }
  25642. };
  25643. // UnicodePropertyName ::
  25644. // UnicodePropertyNameCharacters
  25645. pp$8.regexp_eatUnicodePropertyName = function(state) {
  25646. var ch = 0;
  25647. state.lastStringValue = "";
  25648. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  25649. state.lastStringValue += codePointToString(ch);
  25650. state.advance();
  25651. }
  25652. return state.lastStringValue !== ""
  25653. };
  25654. function isUnicodePropertyNameCharacter(ch) {
  25655. return isControlLetter(ch) || ch === 0x5F /* _ */
  25656. }
  25657. // UnicodePropertyValue ::
  25658. // UnicodePropertyValueCharacters
  25659. pp$8.regexp_eatUnicodePropertyValue = function(state) {
  25660. var ch = 0;
  25661. state.lastStringValue = "";
  25662. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  25663. state.lastStringValue += codePointToString(ch);
  25664. state.advance();
  25665. }
  25666. return state.lastStringValue !== ""
  25667. };
  25668. function isUnicodePropertyValueCharacter(ch) {
  25669. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  25670. }
  25671. // LoneUnicodePropertyNameOrValue ::
  25672. // UnicodePropertyValueCharacters
  25673. pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  25674. return this.regexp_eatUnicodePropertyValue(state)
  25675. };
  25676. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  25677. pp$8.regexp_eatCharacterClass = function(state) {
  25678. if (state.eat(0x5B /* [ */)) {
  25679. state.eat(0x5E /* ^ */);
  25680. this.regexp_classRanges(state);
  25681. if (state.eat(0x5D /* ] */)) {
  25682. return true
  25683. }
  25684. // Unreachable since it threw "unterminated regular expression" error before.
  25685. state.raise("Unterminated character class");
  25686. }
  25687. return false
  25688. };
  25689. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  25690. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  25691. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  25692. pp$8.regexp_classRanges = function(state) {
  25693. while (this.regexp_eatClassAtom(state)) {
  25694. var left = state.lastIntValue;
  25695. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  25696. var right = state.lastIntValue;
  25697. if (state.switchU && (left === -1 || right === -1)) {
  25698. state.raise("Invalid character class");
  25699. }
  25700. if (left !== -1 && right !== -1 && left > right) {
  25701. state.raise("Range out of order in character class");
  25702. }
  25703. }
  25704. }
  25705. };
  25706. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  25707. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  25708. pp$8.regexp_eatClassAtom = function(state) {
  25709. var start = state.pos;
  25710. if (state.eat(0x5C /* \ */)) {
  25711. if (this.regexp_eatClassEscape(state)) {
  25712. return true
  25713. }
  25714. if (state.switchU) {
  25715. // Make the same message as V8.
  25716. var ch$1 = state.current();
  25717. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  25718. state.raise("Invalid class escape");
  25719. }
  25720. state.raise("Invalid escape");
  25721. }
  25722. state.pos = start;
  25723. }
  25724. var ch = state.current();
  25725. if (ch !== 0x5D /* ] */) {
  25726. state.lastIntValue = ch;
  25727. state.advance();
  25728. return true
  25729. }
  25730. return false
  25731. };
  25732. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  25733. pp$8.regexp_eatClassEscape = function(state) {
  25734. var start = state.pos;
  25735. if (state.eat(0x62 /* b */)) {
  25736. state.lastIntValue = 0x08; /* <BS> */
  25737. return true
  25738. }
  25739. if (state.switchU && state.eat(0x2D /* - */)) {
  25740. state.lastIntValue = 0x2D; /* - */
  25741. return true
  25742. }
  25743. if (!state.switchU && state.eat(0x63 /* c */)) {
  25744. if (this.regexp_eatClassControlLetter(state)) {
  25745. return true
  25746. }
  25747. state.pos = start;
  25748. }
  25749. return (
  25750. this.regexp_eatCharacterClassEscape(state) ||
  25751. this.regexp_eatCharacterEscape(state)
  25752. )
  25753. };
  25754. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  25755. pp$8.regexp_eatClassControlLetter = function(state) {
  25756. var ch = state.current();
  25757. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  25758. state.lastIntValue = ch % 0x20;
  25759. state.advance();
  25760. return true
  25761. }
  25762. return false
  25763. };
  25764. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  25765. pp$8.regexp_eatHexEscapeSequence = function(state) {
  25766. var start = state.pos;
  25767. if (state.eat(0x78 /* x */)) {
  25768. if (this.regexp_eatFixedHexDigits(state, 2)) {
  25769. return true
  25770. }
  25771. if (state.switchU) {
  25772. state.raise("Invalid escape");
  25773. }
  25774. state.pos = start;
  25775. }
  25776. return false
  25777. };
  25778. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  25779. pp$8.regexp_eatDecimalDigits = function(state) {
  25780. var start = state.pos;
  25781. var ch = 0;
  25782. state.lastIntValue = 0;
  25783. while (isDecimalDigit(ch = state.current())) {
  25784. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  25785. state.advance();
  25786. }
  25787. return state.pos !== start
  25788. };
  25789. function isDecimalDigit(ch) {
  25790. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  25791. }
  25792. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  25793. pp$8.regexp_eatHexDigits = function(state) {
  25794. var start = state.pos;
  25795. var ch = 0;
  25796. state.lastIntValue = 0;
  25797. while (isHexDigit(ch = state.current())) {
  25798. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  25799. state.advance();
  25800. }
  25801. return state.pos !== start
  25802. };
  25803. function isHexDigit(ch) {
  25804. return (
  25805. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  25806. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  25807. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  25808. )
  25809. }
  25810. function hexToInt(ch) {
  25811. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  25812. return 10 + (ch - 0x41 /* A */)
  25813. }
  25814. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  25815. return 10 + (ch - 0x61 /* a */)
  25816. }
  25817. return ch - 0x30 /* 0 */
  25818. }
  25819. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  25820. // Allows only 0-377(octal) i.e. 0-255(decimal).
  25821. pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
  25822. if (this.regexp_eatOctalDigit(state)) {
  25823. var n1 = state.lastIntValue;
  25824. if (this.regexp_eatOctalDigit(state)) {
  25825. var n2 = state.lastIntValue;
  25826. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  25827. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  25828. } else {
  25829. state.lastIntValue = n1 * 8 + n2;
  25830. }
  25831. } else {
  25832. state.lastIntValue = n1;
  25833. }
  25834. return true
  25835. }
  25836. return false
  25837. };
  25838. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  25839. pp$8.regexp_eatOctalDigit = function(state) {
  25840. var ch = state.current();
  25841. if (isOctalDigit(ch)) {
  25842. state.lastIntValue = ch - 0x30; /* 0 */
  25843. state.advance();
  25844. return true
  25845. }
  25846. state.lastIntValue = 0;
  25847. return false
  25848. };
  25849. function isOctalDigit(ch) {
  25850. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  25851. }
  25852. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  25853. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  25854. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  25855. pp$8.regexp_eatFixedHexDigits = function(state, length) {
  25856. var start = state.pos;
  25857. state.lastIntValue = 0;
  25858. for (var i = 0; i < length; ++i) {
  25859. var ch = state.current();
  25860. if (!isHexDigit(ch)) {
  25861. state.pos = start;
  25862. return false
  25863. }
  25864. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  25865. state.advance();
  25866. }
  25867. return true
  25868. };
  25869. // Object type used to represent tokens. Note that normally, tokens
  25870. // simply exist as properties on the parser object. This is only
  25871. // used for the onToken callback and the external tokenizer.
  25872. var Token = function Token(p) {
  25873. this.type = p.type;
  25874. this.value = p.value;
  25875. this.start = p.start;
  25876. this.end = p.end;
  25877. if (p.options.locations)
  25878. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  25879. if (p.options.ranges)
  25880. { this.range = [p.start, p.end]; }
  25881. };
  25882. // ## Tokenizer
  25883. var pp$9 = Parser.prototype;
  25884. // Move to the next token
  25885. pp$9.next = function(ignoreEscapeSequenceInKeyword) {
  25886. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  25887. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  25888. if (this.options.onToken)
  25889. { this.options.onToken(new Token(this)); }
  25890. this.lastTokEnd = this.end;
  25891. this.lastTokStart = this.start;
  25892. this.lastTokEndLoc = this.endLoc;
  25893. this.lastTokStartLoc = this.startLoc;
  25894. this.nextToken();
  25895. };
  25896. pp$9.getToken = function() {
  25897. this.next();
  25898. return new Token(this)
  25899. };
  25900. // If we're in an ES6 environment, make parsers iterable
  25901. if (typeof Symbol !== "undefined")
  25902. { pp$9[Symbol.iterator] = function() {
  25903. var this$1$1 = this;
  25904. return {
  25905. next: function () {
  25906. var token = this$1$1.getToken();
  25907. return {
  25908. done: token.type === types.eof,
  25909. value: token
  25910. }
  25911. }
  25912. }
  25913. }; }
  25914. // Toggle strict mode. Re-reads the next number or string to please
  25915. // pedantic tests (`"use strict"; 010;` should fail).
  25916. pp$9.curContext = function() {
  25917. return this.context[this.context.length - 1]
  25918. };
  25919. // Read a single token, updating the parser object's token-related
  25920. // properties.
  25921. pp$9.nextToken = function() {
  25922. var curContext = this.curContext();
  25923. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  25924. this.start = this.pos;
  25925. if (this.options.locations) { this.startLoc = this.curPosition(); }
  25926. if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
  25927. if (curContext.override) { return curContext.override(this) }
  25928. else { this.readToken(this.fullCharCodeAtPos()); }
  25929. };
  25930. pp$9.readToken = function(code) {
  25931. // Identifier or keyword. '\uXXXX' sequences are allowed in
  25932. // identifiers, so '\' also dispatches to that.
  25933. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  25934. { return this.readWord() }
  25935. return this.getTokenFromCode(code)
  25936. };
  25937. pp$9.fullCharCodeAtPos = function() {
  25938. var code = this.input.charCodeAt(this.pos);
  25939. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  25940. var next = this.input.charCodeAt(this.pos + 1);
  25941. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  25942. };
  25943. pp$9.skipBlockComment = function() {
  25944. var startLoc = this.options.onComment && this.curPosition();
  25945. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  25946. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  25947. this.pos = end + 2;
  25948. if (this.options.locations) {
  25949. lineBreakG.lastIndex = start;
  25950. var match;
  25951. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  25952. ++this.curLine;
  25953. this.lineStart = match.index + match[0].length;
  25954. }
  25955. }
  25956. if (this.options.onComment)
  25957. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  25958. startLoc, this.curPosition()); }
  25959. };
  25960. pp$9.skipLineComment = function(startSkip) {
  25961. var start = this.pos;
  25962. var startLoc = this.options.onComment && this.curPosition();
  25963. var ch = this.input.charCodeAt(this.pos += startSkip);
  25964. while (this.pos < this.input.length && !isNewLine(ch)) {
  25965. ch = this.input.charCodeAt(++this.pos);
  25966. }
  25967. if (this.options.onComment)
  25968. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  25969. startLoc, this.curPosition()); }
  25970. };
  25971. // Called at the start of the parse and after every token. Skips
  25972. // whitespace and comments, and.
  25973. pp$9.skipSpace = function() {
  25974. loop: while (this.pos < this.input.length) {
  25975. var ch = this.input.charCodeAt(this.pos);
  25976. switch (ch) {
  25977. case 32: case 160: // ' '
  25978. ++this.pos;
  25979. break
  25980. case 13:
  25981. if (this.input.charCodeAt(this.pos + 1) === 10) {
  25982. ++this.pos;
  25983. }
  25984. case 10: case 8232: case 8233:
  25985. ++this.pos;
  25986. if (this.options.locations) {
  25987. ++this.curLine;
  25988. this.lineStart = this.pos;
  25989. }
  25990. break
  25991. case 47: // '/'
  25992. switch (this.input.charCodeAt(this.pos + 1)) {
  25993. case 42: // '*'
  25994. this.skipBlockComment();
  25995. break
  25996. case 47:
  25997. this.skipLineComment(2);
  25998. break
  25999. default:
  26000. break loop
  26001. }
  26002. break
  26003. default:
  26004. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  26005. ++this.pos;
  26006. } else {
  26007. break loop
  26008. }
  26009. }
  26010. }
  26011. };
  26012. // Called at the end of every token. Sets `end`, `val`, and
  26013. // maintains `context` and `exprAllowed`, and skips the space after
  26014. // the token, so that the next one's `start` will point at the
  26015. // right position.
  26016. pp$9.finishToken = function(type, val) {
  26017. this.end = this.pos;
  26018. if (this.options.locations) { this.endLoc = this.curPosition(); }
  26019. var prevType = this.type;
  26020. this.type = type;
  26021. this.value = val;
  26022. this.updateContext(prevType);
  26023. };
  26024. // ### Token reading
  26025. // This is the function that is called to fetch the next token. It
  26026. // is somewhat obscure, because it works in character codes rather
  26027. // than characters, and because operator parsing has been inlined
  26028. // into it.
  26029. //
  26030. // All in the name of speed.
  26031. //
  26032. pp$9.readToken_dot = function() {
  26033. var next = this.input.charCodeAt(this.pos + 1);
  26034. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  26035. var next2 = this.input.charCodeAt(this.pos + 2);
  26036. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  26037. this.pos += 3;
  26038. return this.finishToken(types.ellipsis)
  26039. } else {
  26040. ++this.pos;
  26041. return this.finishToken(types.dot)
  26042. }
  26043. };
  26044. pp$9.readToken_slash = function() { // '/'
  26045. var next = this.input.charCodeAt(this.pos + 1);
  26046. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  26047. if (next === 61) { return this.finishOp(types.assign, 2) }
  26048. return this.finishOp(types.slash, 1)
  26049. };
  26050. pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
  26051. var next = this.input.charCodeAt(this.pos + 1);
  26052. var size = 1;
  26053. var tokentype = code === 42 ? types.star : types.modulo;
  26054. // exponentiation operator ** and **=
  26055. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  26056. ++size;
  26057. tokentype = types.starstar;
  26058. next = this.input.charCodeAt(this.pos + 2);
  26059. }
  26060. if (next === 61) { return this.finishOp(types.assign, size + 1) }
  26061. return this.finishOp(tokentype, size)
  26062. };
  26063. pp$9.readToken_pipe_amp = function(code) { // '|&'
  26064. var next = this.input.charCodeAt(this.pos + 1);
  26065. if (next === code) {
  26066. if (this.options.ecmaVersion >= 12) {
  26067. var next2 = this.input.charCodeAt(this.pos + 2);
  26068. if (next2 === 61) { return this.finishOp(types.assign, 3) }
  26069. }
  26070. return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
  26071. }
  26072. if (next === 61) { return this.finishOp(types.assign, 2) }
  26073. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
  26074. };
  26075. pp$9.readToken_caret = function() { // '^'
  26076. var next = this.input.charCodeAt(this.pos + 1);
  26077. if (next === 61) { return this.finishOp(types.assign, 2) }
  26078. return this.finishOp(types.bitwiseXOR, 1)
  26079. };
  26080. pp$9.readToken_plus_min = function(code) { // '+-'
  26081. var next = this.input.charCodeAt(this.pos + 1);
  26082. if (next === code) {
  26083. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  26084. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  26085. // A `-->` line comment
  26086. this.skipLineComment(3);
  26087. this.skipSpace();
  26088. return this.nextToken()
  26089. }
  26090. return this.finishOp(types.incDec, 2)
  26091. }
  26092. if (next === 61) { return this.finishOp(types.assign, 2) }
  26093. return this.finishOp(types.plusMin, 1)
  26094. };
  26095. pp$9.readToken_lt_gt = function(code) { // '<>'
  26096. var next = this.input.charCodeAt(this.pos + 1);
  26097. var size = 1;
  26098. if (next === code) {
  26099. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  26100. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
  26101. return this.finishOp(types.bitShift, size)
  26102. }
  26103. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  26104. this.input.charCodeAt(this.pos + 3) === 45) {
  26105. // `<!--`, an XML-style comment that should be interpreted as a line comment
  26106. this.skipLineComment(4);
  26107. this.skipSpace();
  26108. return this.nextToken()
  26109. }
  26110. if (next === 61) { size = 2; }
  26111. return this.finishOp(types.relational, size)
  26112. };
  26113. pp$9.readToken_eq_excl = function(code) { // '=!'
  26114. var next = this.input.charCodeAt(this.pos + 1);
  26115. if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  26116. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  26117. this.pos += 2;
  26118. return this.finishToken(types.arrow)
  26119. }
  26120. return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
  26121. };
  26122. pp$9.readToken_question = function() { // '?'
  26123. var ecmaVersion = this.options.ecmaVersion;
  26124. if (ecmaVersion >= 11) {
  26125. var next = this.input.charCodeAt(this.pos + 1);
  26126. if (next === 46) {
  26127. var next2 = this.input.charCodeAt(this.pos + 2);
  26128. if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
  26129. }
  26130. if (next === 63) {
  26131. if (ecmaVersion >= 12) {
  26132. var next2$1 = this.input.charCodeAt(this.pos + 2);
  26133. if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
  26134. }
  26135. return this.finishOp(types.coalesce, 2)
  26136. }
  26137. }
  26138. return this.finishOp(types.question, 1)
  26139. };
  26140. pp$9.readToken_numberSign = function() { // '#'
  26141. var ecmaVersion = this.options.ecmaVersion;
  26142. var code = 35; // '#'
  26143. if (ecmaVersion >= 13) {
  26144. ++this.pos;
  26145. code = this.fullCharCodeAtPos();
  26146. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  26147. return this.finishToken(types.privateId, this.readWord1())
  26148. }
  26149. }
  26150. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  26151. };
  26152. pp$9.getTokenFromCode = function(code) {
  26153. switch (code) {
  26154. // The interpretation of a dot depends on whether it is followed
  26155. // by a digit or another two dots.
  26156. case 46: // '.'
  26157. return this.readToken_dot()
  26158. // Punctuation tokens.
  26159. case 40: ++this.pos; return this.finishToken(types.parenL)
  26160. case 41: ++this.pos; return this.finishToken(types.parenR)
  26161. case 59: ++this.pos; return this.finishToken(types.semi)
  26162. case 44: ++this.pos; return this.finishToken(types.comma)
  26163. case 91: ++this.pos; return this.finishToken(types.bracketL)
  26164. case 93: ++this.pos; return this.finishToken(types.bracketR)
  26165. case 123: ++this.pos; return this.finishToken(types.braceL)
  26166. case 125: ++this.pos; return this.finishToken(types.braceR)
  26167. case 58: ++this.pos; return this.finishToken(types.colon)
  26168. case 96: // '`'
  26169. if (this.options.ecmaVersion < 6) { break }
  26170. ++this.pos;
  26171. return this.finishToken(types.backQuote)
  26172. case 48: // '0'
  26173. var next = this.input.charCodeAt(this.pos + 1);
  26174. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  26175. if (this.options.ecmaVersion >= 6) {
  26176. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  26177. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  26178. }
  26179. // Anything else beginning with a digit is an integer, octal
  26180. // number, or float.
  26181. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  26182. return this.readNumber(false)
  26183. // Quotes produce strings.
  26184. case 34: case 39: // '"', "'"
  26185. return this.readString(code)
  26186. // Operators are parsed inline in tiny state machines. '=' (61) is
  26187. // often referred to. `finishOp` simply skips the amount of
  26188. // characters it is given as second argument, and returns a token
  26189. // of the type given by its first argument.
  26190. case 47: // '/'
  26191. return this.readToken_slash()
  26192. case 37: case 42: // '%*'
  26193. return this.readToken_mult_modulo_exp(code)
  26194. case 124: case 38: // '|&'
  26195. return this.readToken_pipe_amp(code)
  26196. case 94: // '^'
  26197. return this.readToken_caret()
  26198. case 43: case 45: // '+-'
  26199. return this.readToken_plus_min(code)
  26200. case 60: case 62: // '<>'
  26201. return this.readToken_lt_gt(code)
  26202. case 61: case 33: // '=!'
  26203. return this.readToken_eq_excl(code)
  26204. case 63: // '?'
  26205. return this.readToken_question()
  26206. case 126: // '~'
  26207. return this.finishOp(types.prefix, 1)
  26208. case 35: // '#'
  26209. return this.readToken_numberSign()
  26210. }
  26211. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  26212. };
  26213. pp$9.finishOp = function(type, size) {
  26214. var str = this.input.slice(this.pos, this.pos + size);
  26215. this.pos += size;
  26216. return this.finishToken(type, str)
  26217. };
  26218. pp$9.readRegexp = function() {
  26219. var escaped, inClass, start = this.pos;
  26220. for (;;) {
  26221. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  26222. var ch = this.input.charAt(this.pos);
  26223. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  26224. if (!escaped) {
  26225. if (ch === "[") { inClass = true; }
  26226. else if (ch === "]" && inClass) { inClass = false; }
  26227. else if (ch === "/" && !inClass) { break }
  26228. escaped = ch === "\\";
  26229. } else { escaped = false; }
  26230. ++this.pos;
  26231. }
  26232. var pattern = this.input.slice(start, this.pos);
  26233. ++this.pos;
  26234. var flagsStart = this.pos;
  26235. var flags = this.readWord1();
  26236. if (this.containsEsc) { this.unexpected(flagsStart); }
  26237. // Validate pattern
  26238. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  26239. state.reset(start, pattern, flags);
  26240. this.validateRegExpFlags(state);
  26241. this.validateRegExpPattern(state);
  26242. // Create Literal#value property value.
  26243. var value = null;
  26244. try {
  26245. value = new RegExp(pattern, flags);
  26246. } catch (e) {
  26247. // ESTree requires null if it failed to instantiate RegExp object.
  26248. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  26249. }
  26250. return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
  26251. };
  26252. // Read an integer in the given radix. Return null if zero digits
  26253. // were read, the integer value otherwise. When `len` is given, this
  26254. // will return `null` unless the integer has exactly `len` digits.
  26255. pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  26256. // `len` is used for character escape sequences. In that case, disallow separators.
  26257. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  26258. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  26259. // and isn't fraction part nor exponent part. In that case, if the first digit
  26260. // is zero then disallow separators.
  26261. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  26262. var start = this.pos, total = 0, lastCode = 0;
  26263. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  26264. var code = this.input.charCodeAt(this.pos), val = (void 0);
  26265. if (allowSeparators && code === 95) {
  26266. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  26267. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  26268. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  26269. lastCode = code;
  26270. continue
  26271. }
  26272. if (code >= 97) { val = code - 97 + 10; } // a
  26273. else if (code >= 65) { val = code - 65 + 10; } // A
  26274. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  26275. else { val = Infinity; }
  26276. if (val >= radix) { break }
  26277. lastCode = code;
  26278. total = total * radix + val;
  26279. }
  26280. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  26281. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  26282. return total
  26283. };
  26284. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  26285. if (isLegacyOctalNumericLiteral) {
  26286. return parseInt(str, 8)
  26287. }
  26288. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  26289. return parseFloat(str.replace(/_/g, ""))
  26290. }
  26291. function stringToBigInt(str) {
  26292. if (typeof BigInt !== "function") {
  26293. return null
  26294. }
  26295. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  26296. return BigInt(str.replace(/_/g, ""))
  26297. }
  26298. pp$9.readRadixNumber = function(radix) {
  26299. var start = this.pos;
  26300. this.pos += 2; // 0x
  26301. var val = this.readInt(radix);
  26302. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  26303. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  26304. val = stringToBigInt(this.input.slice(start, this.pos));
  26305. ++this.pos;
  26306. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  26307. return this.finishToken(types.num, val)
  26308. };
  26309. // Read an integer, octal integer, or floating-point number.
  26310. pp$9.readNumber = function(startsWithDot) {
  26311. var start = this.pos;
  26312. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  26313. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  26314. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  26315. var next = this.input.charCodeAt(this.pos);
  26316. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  26317. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  26318. ++this.pos;
  26319. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  26320. return this.finishToken(types.num, val$1)
  26321. }
  26322. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  26323. if (next === 46 && !octal) { // '.'
  26324. ++this.pos;
  26325. this.readInt(10);
  26326. next = this.input.charCodeAt(this.pos);
  26327. }
  26328. if ((next === 69 || next === 101) && !octal) { // 'eE'
  26329. next = this.input.charCodeAt(++this.pos);
  26330. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  26331. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  26332. }
  26333. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  26334. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  26335. return this.finishToken(types.num, val)
  26336. };
  26337. // Read a string value, interpreting backslash-escapes.
  26338. pp$9.readCodePoint = function() {
  26339. var ch = this.input.charCodeAt(this.pos), code;
  26340. if (ch === 123) { // '{'
  26341. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  26342. var codePos = ++this.pos;
  26343. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  26344. ++this.pos;
  26345. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  26346. } else {
  26347. code = this.readHexChar(4);
  26348. }
  26349. return code
  26350. };
  26351. function codePointToString$1(code) {
  26352. // UTF-16 Decoding
  26353. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  26354. code -= 0x10000;
  26355. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  26356. }
  26357. pp$9.readString = function(quote) {
  26358. var out = "", chunkStart = ++this.pos;
  26359. for (;;) {
  26360. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  26361. var ch = this.input.charCodeAt(this.pos);
  26362. if (ch === quote) { break }
  26363. if (ch === 92) { // '\'
  26364. out += this.input.slice(chunkStart, this.pos);
  26365. out += this.readEscapedChar(false);
  26366. chunkStart = this.pos;
  26367. } else {
  26368. if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
  26369. ++this.pos;
  26370. }
  26371. }
  26372. out += this.input.slice(chunkStart, this.pos++);
  26373. return this.finishToken(types.string, out)
  26374. };
  26375. // Reads template string tokens.
  26376. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  26377. pp$9.tryReadTemplateToken = function() {
  26378. this.inTemplateElement = true;
  26379. try {
  26380. this.readTmplToken();
  26381. } catch (err) {
  26382. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  26383. this.readInvalidTemplateToken();
  26384. } else {
  26385. throw err
  26386. }
  26387. }
  26388. this.inTemplateElement = false;
  26389. };
  26390. pp$9.invalidStringToken = function(position, message) {
  26391. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  26392. throw INVALID_TEMPLATE_ESCAPE_ERROR
  26393. } else {
  26394. this.raise(position, message);
  26395. }
  26396. };
  26397. pp$9.readTmplToken = function() {
  26398. var out = "", chunkStart = this.pos;
  26399. for (;;) {
  26400. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  26401. var ch = this.input.charCodeAt(this.pos);
  26402. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  26403. if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
  26404. if (ch === 36) {
  26405. this.pos += 2;
  26406. return this.finishToken(types.dollarBraceL)
  26407. } else {
  26408. ++this.pos;
  26409. return this.finishToken(types.backQuote)
  26410. }
  26411. }
  26412. out += this.input.slice(chunkStart, this.pos);
  26413. return this.finishToken(types.template, out)
  26414. }
  26415. if (ch === 92) { // '\'
  26416. out += this.input.slice(chunkStart, this.pos);
  26417. out += this.readEscapedChar(true);
  26418. chunkStart = this.pos;
  26419. } else if (isNewLine(ch)) {
  26420. out += this.input.slice(chunkStart, this.pos);
  26421. ++this.pos;
  26422. switch (ch) {
  26423. case 13:
  26424. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  26425. case 10:
  26426. out += "\n";
  26427. break
  26428. default:
  26429. out += String.fromCharCode(ch);
  26430. break
  26431. }
  26432. if (this.options.locations) {
  26433. ++this.curLine;
  26434. this.lineStart = this.pos;
  26435. }
  26436. chunkStart = this.pos;
  26437. } else {
  26438. ++this.pos;
  26439. }
  26440. }
  26441. };
  26442. // Reads a template token to search for the end, without validating any escape sequences
  26443. pp$9.readInvalidTemplateToken = function() {
  26444. for (; this.pos < this.input.length; this.pos++) {
  26445. switch (this.input[this.pos]) {
  26446. case "\\":
  26447. ++this.pos;
  26448. break
  26449. case "$":
  26450. if (this.input[this.pos + 1] !== "{") {
  26451. break
  26452. }
  26453. // falls through
  26454. case "`":
  26455. return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
  26456. // no default
  26457. }
  26458. }
  26459. this.raise(this.start, "Unterminated template");
  26460. };
  26461. // Used to read escaped characters
  26462. pp$9.readEscapedChar = function(inTemplate) {
  26463. var ch = this.input.charCodeAt(++this.pos);
  26464. ++this.pos;
  26465. switch (ch) {
  26466. case 110: return "\n" // 'n' -> '\n'
  26467. case 114: return "\r" // 'r' -> '\r'
  26468. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  26469. case 117: return codePointToString$1(this.readCodePoint()) // 'u'
  26470. case 116: return "\t" // 't' -> '\t'
  26471. case 98: return "\b" // 'b' -> '\b'
  26472. case 118: return "\u000b" // 'v' -> '\u000b'
  26473. case 102: return "\f" // 'f' -> '\f'
  26474. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  26475. case 10: // ' \n'
  26476. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  26477. return ""
  26478. case 56:
  26479. case 57:
  26480. if (this.strict) {
  26481. this.invalidStringToken(
  26482. this.pos - 1,
  26483. "Invalid escape sequence"
  26484. );
  26485. }
  26486. if (inTemplate) {
  26487. var codePos = this.pos - 1;
  26488. this.invalidStringToken(
  26489. codePos,
  26490. "Invalid escape sequence in template string"
  26491. );
  26492. return null
  26493. }
  26494. default:
  26495. if (ch >= 48 && ch <= 55) {
  26496. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  26497. var octal = parseInt(octalStr, 8);
  26498. if (octal > 255) {
  26499. octalStr = octalStr.slice(0, -1);
  26500. octal = parseInt(octalStr, 8);
  26501. }
  26502. this.pos += octalStr.length - 1;
  26503. ch = this.input.charCodeAt(this.pos);
  26504. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  26505. this.invalidStringToken(
  26506. this.pos - 1 - octalStr.length,
  26507. inTemplate
  26508. ? "Octal literal in template string"
  26509. : "Octal literal in strict mode"
  26510. );
  26511. }
  26512. return String.fromCharCode(octal)
  26513. }
  26514. if (isNewLine(ch)) {
  26515. // Unicode new line characters after \ get removed from output in both
  26516. // template literals and strings
  26517. return ""
  26518. }
  26519. return String.fromCharCode(ch)
  26520. }
  26521. };
  26522. // Used to read character escape sequences ('\x', '\u', '\U').
  26523. pp$9.readHexChar = function(len) {
  26524. var codePos = this.pos;
  26525. var n = this.readInt(16, len);
  26526. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  26527. return n
  26528. };
  26529. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  26530. // to whether the word contained a '\u' escape.
  26531. //
  26532. // Incrementally adds only escaped chars, adding other chunks as-is
  26533. // as a micro-optimization.
  26534. pp$9.readWord1 = function() {
  26535. this.containsEsc = false;
  26536. var word = "", first = true, chunkStart = this.pos;
  26537. var astral = this.options.ecmaVersion >= 6;
  26538. while (this.pos < this.input.length) {
  26539. var ch = this.fullCharCodeAtPos();
  26540. if (isIdentifierChar(ch, astral)) {
  26541. this.pos += ch <= 0xffff ? 1 : 2;
  26542. } else if (ch === 92) { // "\"
  26543. this.containsEsc = true;
  26544. word += this.input.slice(chunkStart, this.pos);
  26545. var escStart = this.pos;
  26546. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  26547. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  26548. ++this.pos;
  26549. var esc = this.readCodePoint();
  26550. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  26551. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  26552. word += codePointToString$1(esc);
  26553. chunkStart = this.pos;
  26554. } else {
  26555. break
  26556. }
  26557. first = false;
  26558. }
  26559. return word + this.input.slice(chunkStart, this.pos)
  26560. };
  26561. // Read an identifier or keyword token. Will check for reserved
  26562. // words when necessary.
  26563. pp$9.readWord = function() {
  26564. var word = this.readWord1();
  26565. var type = types.name;
  26566. if (this.keywords.test(word)) {
  26567. type = keywords$1[word];
  26568. }
  26569. return this.finishToken(type, word)
  26570. };
  26571. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  26572. var version = "8.4.1";
  26573. Parser.acorn = {
  26574. Parser: Parser,
  26575. version: version,
  26576. defaultOptions: defaultOptions,
  26577. Position: Position,
  26578. SourceLocation: SourceLocation,
  26579. getLineInfo: getLineInfo,
  26580. Node: Node,
  26581. TokenType: TokenType,
  26582. tokTypes: types,
  26583. keywordTypes: keywords$1,
  26584. TokContext: TokContext,
  26585. tokContexts: types$1,
  26586. isIdentifierChar: isIdentifierChar,
  26587. isIdentifierStart: isIdentifierStart,
  26588. Token: Token,
  26589. isNewLine: isNewLine,
  26590. lineBreak: lineBreak,
  26591. lineBreakG: lineBreakG,
  26592. nonASCIIwhitespace: nonASCIIwhitespace
  26593. };
  26594. // The main exported interface (under `self.acorn` when in the
  26595. // browser) is a `parse` function that takes a code string and
  26596. // returns an abstract syntax tree as specified by [Mozilla parser
  26597. // API][api].
  26598. //
  26599. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  26600. function parse(input, options) {
  26601. return Parser.parse(input, options)
  26602. }
  26603. // This function tries to parse a single expression at a given
  26604. // offset in a string. Useful for parsing mixed-language formats
  26605. // that embed JavaScript expressions.
  26606. function parseExpressionAt(input, pos, options) {
  26607. return Parser.parseExpressionAt(input, pos, options)
  26608. }
  26609. // Acorn is organized as a tokenizer and a recursive-descent parser.
  26610. // The `tokenizer` export provides an interface to the tokenizer.
  26611. function tokenizer(input, options) {
  26612. return Parser.tokenizer(input, options)
  26613. }
  26614. exports.Node = Node;
  26615. exports.Parser = Parser;
  26616. exports.Position = Position;
  26617. exports.SourceLocation = SourceLocation;
  26618. exports.TokContext = TokContext;
  26619. exports.Token = Token;
  26620. exports.TokenType = TokenType;
  26621. exports.defaultOptions = defaultOptions;
  26622. exports.getLineInfo = getLineInfo;
  26623. exports.isIdentifierChar = isIdentifierChar;
  26624. exports.isIdentifierStart = isIdentifierStart;
  26625. exports.isNewLine = isNewLine;
  26626. exports.keywordTypes = keywords$1;
  26627. exports.lineBreak = lineBreak;
  26628. exports.lineBreakG = lineBreakG;
  26629. exports.nonASCIIwhitespace = nonASCIIwhitespace;
  26630. exports.parse = parse;
  26631. exports.parseExpressionAt = parseExpressionAt;
  26632. exports.tokContexts = types$1;
  26633. exports.tokTypes = types;
  26634. exports.tokenizer = tokenizer;
  26635. exports.version = version;
  26636. Object.defineProperty(exports, '__esModule', { value: true });
  26637. })));
  26638. }(acorn$1, acorn$1.exports));
  26639. var walk$4 = {exports: {}};
  26640. (function (module, exports) {
  26641. (function (global, factory) {
  26642. factory(exports) ;
  26643. }(commonjsGlobal, (function (exports) {
  26644. // AST walker module for Mozilla Parser API compatible trees
  26645. // A simple walk is one where you simply specify callbacks to be
  26646. // called on specific nodes. The last two arguments are optional. A
  26647. // simple use would be
  26648. //
  26649. // walk.simple(myTree, {
  26650. // Expression: function(node) { ... }
  26651. // });
  26652. //
  26653. // to do something with all expressions. All Parser API node types
  26654. // can be used to identify node types, as well as Expression and
  26655. // Statement, which denote categories of nodes.
  26656. //
  26657. // The base argument can be used to pass a custom (recursive)
  26658. // walker, and state can be used to give this walked an initial
  26659. // state.
  26660. function simple(node, visitors, baseVisitor, state, override) {
  26661. if (!baseVisitor) { baseVisitor = base
  26662. ; }(function c(node, st, override) {
  26663. var type = override || node.type, found = visitors[type];
  26664. baseVisitor[type](node, st, c);
  26665. if (found) { found(node, st); }
  26666. })(node, state, override);
  26667. }
  26668. // An ancestor walk keeps an array of ancestor nodes (including the
  26669. // current node) and passes them to the callback as third parameter
  26670. // (and also as state parameter when no other state is present).
  26671. function ancestor(node, visitors, baseVisitor, state, override) {
  26672. var ancestors = [];
  26673. if (!baseVisitor) { baseVisitor = base
  26674. ; }(function c(node, st, override) {
  26675. var type = override || node.type, found = visitors[type];
  26676. var isNew = node !== ancestors[ancestors.length - 1];
  26677. if (isNew) { ancestors.push(node); }
  26678. baseVisitor[type](node, st, c);
  26679. if (found) { found(node, st || ancestors, ancestors); }
  26680. if (isNew) { ancestors.pop(); }
  26681. })(node, state, override);
  26682. }
  26683. // A recursive walk is one where your functions override the default
  26684. // walkers. They can modify and replace the state parameter that's
  26685. // threaded through the walk, and can opt how and whether to walk
  26686. // their child nodes (by calling their third argument on these
  26687. // nodes).
  26688. function recursive(node, state, funcs, baseVisitor, override) {
  26689. var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor
  26690. ;(function c(node, st, override) {
  26691. visitor[override || node.type](node, st, c);
  26692. })(node, state, override);
  26693. }
  26694. function makeTest(test) {
  26695. if (typeof test === "string")
  26696. { return function (type) { return type === test; } }
  26697. else if (!test)
  26698. { return function () { return true; } }
  26699. else
  26700. { return test }
  26701. }
  26702. var Found = function Found(node, state) { this.node = node; this.state = state; };
  26703. // A full walk triggers the callback on each node
  26704. function full(node, callback, baseVisitor, state, override) {
  26705. if (!baseVisitor) { baseVisitor = base; }
  26706. var last
  26707. ;(function c(node, st, override) {
  26708. var type = override || node.type;
  26709. baseVisitor[type](node, st, c);
  26710. if (last !== node) {
  26711. callback(node, st, type);
  26712. last = node;
  26713. }
  26714. })(node, state, override);
  26715. }
  26716. // An fullAncestor walk is like an ancestor walk, but triggers
  26717. // the callback on each node
  26718. function fullAncestor(node, callback, baseVisitor, state) {
  26719. if (!baseVisitor) { baseVisitor = base; }
  26720. var ancestors = [], last
  26721. ;(function c(node, st, override) {
  26722. var type = override || node.type;
  26723. var isNew = node !== ancestors[ancestors.length - 1];
  26724. if (isNew) { ancestors.push(node); }
  26725. baseVisitor[type](node, st, c);
  26726. if (last !== node) {
  26727. callback(node, st || ancestors, ancestors, type);
  26728. last = node;
  26729. }
  26730. if (isNew) { ancestors.pop(); }
  26731. })(node, state);
  26732. }
  26733. // Find a node with a given start, end, and type (all are optional,
  26734. // null can be used as wildcard). Returns a {node, state} object, or
  26735. // undefined when it doesn't find a matching node.
  26736. function findNodeAt(node, start, end, test, baseVisitor, state) {
  26737. if (!baseVisitor) { baseVisitor = base; }
  26738. test = makeTest(test);
  26739. try {
  26740. (function c(node, st, override) {
  26741. var type = override || node.type;
  26742. if ((start == null || node.start <= start) &&
  26743. (end == null || node.end >= end))
  26744. { baseVisitor[type](node, st, c); }
  26745. if ((start == null || node.start === start) &&
  26746. (end == null || node.end === end) &&
  26747. test(type, node))
  26748. { throw new Found(node, st) }
  26749. })(node, state);
  26750. } catch (e) {
  26751. if (e instanceof Found) { return e }
  26752. throw e
  26753. }
  26754. }
  26755. // Find the innermost node of a given type that contains the given
  26756. // position. Interface similar to findNodeAt.
  26757. function findNodeAround(node, pos, test, baseVisitor, state) {
  26758. test = makeTest(test);
  26759. if (!baseVisitor) { baseVisitor = base; }
  26760. try {
  26761. (function c(node, st, override) {
  26762. var type = override || node.type;
  26763. if (node.start > pos || node.end < pos) { return }
  26764. baseVisitor[type](node, st, c);
  26765. if (test(type, node)) { throw new Found(node, st) }
  26766. })(node, state);
  26767. } catch (e) {
  26768. if (e instanceof Found) { return e }
  26769. throw e
  26770. }
  26771. }
  26772. // Find the outermost matching node after a given position.
  26773. function findNodeAfter(node, pos, test, baseVisitor, state) {
  26774. test = makeTest(test);
  26775. if (!baseVisitor) { baseVisitor = base; }
  26776. try {
  26777. (function c(node, st, override) {
  26778. if (node.end < pos) { return }
  26779. var type = override || node.type;
  26780. if (node.start >= pos && test(type, node)) { throw new Found(node, st) }
  26781. baseVisitor[type](node, st, c);
  26782. })(node, state);
  26783. } catch (e) {
  26784. if (e instanceof Found) { return e }
  26785. throw e
  26786. }
  26787. }
  26788. // Find the outermost matching node before a given position.
  26789. function findNodeBefore(node, pos, test, baseVisitor, state) {
  26790. test = makeTest(test);
  26791. if (!baseVisitor) { baseVisitor = base; }
  26792. var max
  26793. ;(function c(node, st, override) {
  26794. if (node.start > pos) { return }
  26795. var type = override || node.type;
  26796. if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
  26797. { max = new Found(node, st); }
  26798. baseVisitor[type](node, st, c);
  26799. })(node, state);
  26800. return max
  26801. }
  26802. // Used to create a custom walker. Will fill in all missing node
  26803. // type properties with the defaults.
  26804. function make(funcs, baseVisitor) {
  26805. var visitor = Object.create(baseVisitor || base);
  26806. for (var type in funcs) { visitor[type] = funcs[type]; }
  26807. return visitor
  26808. }
  26809. function skipThrough(node, st, c) { c(node, st); }
  26810. function ignore(_node, _st, _c) {}
  26811. // Node walkers.
  26812. var base = {};
  26813. base.Program = base.BlockStatement = function (node, st, c) {
  26814. for (var i = 0, list = node.body; i < list.length; i += 1)
  26815. {
  26816. var stmt = list[i];
  26817. c(stmt, st, "Statement");
  26818. }
  26819. };
  26820. base.Statement = skipThrough;
  26821. base.EmptyStatement = ignore;
  26822. base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
  26823. function (node, st, c) { return c(node.expression, st, "Expression"); };
  26824. base.IfStatement = function (node, st, c) {
  26825. c(node.test, st, "Expression");
  26826. c(node.consequent, st, "Statement");
  26827. if (node.alternate) { c(node.alternate, st, "Statement"); }
  26828. };
  26829. base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  26830. base.BreakStatement = base.ContinueStatement = ignore;
  26831. base.WithStatement = function (node, st, c) {
  26832. c(node.object, st, "Expression");
  26833. c(node.body, st, "Statement");
  26834. };
  26835. base.SwitchStatement = function (node, st, c) {
  26836. c(node.discriminant, st, "Expression");
  26837. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  26838. var cs = list$1[i$1];
  26839. if (cs.test) { c(cs.test, st, "Expression"); }
  26840. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  26841. {
  26842. var cons = list[i];
  26843. c(cons, st, "Statement");
  26844. }
  26845. }
  26846. };
  26847. base.SwitchCase = function (node, st, c) {
  26848. if (node.test) { c(node.test, st, "Expression"); }
  26849. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  26850. {
  26851. var cons = list[i];
  26852. c(cons, st, "Statement");
  26853. }
  26854. };
  26855. base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
  26856. if (node.argument) { c(node.argument, st, "Expression"); }
  26857. };
  26858. base.ThrowStatement = base.SpreadElement =
  26859. function (node, st, c) { return c(node.argument, st, "Expression"); };
  26860. base.TryStatement = function (node, st, c) {
  26861. c(node.block, st, "Statement");
  26862. if (node.handler) { c(node.handler, st); }
  26863. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  26864. };
  26865. base.CatchClause = function (node, st, c) {
  26866. if (node.param) { c(node.param, st, "Pattern"); }
  26867. c(node.body, st, "Statement");
  26868. };
  26869. base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
  26870. c(node.test, st, "Expression");
  26871. c(node.body, st, "Statement");
  26872. };
  26873. base.ForStatement = function (node, st, c) {
  26874. if (node.init) { c(node.init, st, "ForInit"); }
  26875. if (node.test) { c(node.test, st, "Expression"); }
  26876. if (node.update) { c(node.update, st, "Expression"); }
  26877. c(node.body, st, "Statement");
  26878. };
  26879. base.ForInStatement = base.ForOfStatement = function (node, st, c) {
  26880. c(node.left, st, "ForInit");
  26881. c(node.right, st, "Expression");
  26882. c(node.body, st, "Statement");
  26883. };
  26884. base.ForInit = function (node, st, c) {
  26885. if (node.type === "VariableDeclaration") { c(node, st); }
  26886. else { c(node, st, "Expression"); }
  26887. };
  26888. base.DebuggerStatement = ignore;
  26889. base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  26890. base.VariableDeclaration = function (node, st, c) {
  26891. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  26892. {
  26893. var decl = list[i];
  26894. c(decl, st);
  26895. }
  26896. };
  26897. base.VariableDeclarator = function (node, st, c) {
  26898. c(node.id, st, "Pattern");
  26899. if (node.init) { c(node.init, st, "Expression"); }
  26900. };
  26901. base.Function = function (node, st, c) {
  26902. if (node.id) { c(node.id, st, "Pattern"); }
  26903. for (var i = 0, list = node.params; i < list.length; i += 1)
  26904. {
  26905. var param = list[i];
  26906. c(param, st, "Pattern");
  26907. }
  26908. c(node.body, st, node.expression ? "Expression" : "Statement");
  26909. };
  26910. base.Pattern = function (node, st, c) {
  26911. if (node.type === "Identifier")
  26912. { c(node, st, "VariablePattern"); }
  26913. else if (node.type === "MemberExpression")
  26914. { c(node, st, "MemberPattern"); }
  26915. else
  26916. { c(node, st); }
  26917. };
  26918. base.VariablePattern = ignore;
  26919. base.MemberPattern = skipThrough;
  26920. base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  26921. base.ArrayPattern = function (node, st, c) {
  26922. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  26923. var elt = list[i];
  26924. if (elt) { c(elt, st, "Pattern"); }
  26925. }
  26926. };
  26927. base.ObjectPattern = function (node, st, c) {
  26928. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  26929. var prop = list[i];
  26930. if (prop.type === "Property") {
  26931. if (prop.computed) { c(prop.key, st, "Expression"); }
  26932. c(prop.value, st, "Pattern");
  26933. } else if (prop.type === "RestElement") {
  26934. c(prop.argument, st, "Pattern");
  26935. }
  26936. }
  26937. };
  26938. base.Expression = skipThrough;
  26939. base.ThisExpression = base.Super = base.MetaProperty = ignore;
  26940. base.ArrayExpression = function (node, st, c) {
  26941. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  26942. var elt = list[i];
  26943. if (elt) { c(elt, st, "Expression"); }
  26944. }
  26945. };
  26946. base.ObjectExpression = function (node, st, c) {
  26947. for (var i = 0, list = node.properties; i < list.length; i += 1)
  26948. {
  26949. var prop = list[i];
  26950. c(prop, st);
  26951. }
  26952. };
  26953. base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
  26954. base.SequenceExpression = function (node, st, c) {
  26955. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  26956. {
  26957. var expr = list[i];
  26958. c(expr, st, "Expression");
  26959. }
  26960. };
  26961. base.TemplateLiteral = function (node, st, c) {
  26962. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  26963. {
  26964. var quasi = list[i];
  26965. c(quasi, st);
  26966. }
  26967. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  26968. {
  26969. var expr = list$1[i$1];
  26970. c(expr, st, "Expression");
  26971. }
  26972. };
  26973. base.TemplateElement = ignore;
  26974. base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
  26975. c(node.argument, st, "Expression");
  26976. };
  26977. base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
  26978. c(node.left, st, "Expression");
  26979. c(node.right, st, "Expression");
  26980. };
  26981. base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
  26982. c(node.left, st, "Pattern");
  26983. c(node.right, st, "Expression");
  26984. };
  26985. base.ConditionalExpression = function (node, st, c) {
  26986. c(node.test, st, "Expression");
  26987. c(node.consequent, st, "Expression");
  26988. c(node.alternate, st, "Expression");
  26989. };
  26990. base.NewExpression = base.CallExpression = function (node, st, c) {
  26991. c(node.callee, st, "Expression");
  26992. if (node.arguments)
  26993. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  26994. {
  26995. var arg = list[i];
  26996. c(arg, st, "Expression");
  26997. } }
  26998. };
  26999. base.MemberExpression = function (node, st, c) {
  27000. c(node.object, st, "Expression");
  27001. if (node.computed) { c(node.property, st, "Expression"); }
  27002. };
  27003. base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
  27004. if (node.declaration)
  27005. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  27006. if (node.source) { c(node.source, st, "Expression"); }
  27007. };
  27008. base.ExportAllDeclaration = function (node, st, c) {
  27009. if (node.exported)
  27010. { c(node.exported, st); }
  27011. c(node.source, st, "Expression");
  27012. };
  27013. base.ImportDeclaration = function (node, st, c) {
  27014. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  27015. {
  27016. var spec = list[i];
  27017. c(spec, st);
  27018. }
  27019. c(node.source, st, "Expression");
  27020. };
  27021. base.ImportExpression = function (node, st, c) {
  27022. c(node.source, st, "Expression");
  27023. };
  27024. base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
  27025. base.TaggedTemplateExpression = function (node, st, c) {
  27026. c(node.tag, st, "Expression");
  27027. c(node.quasi, st, "Expression");
  27028. };
  27029. base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  27030. base.Class = function (node, st, c) {
  27031. if (node.id) { c(node.id, st, "Pattern"); }
  27032. if (node.superClass) { c(node.superClass, st, "Expression"); }
  27033. c(node.body, st);
  27034. };
  27035. base.ClassBody = function (node, st, c) {
  27036. for (var i = 0, list = node.body; i < list.length; i += 1)
  27037. {
  27038. var elt = list[i];
  27039. c(elt, st);
  27040. }
  27041. };
  27042. base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
  27043. if (node.computed) { c(node.key, st, "Expression"); }
  27044. if (node.value) { c(node.value, st, "Expression"); }
  27045. };
  27046. exports.ancestor = ancestor;
  27047. exports.base = base;
  27048. exports.findNodeAfter = findNodeAfter;
  27049. exports.findNodeAround = findNodeAround;
  27050. exports.findNodeAt = findNodeAt;
  27051. exports.findNodeBefore = findNodeBefore;
  27052. exports.full = full;
  27053. exports.fullAncestor = fullAncestor;
  27054. exports.make = make;
  27055. exports.recursive = recursive;
  27056. exports.simple = simple;
  27057. Object.defineProperty(exports, '__esModule', { value: true });
  27058. })));
  27059. }(walk$4, walk$4.exports));
  27060. const {
  27061. ArrayFrom,
  27062. ArrayPrototypeForEach,
  27063. ArrayPrototypeIncludes,
  27064. ArrayPrototypeJoin,
  27065. ArrayPrototypePop,
  27066. ArrayPrototypePush,
  27067. FunctionPrototype,
  27068. ObjectKeys,
  27069. RegExpPrototypeSymbolReplace,
  27070. StringPrototypeEndsWith,
  27071. StringPrototypeIncludes,
  27072. StringPrototypeIndexOf,
  27073. StringPrototypeRepeat,
  27074. StringPrototypeSplit,
  27075. StringPrototypeStartsWith,
  27076. SyntaxError: SyntaxError$1,
  27077. } = nodePrimordials;
  27078. const parser$1 = acorn$1.exports.Parser;
  27079. const walk$3 = walk$4.exports;
  27080. const { Recoverable } = require$$3__default;
  27081. function isTopLevelDeclaration(state) {
  27082. return state.ancestors[state.ancestors.length - 2] === state.body;
  27083. }
  27084. const noop$3 = FunctionPrototype;
  27085. const visitorsWithoutAncestors = {
  27086. ClassDeclaration(node, state, c) {
  27087. if (isTopLevelDeclaration(state)) {
  27088. state.prepend(node, `${node.id.name}=`);
  27089. ArrayPrototypePush(
  27090. state.hoistedDeclarationStatements,
  27091. `let ${node.id.name}; `
  27092. );
  27093. }
  27094. walk$3.base.ClassDeclaration(node, state, c);
  27095. },
  27096. ForOfStatement(node, state, c) {
  27097. if (node.await === true) {
  27098. state.containsAwait = true;
  27099. }
  27100. walk$3.base.ForOfStatement(node, state, c);
  27101. },
  27102. FunctionDeclaration(node, state, c) {
  27103. state.prepend(node, `${node.id.name}=`);
  27104. ArrayPrototypePush(
  27105. state.hoistedDeclarationStatements,
  27106. `var ${node.id.name}; `
  27107. );
  27108. },
  27109. FunctionExpression: noop$3,
  27110. ArrowFunctionExpression: noop$3,
  27111. MethodDefinition: noop$3,
  27112. AwaitExpression(node, state, c) {
  27113. state.containsAwait = true;
  27114. walk$3.base.AwaitExpression(node, state, c);
  27115. },
  27116. ReturnStatement(node, state, c) {
  27117. state.containsReturn = true;
  27118. walk$3.base.ReturnStatement(node, state, c);
  27119. },
  27120. VariableDeclaration(node, state, c) {
  27121. const variableKind = node.kind;
  27122. const isIterableForDeclaration = ArrayPrototypeIncludes(
  27123. ['ForOfStatement', 'ForInStatement'],
  27124. state.ancestors[state.ancestors.length - 2].type
  27125. );
  27126. if (variableKind === 'var' || isTopLevelDeclaration(state)) {
  27127. state.replace(
  27128. node.start,
  27129. node.start + variableKind.length + (isIterableForDeclaration ? 1 : 0),
  27130. variableKind === 'var' && isIterableForDeclaration ?
  27131. '' :
  27132. 'void' + (node.declarations.length === 1 ? '' : ' (')
  27133. );
  27134. if (!isIterableForDeclaration) {
  27135. ArrayPrototypeForEach(node.declarations, (decl) => {
  27136. state.prepend(decl, '(');
  27137. state.append(decl, decl.init ? ')' : '=undefined)');
  27138. });
  27139. if (node.declarations.length !== 1) {
  27140. state.append(node.declarations[node.declarations.length - 1], ')');
  27141. }
  27142. }
  27143. const variableIdentifiersToHoist = [
  27144. ['var', []],
  27145. ['let', []],
  27146. ];
  27147. function registerVariableDeclarationIdentifiers(node) {
  27148. switch (node.type) {
  27149. case 'Identifier':
  27150. ArrayPrototypePush(
  27151. variableIdentifiersToHoist[variableKind === 'var' ? 0 : 1][1],
  27152. node.name
  27153. );
  27154. break;
  27155. case 'ObjectPattern':
  27156. ArrayPrototypeForEach(node.properties, (property) => {
  27157. registerVariableDeclarationIdentifiers(property.value);
  27158. });
  27159. break;
  27160. case 'ArrayPattern':
  27161. ArrayPrototypeForEach(node.elements, (element) => {
  27162. registerVariableDeclarationIdentifiers(element);
  27163. });
  27164. break;
  27165. }
  27166. }
  27167. ArrayPrototypeForEach(node.declarations, (decl) => {
  27168. registerVariableDeclarationIdentifiers(decl.id);
  27169. });
  27170. ArrayPrototypeForEach(
  27171. variableIdentifiersToHoist,
  27172. ({ 0: kind, 1: identifiers }) => {
  27173. if (identifiers.length > 0) {
  27174. ArrayPrototypePush(
  27175. state.hoistedDeclarationStatements,
  27176. `${kind} ${ArrayPrototypeJoin(identifiers, ', ')}; `
  27177. );
  27178. }
  27179. }
  27180. );
  27181. }
  27182. walk$3.base.VariableDeclaration(node, state, c);
  27183. }
  27184. };
  27185. const visitors = {};
  27186. for (const nodeType of ObjectKeys(walk$3.base)) {
  27187. const callback = visitorsWithoutAncestors[nodeType] || walk$3.base[nodeType];
  27188. visitors[nodeType] = (node, state, c) => {
  27189. const isNew = node !== state.ancestors[state.ancestors.length - 1];
  27190. if (isNew) {
  27191. ArrayPrototypePush(state.ancestors, node);
  27192. }
  27193. callback(node, state, c);
  27194. if (isNew) {
  27195. ArrayPrototypePop(state.ancestors);
  27196. }
  27197. };
  27198. }
  27199. function processTopLevelAwait(src) {
  27200. const wrapPrefix = '(async () => { ';
  27201. const wrapped = `${wrapPrefix}${src} })()`;
  27202. const wrappedArray = ArrayFrom(wrapped);
  27203. let root;
  27204. try {
  27205. root = parser$1.parse(wrapped, { ecmaVersion: 'latest' });
  27206. } catch (e) {
  27207. if (StringPrototypeStartsWith(e.message, 'Unterminated '))
  27208. throw new Recoverable(e);
  27209. // If the parse error is before the first "await", then use the execution
  27210. // error. Otherwise we must emit this parse error, making it look like a
  27211. // proper syntax error.
  27212. const awaitPos = StringPrototypeIndexOf(src, 'await');
  27213. const errPos = e.pos - wrapPrefix.length;
  27214. if (awaitPos > errPos)
  27215. return null;
  27216. // Convert keyword parse errors on await into their original errors when
  27217. // possible.
  27218. if (errPos === awaitPos + 6 &&
  27219. StringPrototypeIncludes(e.message, 'Expecting Unicode escape sequence'))
  27220. return null;
  27221. if (errPos === awaitPos + 7 &&
  27222. StringPrototypeIncludes(e.message, 'Unexpected token'))
  27223. return null;
  27224. const line = e.loc.line;
  27225. const column = line === 1 ? e.loc.column - wrapPrefix.length : e.loc.column;
  27226. let message = '\n' + StringPrototypeSplit(src, '\n')[line - 1] + '\n' +
  27227. StringPrototypeRepeat(' ', column) +
  27228. '^\n\n' + RegExpPrototypeSymbolReplace(/ \([^)]+\)/, e.message, '');
  27229. // V8 unexpected token errors include the token string.
  27230. if (StringPrototypeEndsWith(message, 'Unexpected token'))
  27231. message += " '" +
  27232. // Wrapper end may cause acorn to report error position after the source
  27233. ((src.length - 1) >= (e.pos - wrapPrefix.length)
  27234. ? src[e.pos - wrapPrefix.length]
  27235. : src[src.length - 1]) +
  27236. "'";
  27237. // eslint-disable-next-line no-restricted-syntax
  27238. throw new SyntaxError$1(message);
  27239. }
  27240. const body = root.body[0].expression.callee.body;
  27241. const state = {
  27242. body,
  27243. ancestors: [],
  27244. hoistedDeclarationStatements: [],
  27245. replace(from, to, str) {
  27246. for (let i = from; i < to; i++) {
  27247. wrappedArray[i] = '';
  27248. }
  27249. if (from === to) str += wrappedArray[from];
  27250. wrappedArray[from] = str;
  27251. },
  27252. prepend(node, str) {
  27253. wrappedArray[node.start] = str + wrappedArray[node.start];
  27254. },
  27255. append(node, str) {
  27256. wrappedArray[node.end - 1] += str;
  27257. },
  27258. containsAwait: false,
  27259. containsReturn: false
  27260. };
  27261. walk$3.recursive(body, state, visitors);
  27262. // Do not transform if
  27263. // 1. False alarm: there isn't actually an await expression.
  27264. // 2. There is a top-level return, which is not allowed.
  27265. if (!state.containsAwait || state.containsReturn) {
  27266. return null;
  27267. }
  27268. const last = body.body[body.body.length - 1];
  27269. if (last.type === 'ExpressionStatement') {
  27270. // For an expression statement of the form
  27271. // ( expr ) ;
  27272. // ^^^^^^^^^^ // last
  27273. // ^^^^ // last.expression
  27274. //
  27275. // We do not want the left parenthesis before the `return` keyword;
  27276. // therefore we prepend the `return (` to `last`.
  27277. //
  27278. // On the other hand, we do not want the right parenthesis after the
  27279. // semicolon. Since there can only be more right parentheses between
  27280. // last.expression.end and the semicolon, appending one more to
  27281. // last.expression should be fine.
  27282. state.prepend(last, 'return (');
  27283. state.append(last.expression, ')');
  27284. }
  27285. return (
  27286. ArrayPrototypeJoin(state.hoistedDeclarationStatements, '') +
  27287. ArrayPrototypeJoin(wrappedArray, '')
  27288. );
  27289. }
  27290. var nodeReplAwait = {
  27291. processTopLevelAwait
  27292. };
  27293. (function (exports) {
  27294. var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
  27295. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  27296. return new (P || (P = Promise))(function (resolve, reject) {
  27297. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  27298. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  27299. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  27300. step((generator = generator.apply(thisArg, _arguments || [])).next());
  27301. });
  27302. };
  27303. var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
  27304. var t = {};
  27305. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  27306. t[p] = s[p];
  27307. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  27308. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  27309. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  27310. t[p[i]] = s[p[i]];
  27311. }
  27312. return t;
  27313. };
  27314. Object.defineProperty(exports, "__esModule", { value: true });
  27315. exports.setupContext = exports.createEvalAwarePartialHost = exports.EvalState = exports.createRepl = exports.REPL_NAME = exports.REPL_FILENAME = exports.STDIN_NAME = exports.STDIN_FILENAME = exports.EVAL_NAME = exports.EVAL_FILENAME = void 0;
  27316. const diff_1 = require$$0$2;
  27317. const os_1 = require$$0__default$1;
  27318. const path_1 = path__default;
  27319. const repl_1 = require$$3__default;
  27320. const vm_1 = require$$4__default;
  27321. const index_1 = dist$1;
  27322. const fs_1 = fs__default;
  27323. const console_1 = require$$7__default;
  27324. const assert = require$$6__default;
  27325. // Lazy-loaded.
  27326. let _processTopLevelAwait;
  27327. function getProcessTopLevelAwait() {
  27328. if (_processTopLevelAwait === undefined) {
  27329. ({
  27330. processTopLevelAwait: _processTopLevelAwait,
  27331. } = nodeReplAwait);
  27332. }
  27333. return _processTopLevelAwait;
  27334. }
  27335. /** @internal */
  27336. exports.EVAL_FILENAME = `[eval].ts`;
  27337. /** @internal */
  27338. exports.EVAL_NAME = `[eval]`;
  27339. /** @internal */
  27340. exports.STDIN_FILENAME = `[stdin].ts`;
  27341. /** @internal */
  27342. exports.STDIN_NAME = `[stdin]`;
  27343. /** @internal */
  27344. exports.REPL_FILENAME = '<repl>.ts';
  27345. /** @internal */
  27346. exports.REPL_NAME = '<repl>';
  27347. /**
  27348. * Create a ts-node REPL instance.
  27349. *
  27350. * Pay close attention to the example below. Today, the API requires a few lines
  27351. * of boilerplate to correctly bind the `ReplService` to the ts-node `Service` and
  27352. * vice-versa.
  27353. *
  27354. * Usage example:
  27355. *
  27356. * const repl = tsNode.createRepl();
  27357. * const service = tsNode.create({...repl.evalAwarePartialHost});
  27358. * repl.setService(service);
  27359. * repl.start();
  27360. */
  27361. function createRepl(options = {}) {
  27362. var _a, _b, _c, _d, _e;
  27363. const { ignoreDiagnosticsThatAreAnnoyingInInteractiveRepl = true } = options;
  27364. let service = options.service;
  27365. // If `useGlobal` is not true, then REPL creates a context when started.
  27366. // This stores a reference to it or to `global`, whichever is used, after REPL has started.
  27367. let context;
  27368. const state = (_a = options.state) !== null && _a !== void 0 ? _a : new EvalState(path_1.join(process.cwd(), exports.REPL_FILENAME));
  27369. const evalAwarePartialHost = createEvalAwarePartialHost(state, options.composeWithEvalAwarePartialHost);
  27370. const stdin = (_b = options.stdin) !== null && _b !== void 0 ? _b : process.stdin;
  27371. const stdout = (_c = options.stdout) !== null && _c !== void 0 ? _c : process.stdout;
  27372. const stderr = (_d = options.stderr) !== null && _d !== void 0 ? _d : process.stderr;
  27373. const _console = stdout === process.stdout && stderr === process.stderr
  27374. ? console
  27375. : new console_1.Console(stdout, stderr);
  27376. const replService = {
  27377. state: (_e = options.state) !== null && _e !== void 0 ? _e : new EvalState(path_1.join(process.cwd(), exports.EVAL_FILENAME)),
  27378. setService,
  27379. evalCode,
  27380. evalCodeInternal,
  27381. nodeEval,
  27382. evalAwarePartialHost,
  27383. start,
  27384. startInternal,
  27385. stdin,
  27386. stdout,
  27387. stderr,
  27388. console: _console,
  27389. };
  27390. return replService;
  27391. function setService(_service) {
  27392. service = _service;
  27393. if (ignoreDiagnosticsThatAreAnnoyingInInteractiveRepl) {
  27394. service.addDiagnosticFilter({
  27395. appliesToAllFiles: false,
  27396. filenamesAbsolute: [state.path],
  27397. diagnosticsIgnored: [
  27398. 2393,
  27399. 6133,
  27400. 7027,
  27401. ...(service.shouldReplAwait ? topLevelAwaitDiagnosticCodes : []),
  27402. ],
  27403. });
  27404. }
  27405. }
  27406. function evalCode(code) {
  27407. const result = appendCompileAndEvalInput({
  27408. service: service,
  27409. state,
  27410. input: code,
  27411. context,
  27412. });
  27413. assert(result.containsTopLevelAwait === false);
  27414. return result.value;
  27415. }
  27416. function evalCodeInternal(options) {
  27417. const { code, enableTopLevelAwait, context } = options;
  27418. return appendCompileAndEvalInput({
  27419. service: service,
  27420. state,
  27421. input: code,
  27422. enableTopLevelAwait,
  27423. context,
  27424. });
  27425. }
  27426. function nodeEval(code, context, _filename, callback) {
  27427. // TODO: Figure out how to handle completion here.
  27428. if (code === '.scope') {
  27429. callback(null);
  27430. return;
  27431. }
  27432. try {
  27433. const evalResult = evalCodeInternal({
  27434. code,
  27435. enableTopLevelAwait: true,
  27436. context,
  27437. });
  27438. if (evalResult.containsTopLevelAwait) {
  27439. (() => __awaiter(this, void 0, void 0, function* () {
  27440. try {
  27441. callback(null, yield evalResult.valuePromise);
  27442. }
  27443. catch (promiseError) {
  27444. handleError(promiseError);
  27445. }
  27446. }))();
  27447. }
  27448. else {
  27449. callback(null, evalResult.value);
  27450. }
  27451. }
  27452. catch (error) {
  27453. handleError(error);
  27454. }
  27455. // Log TSErrors, check if they're recoverable, log helpful hints for certain
  27456. // well-known errors, and invoke `callback()`
  27457. // TODO should evalCode API get the same error-handling benefits?
  27458. function handleError(error) {
  27459. var _a, _b;
  27460. // Don't show TLA hint if the user explicitly disabled repl top level await
  27461. const canLogTopLevelAwaitHint = service.options.experimentalReplAwait !== false &&
  27462. !service.shouldReplAwait;
  27463. if (error instanceof index_1.TSError) {
  27464. // Support recoverable compilations using >= node 6.
  27465. if (repl_1.Recoverable && isRecoverable(error)) {
  27466. callback(new repl_1.Recoverable(error));
  27467. return;
  27468. }
  27469. else {
  27470. _console.error(error);
  27471. if (canLogTopLevelAwaitHint &&
  27472. error.diagnosticCodes.some((dC) => topLevelAwaitDiagnosticCodes.includes(dC))) {
  27473. _console.error(getTopLevelAwaitHint());
  27474. }
  27475. callback(null);
  27476. }
  27477. }
  27478. else {
  27479. let _error = error;
  27480. if (canLogTopLevelAwaitHint &&
  27481. _error instanceof SyntaxError &&
  27482. ((_a = _error.message) === null || _a === void 0 ? void 0 : _a.includes('await is only valid'))) {
  27483. try {
  27484. // Only way I know to make our hint appear after the error
  27485. _error.message += `\n\n${getTopLevelAwaitHint()}`;
  27486. _error.stack = (_b = _error.stack) === null || _b === void 0 ? void 0 : _b.replace(/(SyntaxError:.*)/, (_, $1) => `${$1}\n\n${getTopLevelAwaitHint()}`);
  27487. }
  27488. catch (_c) { }
  27489. }
  27490. callback(_error);
  27491. }
  27492. }
  27493. function getTopLevelAwaitHint() {
  27494. return `Hint: REPL top-level await requires TypeScript version 3.8 or higher and target ES2018 or higher. You are using TypeScript ${service.ts.version} and target ${service.ts.ScriptTarget[service.config.options.target]}.`;
  27495. }
  27496. }
  27497. // Note: `code` argument is deprecated
  27498. function start(code) {
  27499. startInternal({ code });
  27500. }
  27501. // Note: `code` argument is deprecated
  27502. function startInternal(options) {
  27503. const _a = options !== null && options !== void 0 ? options : {}, { code, forceToBeModule = true } = _a, optionsOverride = __rest(_a, ["code", "forceToBeModule"]);
  27504. // TODO assert that `service` is set; remove all `service!` non-null assertions
  27505. // Eval incoming code before the REPL starts.
  27506. // Note: deprecated
  27507. if (code) {
  27508. try {
  27509. evalCode(`${code}\n`);
  27510. }
  27511. catch (err) {
  27512. _console.error(err);
  27513. // Note: should not be killing the process here, but this codepath is deprecated anyway
  27514. process.exit(1);
  27515. }
  27516. }
  27517. const repl = repl_1.start(Object.assign({ prompt: '> ', input: replService.stdin, output: replService.stdout,
  27518. // Mimicking node's REPL implementation: https://github.com/nodejs/node/blob/168b22ba073ee1cbf8d0bcb4ded7ff3099335d04/lib/internal/repl.js#L28-L30
  27519. terminal: stdout.isTTY &&
  27520. !parseInt(index_1.env.NODE_NO_READLINE, 10), eval: nodeEval, useGlobal: true }, optionsOverride));
  27521. context = repl.context;
  27522. // Bookmark the point where we should reset the REPL state.
  27523. const resetEval = appendToEvalState(state, '');
  27524. function reset() {
  27525. resetEval();
  27526. // Hard fix for TypeScript forcing `Object.defineProperty(exports, ...)`.
  27527. runInContext('exports = module.exports', state.path, context);
  27528. if (forceToBeModule) {
  27529. state.input += 'export {};void 0;\n';
  27530. }
  27531. }
  27532. reset();
  27533. repl.on('reset', reset);
  27534. repl.defineCommand('type', {
  27535. help: 'Check the type of a TypeScript identifier',
  27536. action: function (identifier) {
  27537. if (!identifier) {
  27538. repl.displayPrompt();
  27539. return;
  27540. }
  27541. const undo = appendToEvalState(state, identifier);
  27542. const { name, comment } = service.getTypeInfo(state.input, state.path, state.input.length);
  27543. undo();
  27544. if (name)
  27545. repl.outputStream.write(`${name}\n`);
  27546. if (comment)
  27547. repl.outputStream.write(`${comment}\n`);
  27548. repl.displayPrompt();
  27549. },
  27550. });
  27551. // Set up REPL history when available natively via node.js >= 11.
  27552. if (repl.setupHistory) {
  27553. const historyPath = index_1.env.TS_NODE_HISTORY || path_1.join(os_1.homedir(), '.ts_node_repl_history');
  27554. repl.setupHistory(historyPath, (err) => {
  27555. if (!err)
  27556. return;
  27557. _console.error(err);
  27558. process.exit(1);
  27559. });
  27560. }
  27561. return repl;
  27562. }
  27563. }
  27564. exports.createRepl = createRepl;
  27565. /**
  27566. * Eval state management. Stores virtual `[eval].ts` file
  27567. */
  27568. class EvalState {
  27569. constructor(path) {
  27570. this.path = path;
  27571. /** @internal */
  27572. this.input = '';
  27573. /** @internal */
  27574. this.output = '';
  27575. /** @internal */
  27576. this.version = 0;
  27577. /** @internal */
  27578. this.lines = 0;
  27579. }
  27580. }
  27581. exports.EvalState = EvalState;
  27582. function createEvalAwarePartialHost(state, composeWith) {
  27583. function readFile(path) {
  27584. if (path === state.path)
  27585. return state.input;
  27586. if (composeWith === null || composeWith === void 0 ? void 0 : composeWith.readFile)
  27587. return composeWith.readFile(path);
  27588. try {
  27589. return fs_1.readFileSync(path, 'utf8');
  27590. }
  27591. catch (err) {
  27592. /* Ignore. */
  27593. }
  27594. }
  27595. function fileExists(path) {
  27596. if (path === state.path)
  27597. return true;
  27598. if (composeWith === null || composeWith === void 0 ? void 0 : composeWith.fileExists)
  27599. return composeWith.fileExists(path);
  27600. try {
  27601. const stats = fs_1.statSync(path);
  27602. return stats.isFile() || stats.isFIFO();
  27603. }
  27604. catch (err) {
  27605. return false;
  27606. }
  27607. }
  27608. return { readFile, fileExists };
  27609. }
  27610. exports.createEvalAwarePartialHost = createEvalAwarePartialHost;
  27611. /**
  27612. * Evaluate the code snippet.
  27613. *
  27614. * Append it to virtual .ts file, compile, handle compiler errors, compute a diff of the JS, and eval any code that
  27615. * appears as "added" in the diff.
  27616. */
  27617. function appendCompileAndEvalInput(options) {
  27618. const { service, state, input, enableTopLevelAwait = false, context, } = options;
  27619. const lines = state.lines;
  27620. const isCompletion = !/\n$/.test(input);
  27621. const undo = appendToEvalState(state, input);
  27622. let output;
  27623. // Based on https://github.com/nodejs/node/blob/92573721c7cff104ccb82b6ed3e8aa69c4b27510/lib/repl.js#L457-L461
  27624. function adjustUseStrict(code) {
  27625. // "void 0" keeps the repl from returning "use strict" as the result
  27626. // value for statements and declarations that don't return a value.
  27627. return code.replace(/^"use strict";/, '"use strict"; void 0;');
  27628. }
  27629. try {
  27630. output = service.compile(state.input, state.path, -lines);
  27631. }
  27632. catch (err) {
  27633. undo();
  27634. throw err;
  27635. }
  27636. output = adjustUseStrict(output);
  27637. // Use `diff` to check for new JavaScript to execute.
  27638. const changes = diff_1.diffLines(state.output, output);
  27639. if (isCompletion) {
  27640. undo();
  27641. }
  27642. else {
  27643. state.output = output;
  27644. }
  27645. let commands = [];
  27646. let containsTopLevelAwait = false;
  27647. // Build a list of "commands": bits of JS code in the diff that must be executed.
  27648. for (const change of changes) {
  27649. if (change.added) {
  27650. if (enableTopLevelAwait &&
  27651. service.shouldReplAwait &&
  27652. change.value.indexOf('await') > -1) {
  27653. const processTopLevelAwait = getProcessTopLevelAwait();
  27654. // Newline prevents comments to mess with wrapper
  27655. const wrappedResult = processTopLevelAwait(change.value + '\n');
  27656. if (wrappedResult !== null) {
  27657. containsTopLevelAwait = true;
  27658. commands.push({
  27659. mustAwait: true,
  27660. execCommand: () => runInContext(wrappedResult, state.path, context),
  27661. });
  27662. continue;
  27663. }
  27664. }
  27665. commands.push({
  27666. execCommand: () => runInContext(change.value, state.path, context),
  27667. });
  27668. }
  27669. }
  27670. // Execute all commands asynchronously if necessary, returning the result or a
  27671. // promise of the result.
  27672. if (containsTopLevelAwait) {
  27673. return {
  27674. containsTopLevelAwait,
  27675. valuePromise: (() => __awaiter(this, void 0, void 0, function* () {
  27676. let value;
  27677. for (const command of commands) {
  27678. const r = command.execCommand();
  27679. value = command.mustAwait ? yield r : r;
  27680. }
  27681. return value;
  27682. }))(),
  27683. };
  27684. }
  27685. else {
  27686. return {
  27687. containsTopLevelAwait: false,
  27688. value: commands.reduce((_, c) => c.execCommand(), undefined),
  27689. };
  27690. }
  27691. }
  27692. /**
  27693. * Low-level execution of JS code in context
  27694. */
  27695. function runInContext(code, filename, context) {
  27696. const script = new vm_1.Script(code, { filename });
  27697. if (context === undefined || context === commonjsGlobal) {
  27698. return script.runInThisContext();
  27699. }
  27700. else {
  27701. return script.runInContext(context);
  27702. }
  27703. }
  27704. /**
  27705. * Append to the eval instance and return an undo function.
  27706. */
  27707. function appendToEvalState(state, input) {
  27708. const undoInput = state.input;
  27709. const undoVersion = state.version;
  27710. const undoOutput = state.output;
  27711. const undoLines = state.lines;
  27712. // Handle ASI issues with TypeScript re-evaluation.
  27713. if (undoInput.charAt(undoInput.length - 1) === '\n' &&
  27714. /^\s*[\/\[(`-]/.test(input) &&
  27715. !/;\s*$/.test(undoInput)) {
  27716. state.input = `${state.input.slice(0, -1)};\n`;
  27717. }
  27718. state.input += input;
  27719. state.lines += lineCount(input);
  27720. state.version++;
  27721. return function () {
  27722. state.input = undoInput;
  27723. state.output = undoOutput;
  27724. state.version = undoVersion;
  27725. state.lines = undoLines;
  27726. };
  27727. }
  27728. /**
  27729. * Count the number of lines.
  27730. */
  27731. function lineCount(value) {
  27732. let count = 0;
  27733. for (const char of value) {
  27734. if (char === '\n') {
  27735. count++;
  27736. }
  27737. }
  27738. return count;
  27739. }
  27740. /**
  27741. * TS diagnostic codes which are recoverable, meaning that the user likely entered and incomplete line of code
  27742. * and should be prompted for the next. For example, starting a multi-line for() loop and not finishing it.
  27743. */
  27744. const RECOVERY_CODES = new Set([
  27745. 1003,
  27746. 1005,
  27747. 1109,
  27748. 1126,
  27749. 1160,
  27750. 1161,
  27751. 2355, // "A function whose declared type is neither 'void' nor 'any' must return a value."
  27752. ]);
  27753. /**
  27754. * Diagnostic codes raised when using top-level await.
  27755. * These are suppressed when top-level await is enabled.
  27756. * When it is *not* enabled, these trigger a helpful hint about enabling top-level await.
  27757. */
  27758. const topLevelAwaitDiagnosticCodes = [
  27759. 1375,
  27760. 1378,
  27761. 1431,
  27762. 1432, // Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  27763. ];
  27764. /**
  27765. * Check if a function can recover gracefully.
  27766. */
  27767. function isRecoverable(error) {
  27768. return error.diagnosticCodes.every((code) => RECOVERY_CODES.has(code));
  27769. }
  27770. /**
  27771. * @internal
  27772. * Set properties on `context` before eval-ing [stdin] or [eval] input.
  27773. */
  27774. function setupContext(context, module, filenameAndDirname) {
  27775. if (filenameAndDirname) {
  27776. context.__dirname = '.';
  27777. context.__filename = `[${filenameAndDirname}]`;
  27778. }
  27779. context.module = module;
  27780. context.exports = module.exports;
  27781. context.require = module.require.bind(module);
  27782. }
  27783. exports.setupContext = setupContext;
  27784. }(repl));
  27785. var nodeCjsLoaderUtils = {};
  27786. const fs$j = fs__default;
  27787. // In node's core, this is implemented in C
  27788. // https://github.com/nodejs/node/blob/v15.3.0/src/node_file.cc#L891-L985
  27789. function internalModuleReadJSON$1(path) {
  27790. let string;
  27791. try {
  27792. string = fs$j.readFileSync(path, 'utf8');
  27793. } catch (e) {
  27794. if (e.code === 'ENOENT') return []
  27795. throw e
  27796. }
  27797. // Node's implementation checks for the presence of relevant keys: main, name, type, exports, imports
  27798. // Node does this for performance to skip unnecessary parsing.
  27799. // This would slow us down and, based on our usage, we can skip it.
  27800. const containsKeys = true;
  27801. return [string, containsKeys]
  27802. }
  27803. var nodeInternalFs = {
  27804. internalModuleReadJSON: internalModuleReadJSON$1
  27805. };
  27806. const flagSymbol = Symbol('arg flag');
  27807. function arg(opts, {argv = process.argv.slice(2), permissive = false, stopAtPositional = false} = {}) {
  27808. if (!opts) {
  27809. throw new Error('Argument specification object is required');
  27810. }
  27811. const result = {_: []};
  27812. const aliases = {};
  27813. const handlers = {};
  27814. for (const key of Object.keys(opts)) {
  27815. if (!key) {
  27816. throw new TypeError('Argument key cannot be an empty string');
  27817. }
  27818. if (key[0] !== '-') {
  27819. throw new TypeError(`Argument key must start with '-' but found: '${key}'`);
  27820. }
  27821. if (key.length === 1) {
  27822. throw new TypeError(`Argument key must have a name; singular '-' keys are not allowed: ${key}`);
  27823. }
  27824. if (typeof opts[key] === 'string') {
  27825. aliases[key] = opts[key];
  27826. continue;
  27827. }
  27828. let type = opts[key];
  27829. let isFlag = false;
  27830. if (Array.isArray(type) && type.length === 1 && typeof type[0] === 'function') {
  27831. const [fn] = type;
  27832. type = (value, name, prev = []) => {
  27833. prev.push(fn(value, name, prev[prev.length - 1]));
  27834. return prev;
  27835. };
  27836. isFlag = fn === Boolean || fn[flagSymbol] === true;
  27837. } else if (typeof type === 'function') {
  27838. isFlag = type === Boolean || type[flagSymbol] === true;
  27839. } else {
  27840. throw new TypeError(`Type missing or not a function or valid array type: ${key}`);
  27841. }
  27842. if (key[1] !== '-' && key.length > 2) {
  27843. throw new TypeError(`Short argument keys (with a single hyphen) must have only one character: ${key}`);
  27844. }
  27845. handlers[key] = [type, isFlag];
  27846. }
  27847. for (let i = 0, len = argv.length; i < len; i++) {
  27848. const wholeArg = argv[i];
  27849. if (stopAtPositional && result._.length > 0) {
  27850. result._ = result._.concat(argv.slice(i));
  27851. break;
  27852. }
  27853. if (wholeArg === '--') {
  27854. result._ = result._.concat(argv.slice(i + 1));
  27855. break;
  27856. }
  27857. if (wholeArg.length > 1 && wholeArg[0] === '-') {
  27858. /* eslint-disable operator-linebreak */
  27859. const separatedArguments = (wholeArg[1] === '-' || wholeArg.length === 2)
  27860. ? [wholeArg]
  27861. : wholeArg.slice(1).split('').map(a => `-${a}`);
  27862. /* eslint-enable operator-linebreak */
  27863. for (let j = 0; j < separatedArguments.length; j++) {
  27864. const arg = separatedArguments[j];
  27865. const [originalArgName, argStr] = arg[1] === '-' ? arg.split(/=(.*)/, 2) : [arg, undefined];
  27866. let argName = originalArgName;
  27867. while (argName in aliases) {
  27868. argName = aliases[argName];
  27869. }
  27870. if (!(argName in handlers)) {
  27871. if (permissive) {
  27872. result._.push(arg);
  27873. continue;
  27874. } else {
  27875. const err = new Error(`Unknown or unexpected option: ${originalArgName}`);
  27876. err.code = 'ARG_UNKNOWN_OPTION';
  27877. throw err;
  27878. }
  27879. }
  27880. const [type, isFlag] = handlers[argName];
  27881. if (!isFlag && ((j + 1) < separatedArguments.length)) {
  27882. throw new TypeError(`Option requires argument (but was followed by another short argument): ${originalArgName}`);
  27883. }
  27884. if (isFlag) {
  27885. result[argName] = type(true, argName, result[argName]);
  27886. } else if (argStr === undefined) {
  27887. if (
  27888. argv.length < i + 2 ||
  27889. (
  27890. argv[i + 1].length > 1 &&
  27891. (argv[i + 1][0] === '-') &&
  27892. !(
  27893. argv[i + 1].match(/^-?\d*(\.(?=\d))?\d*$/) &&
  27894. (
  27895. type === Number ||
  27896. // eslint-disable-next-line no-undef
  27897. (typeof BigInt !== 'undefined' && type === BigInt)
  27898. )
  27899. )
  27900. )
  27901. ) {
  27902. const extended = originalArgName === argName ? '' : ` (alias for ${argName})`;
  27903. throw new Error(`Option requires argument: ${originalArgName}${extended}`);
  27904. }
  27905. result[argName] = type(argv[i + 1], argName, result[argName]);
  27906. ++i;
  27907. } else {
  27908. result[argName] = type(argStr, argName, result[argName]);
  27909. }
  27910. }
  27911. } else {
  27912. result._.push(wholeArg);
  27913. }
  27914. }
  27915. return result;
  27916. }
  27917. arg.flag = fn => {
  27918. fn[flagSymbol] = true;
  27919. return fn;
  27920. };
  27921. // Utility types
  27922. arg.COUNT = arg.flag((v, name, existingCount) => (existingCount || 0) + 1);
  27923. const { SafeMap } = nodePrimordials;
  27924. const { internalModuleReadJSON } = nodeInternalFs;
  27925. const { pathToFileURL } = require$$0__default$7;
  27926. const { toNamespacedPath } = path__default;
  27927. const cache = new SafeMap();
  27928. let manifest;
  27929. /**
  27930. * @param {string} jsonPath
  27931. * @return {[string, boolean]}
  27932. */
  27933. function read(jsonPath) {
  27934. if (cache.has(jsonPath)) {
  27935. return cache.get(jsonPath);
  27936. }
  27937. const [string, containsKeys] = internalModuleReadJSON(
  27938. toNamespacedPath(jsonPath)
  27939. );
  27940. const result = { string, containsKeys };
  27941. if (string !== undefined) {
  27942. if (manifest === undefined) {
  27943. // manifest = getOptionValue('--experimental-policy') ?
  27944. // require('internal/process/policy').manifest :
  27945. // null;
  27946. // disabled for now. I am not sure if/how we should support this
  27947. manifest = null;
  27948. }
  27949. if (manifest !== null) {
  27950. const jsonURL = pathToFileURL(jsonPath);
  27951. manifest.assertIntegrity(jsonURL, string);
  27952. }
  27953. }
  27954. cache.set(jsonPath, result);
  27955. return result;
  27956. }
  27957. var nodePackageJsonReader = { read };
  27958. // Copied from several files in node's source code.
  27959. // https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/modules/cjs/loader.js
  27960. // Each function and variable below must have a comment linking to the source in node's github repo.
  27961. const path$i = path__default;
  27962. const packageJsonReader = nodePackageJsonReader;
  27963. const {JSONParse} = nodePrimordials;
  27964. const {normalizeSlashes} = util$7;
  27965. nodeCjsLoaderUtils.assertScriptCanLoadAsCJSImpl = assertScriptCanLoadAsCJSImpl;
  27966. /**
  27967. * copied from Module._extensions['.js']
  27968. * https://github.com/nodejs/node/blob/v15.3.0/lib/internal/modules/cjs/loader.js#L1113-L1120
  27969. * @param {import('../src/index').Service} service
  27970. * @param {NodeJS.Module} module
  27971. * @param {string} filename
  27972. */
  27973. function assertScriptCanLoadAsCJSImpl(service, module, filename) {
  27974. const pkg = readPackageScope(filename);
  27975. // ts-node modification: allow our configuration to override
  27976. const tsNodeClassification = service.moduleTypeClassifier.classifyModule(normalizeSlashes(filename));
  27977. if(tsNodeClassification.moduleType === 'cjs') return;
  27978. // Function require shouldn't be used in ES modules.
  27979. if (tsNodeClassification.moduleType === 'esm' || (pkg && pkg.data && pkg.data.type === 'module')) {
  27980. const parentPath = module.parent && module.parent.filename;
  27981. const packageJsonPath = pkg ? path$i.resolve(pkg.path, 'package.json') : null;
  27982. throw createErrRequireEsm(filename, parentPath, packageJsonPath);
  27983. }
  27984. }
  27985. // Copied from https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/modules/cjs/loader.js#L285-L301
  27986. function readPackageScope(checkPath) {
  27987. const rootSeparatorIndex = checkPath.indexOf(path$i.sep);
  27988. let separatorIndex;
  27989. while (
  27990. (separatorIndex = checkPath.lastIndexOf(path$i.sep)) > rootSeparatorIndex
  27991. ) {
  27992. checkPath = checkPath.slice(0, separatorIndex);
  27993. if (checkPath.endsWith(path$i.sep + 'node_modules'))
  27994. return false;
  27995. const pjson = readPackage(checkPath);
  27996. if (pjson) return {
  27997. path: checkPath,
  27998. data: pjson
  27999. };
  28000. }
  28001. return false;
  28002. }
  28003. // Copied from https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/modules/cjs/loader.js#L249
  28004. const packageJsonCache = new Map();
  28005. // Copied from https://github.com/nodejs/node/blob/v15.3.0/lib/internal/modules/cjs/loader.js#L275-L304
  28006. function readPackage(requestPath) {
  28007. const jsonPath = path$i.resolve(requestPath, 'package.json');
  28008. const existing = packageJsonCache.get(jsonPath);
  28009. if (existing !== undefined) return existing;
  28010. const result = packageJsonReader.read(jsonPath);
  28011. const json = result.containsKeys === false ? '{}' : result.string;
  28012. if (json === undefined) {
  28013. packageJsonCache.set(jsonPath, false);
  28014. return false;
  28015. }
  28016. try {
  28017. const parsed = JSONParse(json);
  28018. const filtered = {
  28019. name: parsed.name,
  28020. main: parsed.main,
  28021. exports: parsed.exports,
  28022. imports: parsed.imports,
  28023. type: parsed.type
  28024. };
  28025. packageJsonCache.set(jsonPath, filtered);
  28026. return filtered;
  28027. } catch (e) {
  28028. e.path = jsonPath;
  28029. e.message = 'Error parsing ' + jsonPath + ': ' + e.message;
  28030. throw e;
  28031. }
  28032. }
  28033. // Native ERR_REQUIRE_ESM Error is declared here:
  28034. // https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L1294-L1313
  28035. // Error class factory is implemented here:
  28036. // function E: https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L323-L341
  28037. // function makeNodeErrorWithCode: https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L251-L278
  28038. // The code below should create an error that matches the native error as closely as possible.
  28039. // Third-party libraries which attempt to catch the native ERR_REQUIRE_ESM should recognize our imitation error.
  28040. function createErrRequireEsm(filename, parentPath, packageJsonPath) {
  28041. const code = 'ERR_REQUIRE_ESM';
  28042. const err = new Error(getMessage(filename, parentPath, packageJsonPath));
  28043. // Set `name` to be used in stack trace, generate stack trace with that name baked in, then re-declare the `name` field.
  28044. // This trick is copied from node's source.
  28045. err.name = `Error [${ code }]`;
  28046. Object.defineProperty(err, 'name', {
  28047. value: 'Error',
  28048. enumerable: false,
  28049. writable: true,
  28050. configurable: true
  28051. });
  28052. err.code = code;
  28053. return err
  28054. // Copy-pasted from https://github.com/nodejs/node/blob/b533fb3508009e5f567cc776daba8fbf665386a6/lib/internal/errors.js#L1293-L1311
  28055. // so that our error message is identical to the native message.
  28056. function getMessage(filename, parentPath = null, packageJsonPath = null) {
  28057. const ext = path$i.extname(filename);
  28058. let msg = `Must use import to load ES Module: ${filename}`;
  28059. if (parentPath && packageJsonPath) {
  28060. const path = path__default;
  28061. path.basename(filename) === path.basename(parentPath) ?
  28062. filename : path.basename(filename);
  28063. msg +=
  28064. '\nrequire() of ES modules is not supported.\nrequire() of ' +
  28065. `${filename} ${parentPath ? `from ${parentPath} ` : ''}` +
  28066. `is an ES module file as it is a ${ext} file whose nearest parent ` +
  28067. `package.json contains "type": "module" which defines all ${ext} ` +
  28068. 'files in that package scope as ES modules.\nInstead ' +
  28069. 'change the requiring code to use ' +
  28070. 'import(), or remove "type": "module" from ' +
  28071. `${packageJsonPath}.\n`;
  28072. return msg;
  28073. }
  28074. return msg;
  28075. }
  28076. }
  28077. var name = "ts-node";
  28078. var version$2 = "10.2.1";
  28079. var description = "TypeScript execution environment and REPL for node.js, with source map support";
  28080. var main$3 = "dist/index.js";
  28081. var exports$1 = {
  28082. ".": "./dist/index.js",
  28083. "./package": "./package.json",
  28084. "./package.json": "./package.json",
  28085. "./dist/bin": "./dist/bin.js",
  28086. "./dist/bin.js": "./dist/bin.js",
  28087. "./dist/bin-transpile": "./dist/bin-transpile.js",
  28088. "./dist/bin-transpile.js": "./dist/bin-transpile.js",
  28089. "./dist/bin-script": "./dist/bin-script.js",
  28090. "./dist/bin-script.js": "./dist/bin-script.js",
  28091. "./dist/bin-cwd": "./dist/bin-cwd.js",
  28092. "./dist/bin-cwd.js": "./dist/bin-cwd.js",
  28093. "./register": "./register/index.js",
  28094. "./register/files": "./register/files.js",
  28095. "./register/transpile-only": "./register/transpile-only.js",
  28096. "./register/type-check": "./register/type-check.js",
  28097. "./esm": "./esm.mjs",
  28098. "./esm.mjs": "./esm.mjs",
  28099. "./esm/transpile-only": "./esm/transpile-only.mjs",
  28100. "./esm/transpile-only.mjs": "./esm/transpile-only.mjs",
  28101. "./transpilers/swc-experimental": "./transpilers/swc-experimental.js",
  28102. "./node10/tsconfig.json": "./node10/tsconfig.json",
  28103. "./node12/tsconfig.json": "./node12/tsconfig.json",
  28104. "./node14/tsconfig.json": "./node14/tsconfig.json",
  28105. "./node16/tsconfig.json": "./node16/tsconfig.json"
  28106. };
  28107. var types$2 = "dist/index.d.ts";
  28108. var bin = {
  28109. "ts-node": "dist/bin.js",
  28110. "ts-script": "dist/bin-script-deprecated.js",
  28111. "ts-node-script": "dist/bin-script.js",
  28112. "ts-node-cwd": "dist/bin-cwd.js",
  28113. "ts-node-transpile-only": "dist/bin-transpile.js"
  28114. };
  28115. var files = [
  28116. "/transpilers/",
  28117. "/dist/",
  28118. "!/dist/test",
  28119. "/dist-raw/**.js",
  28120. "/register/",
  28121. "/esm/",
  28122. "/esm.mjs",
  28123. "/LICENSE",
  28124. "/tsconfig.schema.json",
  28125. "/tsconfig.schemastore-schema.json",
  28126. "/node10/",
  28127. "/node12/",
  28128. "/node14/",
  28129. "/node16/"
  28130. ];
  28131. var scripts = {
  28132. lint: "prettier --check .",
  28133. "lint-fix": "prettier --write .",
  28134. clean: "rimraf dist tsconfig.schema.json tsconfig.schemastore-schema.json tsconfig.tsbuildinfo tests/ts-node-packed.tgz",
  28135. rebuild: "npm run clean && npm run build",
  28136. build: "npm run build-nopack && npm run build-pack",
  28137. "build-nopack": "npm run build-tsc && npm run build-configSchema",
  28138. "build-tsc": "tsc",
  28139. "build-configSchema": "typescript-json-schema --topRef --refs --validationKeywords allOf --out tsconfig.schema.json tsconfig.build-schema.json TsConfigSchema && node --require ./register ./scripts/create-merged-schema",
  28140. "build-pack": "node ./scripts/build-pack.js",
  28141. "test-spec": "ava",
  28142. "test-cov": "nyc ava",
  28143. test: "npm run build && npm run lint && npm run test-cov --",
  28144. "test-local": "npm run lint-fix && npm run build-tsc && npm run build-pack && npm run test-spec --",
  28145. "coverage-report": "nyc report --reporter=lcov",
  28146. prepare: "npm run clean && npm run build-nopack",
  28147. "api-extractor": "api-extractor run --local --verbose"
  28148. };
  28149. var engines = {
  28150. node: ">=12.0.0"
  28151. };
  28152. var repository = {
  28153. type: "git",
  28154. url: "git://github.com/TypeStrong/ts-node.git"
  28155. };
  28156. var keywords$2 = [
  28157. "typescript",
  28158. "node",
  28159. "runtime",
  28160. "environment",
  28161. "ts",
  28162. "compiler"
  28163. ];
  28164. var author = {
  28165. name: "Blake Embrey",
  28166. email: "hello@blakeembrey.com",
  28167. url: "http://blakeembrey.me"
  28168. };
  28169. var contributors = [
  28170. {
  28171. name: "Andrew Bradley",
  28172. email: "cspotcode@gmail.com",
  28173. url: "https://github.com/cspotcode"
  28174. }
  28175. ];
  28176. var license = "MIT";
  28177. var bugs = {
  28178. url: "https://github.com/TypeStrong/ts-node/issues"
  28179. };
  28180. var homepage = "https://typestrong.org/ts-node";
  28181. var ava = {
  28182. files: [
  28183. "dist/test/*.spec.js"
  28184. ],
  28185. failWithoutAssertions: false,
  28186. timeout: "300s"
  28187. };
  28188. var devDependencies = {
  28189. "@microsoft/api-extractor": "^7.15.2",
  28190. "@swc/core": ">=1.2.50",
  28191. "@swc/wasm": ">=1.2.50",
  28192. "@types/chai": "^4.0.4",
  28193. "@types/diff": "^4.0.2",
  28194. "@types/lodash": "^4.14.151",
  28195. "@types/node": "13.13.5",
  28196. "@types/proxyquire": "^1.3.28",
  28197. "@types/react": "^16.0.2",
  28198. "@types/rimraf": "^3.0.0",
  28199. "@types/semver": "^7.1.0",
  28200. "@yarnpkg/fslib": "^2.4.0",
  28201. ava: "^3.15.0",
  28202. axios: "^0.21.1",
  28203. chai: "^4.0.1",
  28204. expect: "^27.0.2",
  28205. "get-stream": "^6.0.0",
  28206. lodash: "^4.17.15",
  28207. ntypescript: "^1.201507091536.1",
  28208. nyc: "^15.0.1",
  28209. prettier: "^2.2.1",
  28210. proxyquire: "^2.0.0",
  28211. react: "^16.14.0",
  28212. rimraf: "^3.0.0",
  28213. semver: "^7.1.3",
  28214. throat: "^6.0.1",
  28215. typedoc: "^0.20.28",
  28216. typescript: "4.3.5",
  28217. "typescript-json-schema": "^0.42.0",
  28218. "util.promisify": "^1.0.1"
  28219. };
  28220. var peerDependencies$1 = {
  28221. "@swc/core": ">=1.2.50",
  28222. "@swc/wasm": ">=1.2.50",
  28223. "@types/node": "*",
  28224. typescript: ">=2.7"
  28225. };
  28226. var peerDependenciesMeta = {
  28227. "@swc/core": {
  28228. optional: true
  28229. },
  28230. "@swc/wasm": {
  28231. optional: true
  28232. }
  28233. };
  28234. var dependencies = {
  28235. "@cspotcode/source-map-support": "0.6.1",
  28236. "@tsconfig/node10": "^1.0.7",
  28237. "@tsconfig/node12": "^1.0.7",
  28238. "@tsconfig/node14": "^1.0.0",
  28239. "@tsconfig/node16": "^1.0.2",
  28240. acorn: "^8.4.1",
  28241. "acorn-walk": "^8.1.1",
  28242. arg: "^4.1.0",
  28243. "create-require": "^1.1.0",
  28244. diff: "^4.0.1",
  28245. "make-error": "^1.1.1",
  28246. yn: "3.1.1"
  28247. };
  28248. var prettier = {
  28249. singleQuote: true
  28250. };
  28251. var require$$12 = {
  28252. name: name,
  28253. version: version$2,
  28254. description: description,
  28255. main: main$3,
  28256. exports: exports$1,
  28257. types: types$2,
  28258. bin: bin,
  28259. files: files,
  28260. scripts: scripts,
  28261. engines: engines,
  28262. repository: repository,
  28263. keywords: keywords$2,
  28264. author: author,
  28265. contributors: contributors,
  28266. license: license,
  28267. bugs: bugs,
  28268. homepage: homepage,
  28269. ava: ava,
  28270. devDependencies: devDependencies,
  28271. peerDependencies: peerDependencies$1,
  28272. peerDependenciesMeta: peerDependenciesMeta,
  28273. dependencies: dependencies,
  28274. prettier: prettier
  28275. };
  28276. (function (exports) {
  28277. var _a, _b;
  28278. Object.defineProperty(exports, "__esModule", { value: true });
  28279. exports.create = exports.register = exports.getExtensions = exports.TSError = exports.DEFAULTS = exports.VERSION = exports.debug = exports.INSPECT_CUSTOM = exports.env = exports.REGISTER_INSTANCE = exports.createRepl = void 0;
  28280. const path_1 = path__default;
  28281. const module_1 = require$$0__default$5;
  28282. const util = require$$0__default$3;
  28283. const url_1 = require$$0__default$7;
  28284. const sourceMapSupport$1 = sourceMapSupport.exports;
  28285. const make_error_1 = makeError$2.exports;
  28286. const util_1 = util$7;
  28287. const configuration_1 = configuration;
  28288. const module_type_classifier_1 = moduleTypeClassifier;
  28289. const resolver_functions_1 = resolverFunctions;
  28290. var repl_1 = repl;
  28291. Object.defineProperty(exports, "createRepl", { enumerable: true, get: function () { return repl_1.createRepl; } });
  28292. /**
  28293. * Does this version of node obey the package.json "type" field
  28294. * and throw ERR_REQUIRE_ESM when attempting to require() an ESM modules.
  28295. */
  28296. const engineSupportsPackageTypeField = parseInt(process.versions.node.split('.')[0], 10) >= 12;
  28297. function versionGte(version, requirement) {
  28298. const [major, minor, patch, extra] = version
  28299. .split(/[\.-]/)
  28300. .map((s) => parseInt(s, 10));
  28301. const [reqMajor, reqMinor, reqPatch] = requirement
  28302. .split('.')
  28303. .map((s) => parseInt(s, 10));
  28304. return (major > reqMajor ||
  28305. (major === reqMajor &&
  28306. (minor > reqMinor || (minor === reqMinor && patch >= reqPatch))));
  28307. }
  28308. /**
  28309. * Assert that script can be loaded as CommonJS when we attempt to require it.
  28310. * If it should be loaded as ESM, throw ERR_REQUIRE_ESM like node does.
  28311. *
  28312. * Loaded conditionally so we don't need to support older node versions
  28313. */
  28314. let assertScriptCanLoadAsCJS = engineSupportsPackageTypeField
  28315. ? nodeCjsLoaderUtils.assertScriptCanLoadAsCJSImpl
  28316. : () => {
  28317. /* noop */
  28318. };
  28319. /**
  28320. * Registered `ts-node` instance information.
  28321. */
  28322. exports.REGISTER_INSTANCE = Symbol.for('ts-node.register.instance');
  28323. /** @internal */
  28324. exports.env = process.env;
  28325. /**
  28326. * @internal
  28327. */
  28328. exports.INSPECT_CUSTOM = util.inspect.custom || 'inspect';
  28329. /**
  28330. * Debugging `ts-node`.
  28331. */
  28332. const shouldDebug = util_1.yn(exports.env.TS_NODE_DEBUG);
  28333. /** @internal */
  28334. exports.debug = shouldDebug
  28335. ? (...args) => console.log(`[ts-node ${new Date().toISOString()}]`, ...args)
  28336. : () => undefined;
  28337. const debugFn = shouldDebug
  28338. ? (key, fn) => {
  28339. let i = 0;
  28340. return (x) => {
  28341. exports.debug(key, x, ++i);
  28342. return fn(x);
  28343. };
  28344. }
  28345. : (_, fn) => fn;
  28346. /**
  28347. * Export the current version.
  28348. */
  28349. exports.VERSION = require$$12.version;
  28350. /**
  28351. * Default register options, including values specified via environment
  28352. * variables.
  28353. * @internal
  28354. */
  28355. exports.DEFAULTS = {
  28356. cwd: (_a = exports.env.TS_NODE_CWD) !== null && _a !== void 0 ? _a : exports.env.TS_NODE_DIR,
  28357. emit: util_1.yn(exports.env.TS_NODE_EMIT),
  28358. scope: util_1.yn(exports.env.TS_NODE_SCOPE),
  28359. scopeDir: exports.env.TS_NODE_SCOPE_DIR,
  28360. files: util_1.yn(exports.env.TS_NODE_FILES),
  28361. pretty: util_1.yn(exports.env.TS_NODE_PRETTY),
  28362. compiler: exports.env.TS_NODE_COMPILER,
  28363. compilerOptions: util_1.parse(exports.env.TS_NODE_COMPILER_OPTIONS),
  28364. ignore: util_1.split(exports.env.TS_NODE_IGNORE),
  28365. project: exports.env.TS_NODE_PROJECT,
  28366. skipProject: util_1.yn(exports.env.TS_NODE_SKIP_PROJECT),
  28367. skipIgnore: util_1.yn(exports.env.TS_NODE_SKIP_IGNORE),
  28368. preferTsExts: util_1.yn(exports.env.TS_NODE_PREFER_TS_EXTS),
  28369. ignoreDiagnostics: util_1.split(exports.env.TS_NODE_IGNORE_DIAGNOSTICS),
  28370. transpileOnly: util_1.yn(exports.env.TS_NODE_TRANSPILE_ONLY),
  28371. typeCheck: util_1.yn(exports.env.TS_NODE_TYPE_CHECK),
  28372. compilerHost: util_1.yn(exports.env.TS_NODE_COMPILER_HOST),
  28373. logError: util_1.yn(exports.env.TS_NODE_LOG_ERROR),
  28374. experimentalEsmLoader: false,
  28375. experimentalReplAwait: (_b = util_1.yn(exports.env.TS_NODE_EXPERIMENTAL_REPL_AWAIT)) !== null && _b !== void 0 ? _b : undefined,
  28376. };
  28377. /**
  28378. * TypeScript diagnostics error.
  28379. */
  28380. class TSError extends make_error_1.BaseError {
  28381. constructor(diagnosticText, diagnosticCodes) {
  28382. super(`⨯ Unable to compile TypeScript:\n${diagnosticText}`);
  28383. this.diagnosticText = diagnosticText;
  28384. this.diagnosticCodes = diagnosticCodes;
  28385. this.name = 'TSError';
  28386. }
  28387. /**
  28388. * @internal
  28389. */
  28390. [exports.INSPECT_CUSTOM]() {
  28391. return this.diagnosticText;
  28392. }
  28393. }
  28394. exports.TSError = TSError;
  28395. /** @internal */
  28396. function getExtensions(config) {
  28397. const tsExtensions = ['.ts'];
  28398. const jsExtensions = [];
  28399. // Enable additional extensions when JSX or `allowJs` is enabled.
  28400. if (config.options.jsx)
  28401. tsExtensions.push('.tsx');
  28402. if (config.options.allowJs)
  28403. jsExtensions.push('.js');
  28404. if (config.options.jsx && config.options.allowJs)
  28405. jsExtensions.push('.jsx');
  28406. return { tsExtensions, jsExtensions };
  28407. }
  28408. exports.getExtensions = getExtensions;
  28409. /**
  28410. * Register TypeScript compiler instance onto node.js
  28411. */
  28412. function register(opts = {}) {
  28413. const originalJsHandler = commonjsRequire.extensions['.js'];
  28414. const service = create(opts);
  28415. const { tsExtensions, jsExtensions } = getExtensions(service.config);
  28416. const extensions = [...tsExtensions, ...jsExtensions];
  28417. // Expose registered instance globally.
  28418. process[exports.REGISTER_INSTANCE] = service;
  28419. // Register the extensions.
  28420. registerExtensions(service.options.preferTsExts, extensions, service, originalJsHandler);
  28421. // Require specified modules before start-up.
  28422. module_1.Module._preloadModules(service.options.require);
  28423. return service;
  28424. }
  28425. exports.register = register;
  28426. /**
  28427. * Create TypeScript compiler instance.
  28428. */
  28429. function create(rawOptions = {}) {
  28430. var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
  28431. const cwd = path_1.resolve((_c = (_b = (_a = rawOptions.cwd) !== null && _a !== void 0 ? _a : rawOptions.dir) !== null && _b !== void 0 ? _b : exports.DEFAULTS.cwd) !== null && _c !== void 0 ? _c : process.cwd());
  28432. const compilerName = (_d = rawOptions.compiler) !== null && _d !== void 0 ? _d : exports.DEFAULTS.compiler;
  28433. /**
  28434. * Load the typescript compiler. It is required to load the tsconfig but might
  28435. * be changed by the tsconfig, so we have to do this twice.
  28436. */
  28437. function loadCompiler(name, relativeToPath) {
  28438. const compiler = require.resolve(name || 'typescript', {
  28439. paths: [relativeToPath, __dirname],
  28440. });
  28441. const ts = commonjsRequire(compiler);
  28442. return { compiler, ts };
  28443. }
  28444. // Compute minimum options to read the config file.
  28445. let { compiler, ts } = loadCompiler(compilerName, (_f = (_e = rawOptions.projectSearchDir) !== null && _e !== void 0 ? _e : rawOptions.project) !== null && _f !== void 0 ? _f : cwd);
  28446. // Read config file and merge new options between env and CLI options.
  28447. const { configFilePath, config, tsNodeOptionsFromTsconfig, optionBasePaths, } = configuration_1.readConfig(cwd, ts, rawOptions);
  28448. const options = util_1.assign({}, exports.DEFAULTS, tsNodeOptionsFromTsconfig || {}, { optionBasePaths }, rawOptions);
  28449. options.require = [
  28450. ...(tsNodeOptionsFromTsconfig.require || []),
  28451. ...(rawOptions.require || []),
  28452. ];
  28453. // Experimental REPL await is not compatible targets lower than ES2018
  28454. const targetSupportsTla = config.options.target >= ts.ScriptTarget.ES2018;
  28455. if (options.experimentalReplAwait === true && !targetSupportsTla) {
  28456. throw new Error('Experimental REPL await is not compatible with targets lower than ES2018');
  28457. }
  28458. // Top-level await was added in TS 3.8
  28459. const tsVersionSupportsTla = versionGte(ts.version, '3.8.0');
  28460. if (options.experimentalReplAwait === true && !tsVersionSupportsTla) {
  28461. throw new Error('Experimental REPL await is not compatible with TypeScript versions older than 3.8');
  28462. }
  28463. const shouldReplAwait = options.experimentalReplAwait !== false &&
  28464. tsVersionSupportsTla &&
  28465. targetSupportsTla;
  28466. // Re-load the compiler in case it has changed.
  28467. // Compiler is loaded relative to tsconfig.json, so tsconfig discovery may cause us to load a
  28468. // different compiler than we did above, even if the name has not changed.
  28469. if (configFilePath) {
  28470. ({ compiler, ts } = loadCompiler(options.compiler, configFilePath));
  28471. }
  28472. const readFile = options.readFile || ts.sys.readFile;
  28473. const fileExists = options.fileExists || ts.sys.fileExists;
  28474. // typeCheck can override transpileOnly, useful for CLI flag to override config file
  28475. const transpileOnly = options.transpileOnly === true && options.typeCheck !== true;
  28476. const transformers = options.transformers || undefined;
  28477. const diagnosticFilters = [
  28478. {
  28479. appliesToAllFiles: true,
  28480. filenamesAbsolute: [],
  28481. diagnosticsIgnored: [
  28482. 6059,
  28483. 18002,
  28484. 18003,
  28485. ...(options.ignoreDiagnostics || []),
  28486. ].map(Number),
  28487. },
  28488. ];
  28489. const configDiagnosticList = filterDiagnostics(config.errors, diagnosticFilters);
  28490. const outputCache = new Map();
  28491. const configFileDirname = configFilePath ? path_1.dirname(configFilePath) : null;
  28492. const scopeDir = (_j = (_h = (_g = options.scopeDir) !== null && _g !== void 0 ? _g : config.options.rootDir) !== null && _h !== void 0 ? _h : configFileDirname) !== null && _j !== void 0 ? _j : cwd;
  28493. const ignoreBaseDir = configFileDirname !== null && configFileDirname !== void 0 ? configFileDirname : cwd;
  28494. const isScoped = options.scope
  28495. ? (fileName) => path_1.relative(scopeDir, fileName).charAt(0) !== '.'
  28496. : () => true;
  28497. const shouldIgnore = createIgnore(ignoreBaseDir, options.skipIgnore
  28498. ? []
  28499. : (options.ignore || ['(?:^|/)node_modules/']).map((str) => new RegExp(str)));
  28500. const diagnosticHost = {
  28501. getNewLine: () => ts.sys.newLine,
  28502. getCurrentDirectory: () => cwd,
  28503. getCanonicalFileName: ts.sys.useCaseSensitiveFileNames
  28504. ? (x) => x
  28505. : (x) => x.toLowerCase(),
  28506. };
  28507. if (options.transpileOnly && typeof transformers === 'function') {
  28508. throw new TypeError('Transformers function is unavailable in "--transpile-only"');
  28509. }
  28510. let customTranspiler = undefined;
  28511. if (options.transpiler) {
  28512. if (!transpileOnly)
  28513. throw new Error('Custom transpiler can only be used when transpileOnly is enabled.');
  28514. const transpilerName = typeof options.transpiler === 'string'
  28515. ? options.transpiler
  28516. : options.transpiler[0];
  28517. const transpilerOptions = typeof options.transpiler === 'string' ? {} : (_k = options.transpiler[1]) !== null && _k !== void 0 ? _k : {};
  28518. // TODO mimic fixed resolution logic from loadCompiler main
  28519. // TODO refactor into a more generic "resolve dep relative to project" helper
  28520. const transpilerPath = require.resolve(transpilerName, {
  28521. paths: [cwd, __dirname],
  28522. });
  28523. const transpilerFactory = commonjsRequire(transpilerPath).create;
  28524. customTranspiler = transpilerFactory(Object.assign({ service: { options, config } }, transpilerOptions));
  28525. }
  28526. // Install source map support and read from memory cache.
  28527. sourceMapSupport$1.install({
  28528. environment: 'node',
  28529. retrieveFile(pathOrUrl) {
  28530. var _a;
  28531. let path = pathOrUrl;
  28532. // If it's a file URL, convert to local path
  28533. // Note: fileURLToPath does not exist on early node v10
  28534. // I could not find a way to handle non-URLs except to swallow an error
  28535. if (options.experimentalEsmLoader && path.startsWith('file://')) {
  28536. try {
  28537. path = url_1.fileURLToPath(path);
  28538. }
  28539. catch (e) {
  28540. /* swallow error */
  28541. }
  28542. }
  28543. path = util_1.normalizeSlashes(path);
  28544. return ((_a = outputCache.get(path)) === null || _a === void 0 ? void 0 : _a.content) || '';
  28545. },
  28546. });
  28547. const shouldHavePrettyErrors = options.pretty === undefined ? process.stdout.isTTY : options.pretty;
  28548. const formatDiagnostics = shouldHavePrettyErrors
  28549. ? ts.formatDiagnosticsWithColorAndContext || ts.formatDiagnostics
  28550. : ts.formatDiagnostics;
  28551. function createTSError(diagnostics) {
  28552. const diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
  28553. const diagnosticCodes = diagnostics.map((x) => x.code);
  28554. return new TSError(diagnosticText, diagnosticCodes);
  28555. }
  28556. function reportTSError(configDiagnosticList) {
  28557. const error = createTSError(configDiagnosticList);
  28558. if (options.logError) {
  28559. // Print error in red color and continue execution.
  28560. console.error('\x1b[31m%s\x1b[0m', error);
  28561. }
  28562. else {
  28563. // Throw error and exit the script.
  28564. throw error;
  28565. }
  28566. }
  28567. // Render the configuration errors.
  28568. if (configDiagnosticList.length)
  28569. reportTSError(configDiagnosticList);
  28570. /**
  28571. * Get the extension for a transpiled file.
  28572. */
  28573. const getExtension = config.options.jsx === ts.JsxEmit.Preserve
  28574. ? (path) => (/\.[tj]sx$/.test(path) ? '.jsx' : '.js')
  28575. : (_) => '.js';
  28576. /**
  28577. * Create the basic required function using transpile mode.
  28578. */
  28579. let getOutput;
  28580. let getTypeInfo;
  28581. const getCanonicalFileName = ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames);
  28582. const moduleTypeClassifier = module_type_classifier_1.createModuleTypeClassifier({
  28583. basePath: (_l = options.optionBasePaths) === null || _l === void 0 ? void 0 : _l.moduleTypes,
  28584. patterns: options.moduleTypes,
  28585. });
  28586. // Use full language services when the fast option is disabled.
  28587. if (!transpileOnly) {
  28588. const fileContents = new Map();
  28589. const rootFileNames = new Set(config.fileNames);
  28590. const cachedReadFile = util_1.cachedLookup(debugFn('readFile', readFile));
  28591. // Use language services by default (TODO: invert next major version).
  28592. if (!options.compilerHost) {
  28593. let projectVersion = 1;
  28594. const fileVersions = new Map(Array.from(rootFileNames).map((fileName) => [fileName, 0]));
  28595. const getCustomTransformers = () => {
  28596. if (typeof transformers === 'function') {
  28597. const program = service.getProgram();
  28598. return program ? transformers(program) : undefined;
  28599. }
  28600. return transformers;
  28601. };
  28602. // Create the compiler host for type checking.
  28603. const serviceHost = {
  28604. getProjectVersion: () => String(projectVersion),
  28605. getScriptFileNames: () => Array.from(rootFileNames),
  28606. getScriptVersion: (fileName) => {
  28607. const version = fileVersions.get(fileName);
  28608. return version ? version.toString() : '';
  28609. },
  28610. getScriptSnapshot(fileName) {
  28611. // TODO ordering of this with getScriptVersion? Should they sync up?
  28612. let contents = fileContents.get(fileName);
  28613. // Read contents into TypeScript memory cache.
  28614. if (contents === undefined) {
  28615. contents = cachedReadFile(fileName);
  28616. if (contents === undefined)
  28617. return;
  28618. fileVersions.set(fileName, 1);
  28619. fileContents.set(fileName, contents);
  28620. projectVersion++;
  28621. }
  28622. return ts.ScriptSnapshot.fromString(contents);
  28623. },
  28624. readFile: cachedReadFile,
  28625. readDirectory: ts.sys.readDirectory,
  28626. getDirectories: util_1.cachedLookup(debugFn('getDirectories', ts.sys.getDirectories)),
  28627. fileExists: util_1.cachedLookup(debugFn('fileExists', fileExists)),
  28628. directoryExists: util_1.cachedLookup(debugFn('directoryExists', ts.sys.directoryExists)),
  28629. realpath: ts.sys.realpath
  28630. ? util_1.cachedLookup(debugFn('realpath', ts.sys.realpath))
  28631. : undefined,
  28632. getNewLine: () => ts.sys.newLine,
  28633. useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
  28634. getCurrentDirectory: () => cwd,
  28635. getCompilationSettings: () => config.options,
  28636. getDefaultLibFileName: () => ts.getDefaultLibFilePath(config.options),
  28637. getCustomTransformers: getCustomTransformers,
  28638. };
  28639. const { resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives, isFileKnownToBeInternal, markBucketOfFilenameInternal, } = resolver_functions_1.createResolverFunctions({
  28640. serviceHost,
  28641. getCanonicalFileName,
  28642. ts,
  28643. cwd,
  28644. config,
  28645. configFilePath,
  28646. });
  28647. serviceHost.resolveModuleNames = resolveModuleNames;
  28648. serviceHost.getResolvedModuleWithFailedLookupLocationsFromCache = getResolvedModuleWithFailedLookupLocationsFromCache;
  28649. serviceHost.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
  28650. const registry = ts.createDocumentRegistry(ts.sys.useCaseSensitiveFileNames, cwd);
  28651. const service = ts.createLanguageService(serviceHost, registry);
  28652. const updateMemoryCache = (contents, fileName) => {
  28653. // Add to `rootFiles` as necessary, either to make TS include a file it has not seen,
  28654. // or to trigger a re-classification of files from external to internal.
  28655. if (!rootFileNames.has(fileName) &&
  28656. !isFileKnownToBeInternal(fileName)) {
  28657. markBucketOfFilenameInternal(fileName);
  28658. rootFileNames.add(fileName);
  28659. // Increment project version for every change to rootFileNames.
  28660. projectVersion++;
  28661. }
  28662. const previousVersion = fileVersions.get(fileName) || 0;
  28663. const previousContents = fileContents.get(fileName);
  28664. // Avoid incrementing cache when nothing has changed.
  28665. if (contents !== previousContents) {
  28666. fileVersions.set(fileName, previousVersion + 1);
  28667. fileContents.set(fileName, contents);
  28668. // Increment project version for every file change.
  28669. projectVersion++;
  28670. }
  28671. };
  28672. let previousProgram = undefined;
  28673. getOutput = (code, fileName) => {
  28674. updateMemoryCache(code, fileName);
  28675. const programBefore = service.getProgram();
  28676. if (programBefore !== previousProgram) {
  28677. exports.debug(`compiler rebuilt Program instance when getting output for ${fileName}`);
  28678. }
  28679. const output = service.getEmitOutput(fileName);
  28680. // Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
  28681. const diagnostics = service
  28682. .getSemanticDiagnostics(fileName)
  28683. .concat(service.getSyntacticDiagnostics(fileName));
  28684. const programAfter = service.getProgram();
  28685. exports.debug('invariant: Is service.getProject() identical before and after getting emit output and diagnostics? (should always be true) ', programBefore === programAfter);
  28686. previousProgram = programAfter;
  28687. const diagnosticList = filterDiagnostics(diagnostics, diagnosticFilters);
  28688. if (diagnosticList.length)
  28689. reportTSError(diagnosticList);
  28690. if (output.emitSkipped) {
  28691. throw new TypeError(`${path_1.relative(cwd, fileName)}: Emit skipped`);
  28692. }
  28693. // Throw an error when requiring `.d.ts` files.
  28694. if (output.outputFiles.length === 0) {
  28695. throw new TypeError(`Unable to require file: ${path_1.relative(cwd, fileName)}\n` +
  28696. 'This is usually the result of a faulty configuration or import. ' +
  28697. 'Make sure there is a `.js`, `.json` or other executable extension with ' +
  28698. 'loader attached before `ts-node` available.');
  28699. }
  28700. return [output.outputFiles[1].text, output.outputFiles[0].text];
  28701. };
  28702. getTypeInfo = (code, fileName, position) => {
  28703. updateMemoryCache(code, fileName);
  28704. const info = service.getQuickInfoAtPosition(fileName, position);
  28705. const name = ts.displayPartsToString(info ? info.displayParts : []);
  28706. const comment = ts.displayPartsToString(info ? info.documentation : []);
  28707. return { name, comment };
  28708. };
  28709. }
  28710. else {
  28711. const sys = Object.assign(Object.assign(Object.assign({}, ts.sys), diagnosticHost), { readFile: (fileName) => {
  28712. const cacheContents = fileContents.get(fileName);
  28713. if (cacheContents !== undefined)
  28714. return cacheContents;
  28715. const contents = cachedReadFile(fileName);
  28716. if (contents)
  28717. fileContents.set(fileName, contents);
  28718. return contents;
  28719. }, readDirectory: ts.sys.readDirectory, getDirectories: util_1.cachedLookup(debugFn('getDirectories', ts.sys.getDirectories)), fileExists: util_1.cachedLookup(debugFn('fileExists', fileExists)), directoryExists: util_1.cachedLookup(debugFn('directoryExists', ts.sys.directoryExists)), resolvePath: util_1.cachedLookup(debugFn('resolvePath', ts.sys.resolvePath)), realpath: ts.sys.realpath
  28720. ? util_1.cachedLookup(debugFn('realpath', ts.sys.realpath))
  28721. : undefined });
  28722. const host = ts.createIncrementalCompilerHost
  28723. ? ts.createIncrementalCompilerHost(config.options, sys)
  28724. : Object.assign(Object.assign({}, sys), { getSourceFile: (fileName, languageVersion) => {
  28725. const contents = sys.readFile(fileName);
  28726. if (contents === undefined)
  28727. return;
  28728. return ts.createSourceFile(fileName, contents, languageVersion);
  28729. }, getDefaultLibLocation: () => util_1.normalizeSlashes(path_1.dirname(compiler)), getDefaultLibFileName: () => util_1.normalizeSlashes(path_1.join(path_1.dirname(compiler), ts.getDefaultLibFileName(config.options))), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames });
  28730. const { resolveModuleNames, resolveTypeReferenceDirectives, isFileKnownToBeInternal, markBucketOfFilenameInternal, } = resolver_functions_1.createResolverFunctions({
  28731. serviceHost: host,
  28732. cwd,
  28733. configFilePath,
  28734. config,
  28735. ts,
  28736. getCanonicalFileName,
  28737. });
  28738. host.resolveModuleNames = resolveModuleNames;
  28739. host.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
  28740. // Fallback for older TypeScript releases without incremental API.
  28741. let builderProgram = ts.createIncrementalProgram
  28742. ? ts.createIncrementalProgram({
  28743. rootNames: Array.from(rootFileNames),
  28744. options: config.options,
  28745. host: host,
  28746. configFileParsingDiagnostics: config.errors,
  28747. projectReferences: config.projectReferences,
  28748. })
  28749. : ts.createEmitAndSemanticDiagnosticsBuilderProgram(Array.from(rootFileNames), config.options, host, undefined, config.errors, config.projectReferences);
  28750. // Read and cache custom transformers.
  28751. const customTransformers = typeof transformers === 'function'
  28752. ? transformers(builderProgram.getProgram())
  28753. : transformers;
  28754. // Set the file contents into cache manually.
  28755. const updateMemoryCache = (contents, fileName) => {
  28756. const previousContents = fileContents.get(fileName);
  28757. const contentsChanged = previousContents !== contents;
  28758. if (contentsChanged) {
  28759. fileContents.set(fileName, contents);
  28760. }
  28761. // Add to `rootFiles` when discovered by compiler for the first time.
  28762. let addedToRootFileNames = false;
  28763. if (!rootFileNames.has(fileName) &&
  28764. !isFileKnownToBeInternal(fileName)) {
  28765. markBucketOfFilenameInternal(fileName);
  28766. rootFileNames.add(fileName);
  28767. addedToRootFileNames = true;
  28768. }
  28769. // Update program when file changes.
  28770. if (addedToRootFileNames || contentsChanged) {
  28771. builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(Array.from(rootFileNames), config.options, host, builderProgram, config.errors, config.projectReferences);
  28772. }
  28773. };
  28774. getOutput = (code, fileName) => {
  28775. const output = ['', ''];
  28776. updateMemoryCache(code, fileName);
  28777. const sourceFile = builderProgram.getSourceFile(fileName);
  28778. if (!sourceFile)
  28779. throw new TypeError(`Unable to read file: ${fileName}`);
  28780. const program = builderProgram.getProgram();
  28781. const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);
  28782. const diagnosticList = filterDiagnostics(diagnostics, diagnosticFilters);
  28783. if (diagnosticList.length)
  28784. reportTSError(diagnosticList);
  28785. const result = builderProgram.emit(sourceFile, (path, file, writeByteOrderMark) => {
  28786. if (path.endsWith('.map')) {
  28787. output[1] = file;
  28788. }
  28789. else {
  28790. output[0] = file;
  28791. }
  28792. if (options.emit)
  28793. sys.writeFile(path, file, writeByteOrderMark);
  28794. }, undefined, undefined, customTransformers);
  28795. if (result.emitSkipped) {
  28796. throw new TypeError(`${path_1.relative(cwd, fileName)}: Emit skipped`);
  28797. }
  28798. // Throw an error when requiring files that cannot be compiled.
  28799. if (output[0] === '') {
  28800. if (program.isSourceFileFromExternalLibrary(sourceFile)) {
  28801. throw new TypeError(`Unable to compile file from external library: ${path_1.relative(cwd, fileName)}`);
  28802. }
  28803. throw new TypeError(`Unable to require file: ${path_1.relative(cwd, fileName)}\n` +
  28804. 'This is usually the result of a faulty configuration or import. ' +
  28805. 'Make sure there is a `.js`, `.json` or other executable extension with ' +
  28806. 'loader attached before `ts-node` available.');
  28807. }
  28808. return output;
  28809. };
  28810. getTypeInfo = (code, fileName, position) => {
  28811. updateMemoryCache(code, fileName);
  28812. const sourceFile = builderProgram.getSourceFile(fileName);
  28813. if (!sourceFile)
  28814. throw new TypeError(`Unable to read file: ${fileName}`);
  28815. const node = getTokenAtPosition(ts, sourceFile, position);
  28816. const checker = builderProgram.getProgram().getTypeChecker();
  28817. const symbol = checker.getSymbolAtLocation(node);
  28818. if (!symbol)
  28819. return { name: '', comment: '' };
  28820. const type = checker.getTypeOfSymbolAtLocation(symbol, node);
  28821. const signatures = [
  28822. ...type.getConstructSignatures(),
  28823. ...type.getCallSignatures(),
  28824. ];
  28825. return {
  28826. name: signatures.length
  28827. ? signatures.map((x) => checker.signatureToString(x)).join('\n')
  28828. : checker.typeToString(type),
  28829. comment: ts.displayPartsToString(symbol ? symbol.getDocumentationComment(checker) : []),
  28830. };
  28831. };
  28832. // Write `.tsbuildinfo` when `--build` is enabled.
  28833. if (options.emit && config.options.incremental) {
  28834. process.on('exit', () => {
  28835. // Emits `.tsbuildinfo` to filesystem.
  28836. builderProgram.getProgram().emitBuildInfo();
  28837. });
  28838. }
  28839. }
  28840. }
  28841. else {
  28842. getOutput = createTranspileOnlyGetOutputFunction();
  28843. getTypeInfo = () => {
  28844. throw new TypeError('Type information is unavailable in "--transpile-only"');
  28845. };
  28846. }
  28847. function createTranspileOnlyGetOutputFunction(overrideModuleType) {
  28848. const compilerOptions = Object.assign({}, config.options);
  28849. if (overrideModuleType !== undefined)
  28850. compilerOptions.module = overrideModuleType;
  28851. return (code, fileName) => {
  28852. let result;
  28853. if (customTranspiler) {
  28854. result = customTranspiler.transpile(code, {
  28855. fileName,
  28856. });
  28857. }
  28858. else {
  28859. result = ts.transpileModule(code, {
  28860. fileName,
  28861. compilerOptions,
  28862. reportDiagnostics: true,
  28863. transformers: transformers,
  28864. });
  28865. }
  28866. const diagnosticList = filterDiagnostics(result.diagnostics || [], diagnosticFilters);
  28867. if (diagnosticList.length)
  28868. reportTSError(diagnosticList);
  28869. return [result.outputText, result.sourceMapText];
  28870. };
  28871. }
  28872. // When either is undefined, it means normal `getOutput` should be used
  28873. const getOutputForceCommonJS = config.options.module === ts.ModuleKind.CommonJS
  28874. ? undefined
  28875. : createTranspileOnlyGetOutputFunction(ts.ModuleKind.CommonJS);
  28876. const getOutputForceESM = config.options.module === ts.ModuleKind.ES2015 ||
  28877. config.options.module === ts.ModuleKind.ES2020 ||
  28878. config.options.module === ts.ModuleKind.ESNext
  28879. ? undefined
  28880. : createTranspileOnlyGetOutputFunction(ts.ModuleKind.ES2020 || ts.ModuleKind.ES2015);
  28881. // Create a simple TypeScript compiler proxy.
  28882. function compile(code, fileName, lineOffset = 0) {
  28883. const normalizedFileName = util_1.normalizeSlashes(fileName);
  28884. const classification = moduleTypeClassifier.classifyModule(normalizedFileName);
  28885. // Must always call normal getOutput to throw typechecking errors
  28886. let [value, sourceMap] = getOutput(code, normalizedFileName);
  28887. // If module classification contradicts the above, call the relevant transpiler
  28888. if (classification.moduleType === 'cjs' && getOutputForceCommonJS) {
  28889. [value, sourceMap] = getOutputForceCommonJS(code, normalizedFileName);
  28890. }
  28891. else if (classification.moduleType === 'esm' && getOutputForceESM) {
  28892. [value, sourceMap] = getOutputForceESM(code, normalizedFileName);
  28893. }
  28894. const output = updateOutput(value, normalizedFileName, sourceMap, getExtension);
  28895. outputCache.set(normalizedFileName, { content: output });
  28896. return output;
  28897. }
  28898. let active = true;
  28899. const enabled = (enabled) => enabled === undefined ? active : (active = !!enabled);
  28900. const extensions = getExtensions(config);
  28901. const ignored = (fileName) => {
  28902. if (!active)
  28903. return true;
  28904. const ext = path_1.extname(fileName);
  28905. if (extensions.tsExtensions.includes(ext) ||
  28906. extensions.jsExtensions.includes(ext)) {
  28907. return !isScoped(fileName) || shouldIgnore(fileName);
  28908. }
  28909. return true;
  28910. };
  28911. function addDiagnosticFilter(filter) {
  28912. diagnosticFilters.push(Object.assign(Object.assign({}, filter), { filenamesAbsolute: filter.filenamesAbsolute.map((f) => util_1.normalizeSlashes(f)) }));
  28913. }
  28914. return {
  28915. ts,
  28916. config,
  28917. compile,
  28918. getTypeInfo,
  28919. ignored,
  28920. enabled,
  28921. options,
  28922. configFilePath,
  28923. moduleTypeClassifier,
  28924. shouldReplAwait,
  28925. addDiagnosticFilter,
  28926. };
  28927. }
  28928. exports.create = create;
  28929. /**
  28930. * Check if the filename should be ignored.
  28931. */
  28932. function createIgnore(ignoreBaseDir, ignore) {
  28933. return (fileName) => {
  28934. const relname = path_1.relative(ignoreBaseDir, fileName);
  28935. const path = util_1.normalizeSlashes(relname);
  28936. return ignore.some((x) => x.test(path));
  28937. };
  28938. }
  28939. /**
  28940. * "Refreshes" an extension on `require.extensions`.
  28941. *
  28942. * @param {string} ext
  28943. */
  28944. function reorderRequireExtension(ext) {
  28945. const old = commonjsRequire.extensions[ext];
  28946. delete commonjsRequire.extensions[ext];
  28947. commonjsRequire.extensions[ext] = old;
  28948. }
  28949. /**
  28950. * Register the extensions to support when importing files.
  28951. */
  28952. function registerExtensions(preferTsExts, extensions, service, originalJsHandler) {
  28953. // Register new extensions.
  28954. for (const ext of extensions) {
  28955. registerExtension(ext, service, originalJsHandler);
  28956. }
  28957. if (preferTsExts) {
  28958. const preferredExtensions = new Set([
  28959. ...extensions,
  28960. ...Object.keys(commonjsRequire.extensions),
  28961. ]);
  28962. for (const ext of preferredExtensions)
  28963. reorderRequireExtension(ext);
  28964. }
  28965. }
  28966. /**
  28967. * Register the extension for node.
  28968. */
  28969. function registerExtension(ext, service, originalHandler) {
  28970. const old = commonjsRequire.extensions[ext] || originalHandler;
  28971. commonjsRequire.extensions[ext] = function (m, filename) {
  28972. if (service.ignored(filename))
  28973. return old(m, filename);
  28974. assertScriptCanLoadAsCJS(service, m, filename);
  28975. const _compile = m._compile;
  28976. m._compile = function (code, fileName) {
  28977. exports.debug('module._compile', fileName);
  28978. const result = service.compile(code, fileName);
  28979. return _compile.call(this, result, fileName);
  28980. };
  28981. return old(m, filename);
  28982. };
  28983. }
  28984. /**
  28985. * Update the output remapping the source map.
  28986. */
  28987. function updateOutput(outputText, fileName, sourceMap, getExtension) {
  28988. const base64Map = Buffer.from(updateSourceMap(sourceMap, fileName), 'utf8').toString('base64');
  28989. const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
  28990. // Expected form: `//# sourceMappingURL=foo bar.js.map` or `//# sourceMappingURL=foo%20bar.js.map` for input file "foo bar.tsx"
  28991. // Percent-encoding behavior added in TS 4.1.1: https://github.com/microsoft/TypeScript/issues/40951
  28992. const prefix = '//# sourceMappingURL=';
  28993. const prefixLength = prefix.length;
  28994. const baseName = /*foo.tsx*/ path_1.basename(fileName);
  28995. const extName = /*.tsx*/ path_1.extname(fileName);
  28996. const extension = /*.js*/ getExtension(fileName);
  28997. const sourcemapFilename = baseName.slice(0, -extName.length) + extension + '.map';
  28998. const sourceMapLengthWithoutPercentEncoding = prefixLength + sourcemapFilename.length;
  28999. /*
  29000. * Only rewrite if existing directive exists at the location we expect, to support:
  29001. * a) compilers that do not append a sourcemap directive
  29002. * b) situations where we did the math wrong
  29003. * Not ideal, but appending our sourcemap *after* a pre-existing sourcemap still overrides, so the end-user is happy.
  29004. */
  29005. if (outputText.substr(-sourceMapLengthWithoutPercentEncoding, prefixLength) ===
  29006. prefix) {
  29007. return (outputText.slice(0, -sourceMapLengthWithoutPercentEncoding) +
  29008. sourceMapContent);
  29009. }
  29010. // If anyone asks why we're not using URL, the URL equivalent is: `u = new URL('http://d'); u.pathname = "/" + sourcemapFilename; return u.pathname.slice(1);
  29011. const sourceMapLengthWithPercentEncoding = prefixLength + encodeURI(sourcemapFilename).length;
  29012. if (outputText.substr(-sourceMapLengthWithPercentEncoding, prefixLength) ===
  29013. prefix) {
  29014. return (outputText.slice(0, -sourceMapLengthWithPercentEncoding) +
  29015. sourceMapContent);
  29016. }
  29017. return `${outputText}\n${sourceMapContent}`;
  29018. }
  29019. /**
  29020. * Update the source map contents for improved output.
  29021. */
  29022. function updateSourceMap(sourceMapText, fileName) {
  29023. const sourceMap = JSON.parse(sourceMapText);
  29024. sourceMap.file = fileName;
  29025. sourceMap.sources = [fileName];
  29026. delete sourceMap.sourceRoot;
  29027. return JSON.stringify(sourceMap);
  29028. }
  29029. /**
  29030. * Filter diagnostics.
  29031. */
  29032. function filterDiagnostics(diagnostics, filters) {
  29033. return diagnostics.filter((d) => filters.every((f) => {
  29034. var _a;
  29035. return (!f.appliesToAllFiles &&
  29036. f.filenamesAbsolute.indexOf((_a = d.file) === null || _a === void 0 ? void 0 : _a.fileName) === -1) ||
  29037. f.diagnosticsIgnored.indexOf(d.code) === -1;
  29038. }));
  29039. }
  29040. /**
  29041. * Get token at file position.
  29042. *
  29043. * Reference: https://github.com/microsoft/TypeScript/blob/fcd9334f57d85b73dd66ad2d21c02e84822f4841/src/services/utilities.ts#L705-L731
  29044. */
  29045. function getTokenAtPosition(ts, sourceFile, position) {
  29046. let current = sourceFile;
  29047. outer: while (true) {
  29048. for (const child of current.getChildren(sourceFile)) {
  29049. const start = child.getFullStart();
  29050. if (start > position)
  29051. break;
  29052. const end = child.getEnd();
  29053. if (position <= end) {
  29054. current = child;
  29055. continue outer;
  29056. }
  29057. }
  29058. return current;
  29059. }
  29060. }
  29061. }(dist$1));
  29062. const resolve$2 = path__default.resolve;
  29063. const config$1 = dist$3;
  29064. const yaml = yaml$1;
  29065. const loadOptions = options_1;
  29066. const loadPlugins = plugins_1;
  29067. /* istanbul ignore next */
  29068. const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
  29069. /**
  29070. * Process the result from cosmiconfig
  29071. *
  29072. * @param {Object} ctx Config Context
  29073. * @param {Object} result Cosmiconfig result
  29074. *
  29075. * @return {Object} PostCSS Config
  29076. */
  29077. const processResult = (ctx, result) => {
  29078. const file = result.filepath || '';
  29079. let config = interopRequireDefault(result.config).default || {};
  29080. if (typeof config === 'function') {
  29081. config = config(ctx);
  29082. } else {
  29083. config = Object.assign({}, config, ctx);
  29084. }
  29085. if (!config.plugins) {
  29086. config.plugins = [];
  29087. }
  29088. return {
  29089. plugins: loadPlugins(config, file),
  29090. options: loadOptions(config, file),
  29091. file: file
  29092. }
  29093. };
  29094. /**
  29095. * Builds the Config Context
  29096. *
  29097. * @param {Object} ctx Config Context
  29098. *
  29099. * @return {Object} Config Context
  29100. */
  29101. const createContext = (ctx) => {
  29102. /**
  29103. * @type {Object}
  29104. *
  29105. * @prop {String} cwd=process.cwd() Config search start location
  29106. * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined`
  29107. */
  29108. ctx = Object.assign({
  29109. cwd: process.cwd(),
  29110. env: process.env.NODE_ENV
  29111. }, ctx);
  29112. if (!ctx.env) {
  29113. process.env.NODE_ENV = 'development';
  29114. }
  29115. return ctx
  29116. };
  29117. const addTypeScriptLoader = (options = {}, loader) => {
  29118. const moduleName = 'postcss';
  29119. return {
  29120. ...options,
  29121. searchPlaces: [
  29122. ...(options.searchPlaces || []),
  29123. 'package.json',
  29124. `.${moduleName}rc`,
  29125. `.${moduleName}rc.json`,
  29126. `.${moduleName}rc.yaml`,
  29127. `.${moduleName}rc.yml`,
  29128. `.${moduleName}rc.ts`,
  29129. `.${moduleName}rc.js`,
  29130. `.${moduleName}rc.cjs`,
  29131. `${moduleName}.config.ts`,
  29132. `${moduleName}.config.js`,
  29133. `${moduleName}.config.cjs`
  29134. ],
  29135. loaders: {
  29136. ...options.loaders,
  29137. '.yaml': (filepath, content) => yaml.parse(content),
  29138. '.yml': (filepath, content) => yaml.parse(content),
  29139. '.ts': loader
  29140. }
  29141. }
  29142. };
  29143. const withTypeScriptLoader = (rcFunc) => {
  29144. return (ctx, path, options) => {
  29145. return rcFunc(ctx, path, addTypeScriptLoader(options, (configFile) => {
  29146. let registerer = { enabled () {} };
  29147. try {
  29148. // Register TypeScript compiler instance
  29149. registerer = dist$1.register();
  29150. return commonjsRequire(configFile)
  29151. } catch (err) {
  29152. if (err.code === 'MODULE_NOT_FOUND') {
  29153. throw new Error(
  29154. `'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${err.message}`
  29155. )
  29156. }
  29157. throw err
  29158. } finally {
  29159. registerer.enabled(false);
  29160. }
  29161. }))
  29162. }
  29163. };
  29164. /**
  29165. * Load Config
  29166. *
  29167. * @method rc
  29168. *
  29169. * @param {Object} ctx Config Context
  29170. * @param {String} path Config Path
  29171. * @param {Object} options Config Options
  29172. *
  29173. * @return {Promise} config PostCSS Config
  29174. */
  29175. const rc = withTypeScriptLoader((ctx, path, options) => {
  29176. /**
  29177. * @type {Object} The full Config Context
  29178. */
  29179. ctx = createContext(ctx);
  29180. /**
  29181. * @type {String} `process.cwd()`
  29182. */
  29183. path = path ? resolve$2(path) : process.cwd();
  29184. return config$1.lilconfig('postcss', options)
  29185. .search(path)
  29186. .then((result) => {
  29187. if (!result) {
  29188. throw new Error(`No PostCSS Config found in: ${path}`)
  29189. }
  29190. return processResult(ctx, result)
  29191. })
  29192. });
  29193. rc.sync = withTypeScriptLoader((ctx, path, options) => {
  29194. /**
  29195. * @type {Object} The full Config Context
  29196. */
  29197. ctx = createContext(ctx);
  29198. /**
  29199. * @type {String} `process.cwd()`
  29200. */
  29201. path = path ? resolve$2(path) : process.cwd();
  29202. const result = config$1.lilconfigSync('postcss', options).search(path);
  29203. if (!result) {
  29204. throw new Error(`No PostCSS Config found in: ${path}`)
  29205. }
  29206. return processResult(ctx, result)
  29207. });
  29208. /**
  29209. * Autoload Config for PostCSS
  29210. *
  29211. * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
  29212. * @license MIT
  29213. *
  29214. * @module postcss-load-config
  29215. * @version 2.1.0
  29216. *
  29217. * @requires comsiconfig
  29218. * @requires ./options
  29219. * @requires ./plugins
  29220. */
  29221. var src$2 = rc;
  29222. // Helper since Typescript can't detect readonly arrays with Array.isArray
  29223. function isArray$3(arg) {
  29224. return Array.isArray(arg);
  29225. }
  29226. function ensureArray$1(thing) {
  29227. if (isArray$3(thing))
  29228. return thing;
  29229. if (thing == null)
  29230. return [];
  29231. return [thing];
  29232. }
  29233. const normalizePath$3 = function normalizePath(filename) {
  29234. return filename.split(path$w.win32.sep).join(path$w.posix.sep);
  29235. };
  29236. function getMatcherString$1(id, resolutionBase) {
  29237. if (resolutionBase === false || path$w.isAbsolute(id) || id.startsWith('*')) {
  29238. return id;
  29239. }
  29240. // resolve('') is valid and will default to process.cwd()
  29241. const basePath = normalizePath$3(path$w.resolve(resolutionBase || ''))
  29242. // escape all possible (posix + win) path characters that might interfere with regex
  29243. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  29244. // Note that we use posix.join because:
  29245. // 1. the basePath has been normalized to use /
  29246. // 2. the incoming glob (id) matcher, also uses /
  29247. // otherwise Node will force backslash (\) on windows
  29248. return path$w.posix.join(basePath, id);
  29249. }
  29250. const createFilter$1 = function createFilter(include, exclude, options) {
  29251. const resolutionBase = options && options.resolve;
  29252. const getMatcher = (id) => id instanceof RegExp
  29253. ? id
  29254. : {
  29255. test: (what) => {
  29256. // this refactor is a tad overly verbose but makes for easy debugging
  29257. const pattern = getMatcherString$1(id, resolutionBase);
  29258. const fn = picomatch$3(pattern, { dot: true });
  29259. const result = fn(what);
  29260. return result;
  29261. }
  29262. };
  29263. const includeMatchers = ensureArray$1(include).map(getMatcher);
  29264. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  29265. return function result(id) {
  29266. if (typeof id !== 'string')
  29267. return false;
  29268. if (/\0/.test(id))
  29269. return false;
  29270. const pathId = normalizePath$3(id);
  29271. for (let i = 0; i < excludeMatchers.length; ++i) {
  29272. const matcher = excludeMatchers[i];
  29273. if (matcher.test(pathId))
  29274. return false;
  29275. }
  29276. for (let i = 0; i < includeMatchers.length; ++i) {
  29277. const matcher = includeMatchers[i];
  29278. if (matcher.test(pathId))
  29279. return true;
  29280. }
  29281. return !includeMatchers.length;
  29282. };
  29283. };
  29284. const reservedWords$2 = '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';
  29285. const builtins$1 = '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';
  29286. const forbiddenIdentifiers$1 = new Set(`${reservedWords$2} ${builtins$1}`.split(' '));
  29287. forbiddenIdentifiers$1.add('');
  29288. const makeLegalIdentifier$1 = function makeLegalIdentifier(str) {
  29289. let identifier = str
  29290. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  29291. .replace(/[^$_a-zA-Z0-9]/g, '_');
  29292. if (/\d/.test(identifier[0]) || forbiddenIdentifiers$1.has(identifier)) {
  29293. identifier = `_${identifier}`;
  29294. }
  29295. return identifier || '_';
  29296. };
  29297. function stringify(obj) {
  29298. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  29299. }
  29300. function serializeArray(arr, indent, baseIndent) {
  29301. let output = '[';
  29302. const separator = indent ? `\n${baseIndent}${indent}` : '';
  29303. for (let i = 0; i < arr.length; i++) {
  29304. const key = arr[i];
  29305. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  29306. }
  29307. return `${output}${indent ? `\n${baseIndent}` : ''}]`;
  29308. }
  29309. function serializeObject(obj, indent, baseIndent) {
  29310. let output = '{';
  29311. const separator = indent ? `\n${baseIndent}${indent}` : '';
  29312. const entries = Object.entries(obj);
  29313. for (let i = 0; i < entries.length; i++) {
  29314. const [key, value] = entries[i];
  29315. const stringKey = makeLegalIdentifier$1(key) === key ? key : stringify(key);
  29316. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
  29317. }
  29318. return `${output}${indent ? `\n${baseIndent}` : ''}}`;
  29319. }
  29320. function serialize(obj, indent, baseIndent) {
  29321. if (obj === Infinity)
  29322. return 'Infinity';
  29323. if (obj === -Infinity)
  29324. return '-Infinity';
  29325. if (obj === 0 && 1 / obj === -Infinity)
  29326. return '-0';
  29327. if (obj instanceof Date)
  29328. return `new Date(${obj.getTime()})`;
  29329. if (obj instanceof RegExp)
  29330. return obj.toString();
  29331. if (obj !== obj)
  29332. return 'NaN'; // eslint-disable-line no-self-compare
  29333. if (Array.isArray(obj))
  29334. return serializeArray(obj, indent, baseIndent);
  29335. if (obj === null)
  29336. return 'null';
  29337. if (typeof obj === 'object')
  29338. return serializeObject(obj, indent, baseIndent);
  29339. return stringify(obj);
  29340. }
  29341. const dataToEsm = function dataToEsm(data, options = {}) {
  29342. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  29343. const _ = options.compact ? '' : ' ';
  29344. const n = options.compact ? '' : '\n';
  29345. const declarationType = options.preferConst ? 'const' : 'var';
  29346. if (options.namedExports === false ||
  29347. typeof data !== 'object' ||
  29348. Array.isArray(data) ||
  29349. data instanceof Date ||
  29350. data instanceof RegExp ||
  29351. data === null) {
  29352. const code = serialize(data, options.compact ? null : t, '');
  29353. const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
  29354. return `export default${magic}${code};`;
  29355. }
  29356. let namedExportCode = '';
  29357. const defaultExportRows = [];
  29358. for (const [key, value] of Object.entries(data)) {
  29359. if (key === makeLegalIdentifier$1(key)) {
  29360. if (options.objectShorthand)
  29361. defaultExportRows.push(key);
  29362. else
  29363. defaultExportRows.push(`${key}:${_}${key}`);
  29364. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  29365. }
  29366. else {
  29367. defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
  29368. }
  29369. }
  29370. return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  29371. };
  29372. const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`;
  29373. const cssLangRE = new RegExp(cssLangs);
  29374. const cssModuleRE = new RegExp(`\\.module${cssLangs}`);
  29375. const directRequestRE = /(\?|&)direct\b/;
  29376. const commonjsProxyRE = /\?commonjs-proxy/;
  29377. const inlineRE = /(\?|&)inline\b/;
  29378. const isCSSRequest = (request) => cssLangRE.test(request);
  29379. const isDirectCSSRequest = (request) => cssLangRE.test(request) && directRequestRE.test(request);
  29380. const isDirectRequest = (request) => directRequestRE.test(request);
  29381. const cssModulesCache = new WeakMap();
  29382. const chunkToEmittedCssFileMap = new WeakMap();
  29383. const removedPureCssFilesCache = new WeakMap();
  29384. const postcssConfigCache = new WeakMap();
  29385. /**
  29386. * Plugin applied before user plugins
  29387. */
  29388. function cssPlugin(config) {
  29389. let server;
  29390. let moduleCache;
  29391. const resolveUrl = config.createResolver({
  29392. preferRelative: true,
  29393. tryIndex: false,
  29394. extensions: []
  29395. });
  29396. const atImportResolvers = createCSSResolvers(config);
  29397. return {
  29398. name: 'vite:css',
  29399. configureServer(_server) {
  29400. server = _server;
  29401. },
  29402. buildStart() {
  29403. // Ensure a new cache for every build (i.e. rebuilding in watch mode)
  29404. moduleCache = new Map();
  29405. cssModulesCache.set(config, moduleCache);
  29406. removedPureCssFilesCache.set(config, new Map());
  29407. },
  29408. async transform(raw, id) {
  29409. if (!isCSSRequest(id) || commonjsProxyRE.test(id)) {
  29410. return;
  29411. }
  29412. const urlReplacer = async (url, importer) => {
  29413. if (checkPublicFile(url, config)) {
  29414. return config.base + url.slice(1);
  29415. }
  29416. const resolved = await resolveUrl(url, importer);
  29417. if (resolved) {
  29418. return fileToUrl(resolved, config, this);
  29419. }
  29420. return url;
  29421. };
  29422. const { code: css, modules, deps } = await compileCSS(id, raw, config, urlReplacer, atImportResolvers, server);
  29423. if (modules) {
  29424. moduleCache.set(id, modules);
  29425. }
  29426. // track deps for build watch mode
  29427. if (config.command === 'build' && config.build.watch && deps) {
  29428. for (const file of deps) {
  29429. this.addWatchFile(file);
  29430. }
  29431. }
  29432. // dev
  29433. if (server) {
  29434. // server only logic for handling CSS @import dependency hmr
  29435. const { moduleGraph } = server;
  29436. const thisModule = moduleGraph.getModuleById(id);
  29437. if (thisModule) {
  29438. // CSS modules cannot self-accept since it exports values
  29439. const isSelfAccepting = !modules;
  29440. if (deps) {
  29441. // record deps in the module graph so edits to @import css can trigger
  29442. // main import to hot update
  29443. const depModules = new Set();
  29444. for (const file of deps) {
  29445. depModules.add(isCSSRequest(file)
  29446. ? moduleGraph.createFileOnlyEntry(file)
  29447. : await moduleGraph.ensureEntryFromUrl((await fileToUrl(file, config, this)).replace(config.base, '/')));
  29448. }
  29449. moduleGraph.updateModuleInfo(thisModule, depModules,
  29450. // The root CSS proxy module is self-accepting and should not
  29451. // have an explicit accept list
  29452. new Set(), isSelfAccepting);
  29453. for (const file of deps) {
  29454. this.addWatchFile(file);
  29455. }
  29456. }
  29457. else {
  29458. thisModule.isSelfAccepting = isSelfAccepting;
  29459. }
  29460. }
  29461. }
  29462. return {
  29463. code: css,
  29464. // TODO CSS source map
  29465. map: { mappings: '' }
  29466. };
  29467. }
  29468. };
  29469. }
  29470. /**
  29471. * Plugin applied after user plugins
  29472. */
  29473. function cssPostPlugin(config) {
  29474. // styles initialization in buildStart causes a styling loss in watch
  29475. const styles = new Map();
  29476. let pureCssChunks;
  29477. // when there are multiple rollup outputs and extracting CSS, only emit once,
  29478. // since output formats have no effect on the generated CSS.
  29479. let outputToExtractedCSSMap;
  29480. let hasEmitted = false;
  29481. return {
  29482. name: 'vite:css-post',
  29483. buildStart() {
  29484. // Ensure new caches for every build (i.e. rebuilding in watch mode)
  29485. pureCssChunks = new Set();
  29486. outputToExtractedCSSMap = new Map();
  29487. hasEmitted = false;
  29488. },
  29489. async transform(css, id, ssr) {
  29490. if (!isCSSRequest(id) || commonjsProxyRE.test(id)) {
  29491. return;
  29492. }
  29493. const inlined = inlineRE.test(id);
  29494. const modules = cssModulesCache.get(config).get(id);
  29495. const modulesCode = modules && dataToEsm(modules, { namedExports: true, preferConst: true });
  29496. if (config.command === 'serve') {
  29497. if (isDirectCSSRequest(id)) {
  29498. return css;
  29499. }
  29500. else {
  29501. // server only
  29502. if (ssr) {
  29503. return modulesCode || `export default ${JSON.stringify(css)}`;
  29504. }
  29505. if (inlined) {
  29506. return `export default ${JSON.stringify(css)}`;
  29507. }
  29508. return [
  29509. `import { updateStyle, removeStyle } from ${JSON.stringify(path__default.posix.join(config.base, CLIENT_PUBLIC_PATH))}`,
  29510. `const id = ${JSON.stringify(id)}`,
  29511. `const css = ${JSON.stringify(css)}`,
  29512. `updateStyle(id, css)`,
  29513. // css modules exports change on edit so it can't self accept
  29514. `${modulesCode || `import.meta.hot.accept()\nexport default css`}`,
  29515. `import.meta.hot.prune(() => removeStyle(id))`
  29516. ].join('\n');
  29517. }
  29518. }
  29519. // build CSS handling ----------------------------------------------------
  29520. // record css
  29521. if (!inlined) {
  29522. styles.set(id, css);
  29523. }
  29524. else {
  29525. css = await minifyCSS(css, config);
  29526. }
  29527. return {
  29528. code: modulesCode || `export default ${JSON.stringify(css)}`,
  29529. map: { mappings: '' },
  29530. // avoid the css module from being tree-shaken so that we can retrieve
  29531. // it in renderChunk()
  29532. moduleSideEffects: inlined ? false : 'no-treeshake'
  29533. };
  29534. },
  29535. async renderChunk(code, chunk, opts) {
  29536. let chunkCSS = '';
  29537. let isPureCssChunk = true;
  29538. const ids = Object.keys(chunk.modules);
  29539. for (const id of ids) {
  29540. if (!isCSSRequest(id) ||
  29541. cssModuleRE.test(id) ||
  29542. commonjsProxyRE.test(id)) {
  29543. isPureCssChunk = false;
  29544. }
  29545. if (styles.has(id)) {
  29546. chunkCSS += styles.get(id);
  29547. }
  29548. }
  29549. if (!chunkCSS) {
  29550. return null;
  29551. }
  29552. // resolve asset URL placeholders to their built file URLs and perform
  29553. // minification if necessary
  29554. const processChunkCSS = async (css, { inlined, minify }) => {
  29555. // replace asset url references with resolved url.
  29556. const isRelativeBase = config.base === '' || config.base.startsWith('.');
  29557. css = css.replace(assetUrlRE, (_, fileHash, postfix = '') => {
  29558. const filename = getAssetFilename(fileHash, config) + postfix;
  29559. registerAssetToChunk(chunk, filename);
  29560. if (!isRelativeBase || inlined) {
  29561. // absolute base or relative base but inlined (injected as style tag into
  29562. // index.html) use the base as-is
  29563. return config.base + filename;
  29564. }
  29565. else {
  29566. // relative base + extracted CSS - asset file will be in the same dir
  29567. return `./${path__default.posix.basename(filename)}`;
  29568. }
  29569. });
  29570. // only external @imports should exist at this point - and they need to
  29571. // be hoisted to the top of the CSS chunk per spec (#1845)
  29572. if (css.includes('@import')) {
  29573. css = await hoistAtImports(css);
  29574. }
  29575. if (minify && config.build.minify) {
  29576. css = await minifyCSS(css, config);
  29577. }
  29578. return css;
  29579. };
  29580. if (config.build.cssCodeSplit) {
  29581. if (isPureCssChunk) {
  29582. // this is a shared CSS-only chunk that is empty.
  29583. pureCssChunks.add(chunk.fileName);
  29584. }
  29585. if (opts.format === 'es' || opts.format === 'cjs') {
  29586. chunkCSS = await processChunkCSS(chunkCSS, {
  29587. inlined: false,
  29588. minify: true
  29589. });
  29590. // emit corresponding css file
  29591. const fileHandle = this.emitFile({
  29592. name: chunk.name + '.css',
  29593. type: 'asset',
  29594. source: chunkCSS
  29595. });
  29596. chunkToEmittedCssFileMap.set(chunk, new Set([this.getFileName(fileHandle)]));
  29597. }
  29598. else if (!config.build.ssr) {
  29599. // legacy build, inline css
  29600. chunkCSS = await processChunkCSS(chunkCSS, {
  29601. inlined: true,
  29602. minify: true
  29603. });
  29604. const style = `__vite_style__`;
  29605. const injectCode = `var ${style} = document.createElement('style');` +
  29606. `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` +
  29607. `document.head.appendChild(${style});`;
  29608. if (config.build.sourcemap) {
  29609. const s = new MagicString(code);
  29610. s.prepend(injectCode);
  29611. return {
  29612. code: s.toString(),
  29613. map: s.generateMap({ hires: true })
  29614. };
  29615. }
  29616. else {
  29617. return { code: injectCode + code };
  29618. }
  29619. }
  29620. }
  29621. else {
  29622. // non-split extracted CSS will be minified together
  29623. chunkCSS = await processChunkCSS(chunkCSS, {
  29624. inlined: false,
  29625. minify: false
  29626. });
  29627. outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS);
  29628. }
  29629. return null;
  29630. },
  29631. async generateBundle(opts, bundle) {
  29632. // remove empty css chunks and their imports
  29633. if (pureCssChunks.size) {
  29634. const emptyChunkFiles = [...pureCssChunks]
  29635. .map((file) => path__default.basename(file))
  29636. .join('|')
  29637. .replace(/\./g, '\\.');
  29638. const emptyChunkRE = new RegExp(opts.format === 'es'
  29639. ? `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";\n?`
  29640. : `\\brequire\\(\\s*"[^"]*(?:${emptyChunkFiles})"\\);\n?`, 'g');
  29641. for (const file in bundle) {
  29642. const chunk = bundle[file];
  29643. if (chunk.type === 'chunk') {
  29644. // remove pure css chunk from other chunk's imports,
  29645. // and also register the emitted CSS files under the importer
  29646. // chunks instead.
  29647. chunk.imports = chunk.imports.filter((file) => {
  29648. if (pureCssChunks.has(file)) {
  29649. const css = chunkToEmittedCssFileMap.get(bundle[file]);
  29650. if (css) {
  29651. let existing = chunkToEmittedCssFileMap.get(chunk);
  29652. if (!existing) {
  29653. existing = new Set();
  29654. }
  29655. css.forEach((file) => existing.add(file));
  29656. chunkToEmittedCssFileMap.set(chunk, existing);
  29657. }
  29658. return false;
  29659. }
  29660. return true;
  29661. });
  29662. chunk.code = chunk.code.replace(emptyChunkRE,
  29663. // remove css import while preserving source map location
  29664. (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`);
  29665. }
  29666. }
  29667. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  29668. pureCssChunks.forEach((fileName) => {
  29669. removedPureCssFiles.set(fileName, bundle[fileName]);
  29670. delete bundle[fileName];
  29671. });
  29672. }
  29673. let extractedCss = outputToExtractedCSSMap.get(opts);
  29674. if (extractedCss && !hasEmitted) {
  29675. hasEmitted = true;
  29676. // minify css
  29677. if (config.build.minify) {
  29678. extractedCss = await minifyCSS(extractedCss, config);
  29679. }
  29680. this.emitFile({
  29681. name: 'style.css',
  29682. type: 'asset',
  29683. source: extractedCss
  29684. });
  29685. }
  29686. }
  29687. };
  29688. }
  29689. function createCSSResolvers(config) {
  29690. let cssResolve;
  29691. let sassResolve;
  29692. let lessResolve;
  29693. return {
  29694. get css() {
  29695. return (cssResolve ||
  29696. (cssResolve = config.createResolver({
  29697. extensions: ['.css'],
  29698. mainFields: ['style'],
  29699. tryIndex: false,
  29700. preferRelative: true
  29701. })));
  29702. },
  29703. get sass() {
  29704. return (sassResolve ||
  29705. (sassResolve = config.createResolver({
  29706. extensions: ['.scss', '.sass', '.css'],
  29707. mainFields: ['sass', 'style'],
  29708. tryIndex: true,
  29709. tryPrefix: '_',
  29710. preferRelative: true
  29711. })));
  29712. },
  29713. get less() {
  29714. return (lessResolve ||
  29715. (lessResolve = config.createResolver({
  29716. extensions: ['.less', '.css'],
  29717. mainFields: ['less', 'style'],
  29718. tryIndex: false,
  29719. preferRelative: true
  29720. })));
  29721. }
  29722. };
  29723. }
  29724. function getCssResolversKeys(resolvers) {
  29725. return Object.keys(resolvers);
  29726. }
  29727. async function compileCSS(id, code, config, urlReplacer, atImportResolvers, server) {
  29728. var _a;
  29729. const { modules: modulesOptions, preprocessorOptions } = config.css || {};
  29730. const isModule = modulesOptions !== false && cssModuleRE.test(id);
  29731. // although at serve time it can work without processing, we do need to
  29732. // crawl them in order to register watch dependencies.
  29733. const needInlineImport = code.includes('@import');
  29734. const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
  29735. const postcssConfig = await resolvePostcssConfig(config);
  29736. const lang = (_a = id.match(cssLangRE)) === null || _a === void 0 ? void 0 : _a[1];
  29737. // 1. plain css that needs no processing
  29738. if (lang === 'css' &&
  29739. !postcssConfig &&
  29740. !isModule &&
  29741. !needInlineImport &&
  29742. !hasUrl) {
  29743. return { code };
  29744. }
  29745. let map;
  29746. let modules;
  29747. const deps = new Set();
  29748. // 2. pre-processors: sass etc.
  29749. if (isPreProcessor(lang)) {
  29750. const preProcessor = preProcessors[lang];
  29751. let opts = (preprocessorOptions && preprocessorOptions[lang]) || {};
  29752. // support @import from node dependencies by default
  29753. switch (lang) {
  29754. case "scss" /* scss */:
  29755. case "sass" /* sass */:
  29756. opts = {
  29757. includePaths: ['node_modules'],
  29758. alias: config.resolve.alias,
  29759. ...opts
  29760. };
  29761. break;
  29762. case "less" /* less */:
  29763. case "styl" /* styl */:
  29764. case "stylus" /* stylus */:
  29765. opts = {
  29766. paths: ['node_modules'],
  29767. alias: config.resolve.alias,
  29768. ...opts
  29769. };
  29770. }
  29771. // important: set this for relative import resolving
  29772. opts.filename = cleanUrl(id);
  29773. const preprocessResult = await preProcessor(code, config.root, opts, atImportResolvers);
  29774. if (preprocessResult.errors.length) {
  29775. throw preprocessResult.errors[0];
  29776. }
  29777. code = preprocessResult.code;
  29778. map = preprocessResult.map;
  29779. if (preprocessResult.deps) {
  29780. preprocessResult.deps.forEach((dep) => {
  29781. // sometimes sass registers the file itself as a dep
  29782. if (normalizePath$4(dep) !== normalizePath$4(opts.filename)) {
  29783. deps.add(dep);
  29784. }
  29785. });
  29786. }
  29787. }
  29788. // 3. postcss
  29789. const postcssOptions = (postcssConfig && postcssConfig.options) || {};
  29790. const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
  29791. if (needInlineImport) {
  29792. postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-0d2f9464.js'); }).then(function (n) { return n.index; })).default({
  29793. async resolve(id, basedir) {
  29794. const resolved = await atImportResolvers.css(id, path__default.join(basedir, '*'));
  29795. if (resolved) {
  29796. return path__default.resolve(resolved);
  29797. }
  29798. return id;
  29799. }
  29800. }));
  29801. }
  29802. postcssPlugins.push(UrlRewritePostcssPlugin({
  29803. replacer: urlReplacer
  29804. }));
  29805. if (isModule) {
  29806. postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-afe9ad01.js'); }).then(function (n) { return n.index; })).default({
  29807. ...modulesOptions,
  29808. getJSON(cssFileName, _modules, outputFileName) {
  29809. modules = _modules;
  29810. if (modulesOptions && typeof modulesOptions.getJSON === 'function') {
  29811. modulesOptions.getJSON(cssFileName, _modules, outputFileName);
  29812. }
  29813. },
  29814. async resolve(id) {
  29815. for (const key of getCssResolversKeys(atImportResolvers)) {
  29816. const resolved = await atImportResolvers[key](id);
  29817. if (resolved) {
  29818. return path__default.resolve(resolved);
  29819. }
  29820. }
  29821. return id;
  29822. }
  29823. }));
  29824. }
  29825. if (!postcssPlugins.length) {
  29826. return {
  29827. code,
  29828. map
  29829. };
  29830. }
  29831. // postcss is an unbundled dep and should be lazy imported
  29832. const postcssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); }))
  29833. .default(postcssPlugins)
  29834. .process(code, {
  29835. ...postcssOptions,
  29836. to: id,
  29837. from: id,
  29838. map: {
  29839. inline: false,
  29840. annotation: false,
  29841. prev: map
  29842. }
  29843. });
  29844. // record CSS dependencies from @imports
  29845. for (const message of postcssResult.messages) {
  29846. if (message.type === 'dependency') {
  29847. deps.add(message.file);
  29848. }
  29849. else if (message.type === 'dir-dependency') {
  29850. // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
  29851. const { dir, glob: globPattern = '**' } = message;
  29852. const pattern = normalizePath$4(path__default.resolve(path__default.dirname(id), dir)) + `/` + globPattern;
  29853. const files = out.sync(pattern, {
  29854. ignore: ['**/node_modules/**']
  29855. });
  29856. for (let i = 0; i < files.length; i++) {
  29857. deps.add(files[i]);
  29858. }
  29859. if (server) {
  29860. // register glob importers so we can trigger updates on file add/remove
  29861. if (!(id in server._globImporters)) {
  29862. server._globImporters[id] = {
  29863. module: server.moduleGraph.getModuleById(id),
  29864. importGlobs: []
  29865. };
  29866. }
  29867. server._globImporters[id].importGlobs.push({
  29868. base: config.root,
  29869. pattern
  29870. });
  29871. }
  29872. }
  29873. else if (message.type === 'warning') {
  29874. let msg = `[vite:css] ${message.text}`;
  29875. if (message.line && message.column) {
  29876. msg += `\n${generateCodeFrame(code, {
  29877. line: message.line,
  29878. column: message.column
  29879. })}`;
  29880. }
  29881. config.logger.warn(source.yellow(msg));
  29882. }
  29883. }
  29884. return {
  29885. ast: postcssResult,
  29886. code: postcssResult.css,
  29887. map: postcssResult.map,
  29888. modules,
  29889. deps
  29890. };
  29891. }
  29892. async function resolvePostcssConfig(config) {
  29893. var _a;
  29894. let result = postcssConfigCache.get(config);
  29895. if (result !== undefined) {
  29896. return result;
  29897. }
  29898. // inline postcss config via vite config
  29899. const inlineOptions = (_a = config.css) === null || _a === void 0 ? void 0 : _a.postcss;
  29900. if (isObject$3(inlineOptions)) {
  29901. const options = { ...inlineOptions };
  29902. delete options.plugins;
  29903. result = {
  29904. options,
  29905. plugins: inlineOptions.plugins || []
  29906. };
  29907. }
  29908. else {
  29909. try {
  29910. const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
  29911. // @ts-ignore
  29912. result = await src$2({}, searchPath);
  29913. }
  29914. catch (e) {
  29915. if (!/No PostCSS Config found/.test(e.message)) {
  29916. throw e;
  29917. }
  29918. result = null;
  29919. }
  29920. }
  29921. postcssConfigCache.set(config, result);
  29922. return result;
  29923. }
  29924. // https://drafts.csswg.org/css-syntax-3/#identifier-code-point
  29925. const cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/;
  29926. const cssImageSetRE = /image-set\(([^)]+)\)/;
  29927. const UrlRewritePostcssPlugin = (opts) => {
  29928. if (!opts) {
  29929. throw new Error('base or replace is required');
  29930. }
  29931. return {
  29932. postcssPlugin: 'vite-url-rewrite',
  29933. Once(root) {
  29934. const promises = [];
  29935. root.walkDecls((declaration) => {
  29936. const isCssUrl = cssUrlRE.test(declaration.value);
  29937. const isCssImageSet = cssImageSetRE.test(declaration.value);
  29938. if (isCssUrl || isCssImageSet) {
  29939. const replacerForDeclaration = (rawUrl) => {
  29940. var _a;
  29941. const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file;
  29942. return opts.replacer(rawUrl, importer);
  29943. };
  29944. const rewriterToUse = isCssUrl ? rewriteCssUrls : rewriteCssImageSet;
  29945. promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => {
  29946. declaration.value = url;
  29947. }));
  29948. }
  29949. });
  29950. if (promises.length) {
  29951. return Promise.all(promises);
  29952. }
  29953. }
  29954. };
  29955. };
  29956. UrlRewritePostcssPlugin.postcss = true;
  29957. function rewriteCssUrls(css, replacer) {
  29958. return asyncReplace(css, cssUrlRE, async (match) => {
  29959. const [matched, rawUrl] = match;
  29960. return await doUrlReplace(rawUrl, matched, replacer);
  29961. });
  29962. }
  29963. function rewriteCssImageSet(css, replacer) {
  29964. return asyncReplace(css, cssImageSetRE, async (match) => {
  29965. const [matched, rawUrl] = match;
  29966. const url = await processSrcSet(rawUrl, ({ url }) => doUrlReplace(url, matched, replacer));
  29967. return `image-set(${url})`;
  29968. });
  29969. }
  29970. async function doUrlReplace(rawUrl, matched, replacer) {
  29971. let wrap = '';
  29972. const first = rawUrl[0];
  29973. if (first === `"` || first === `'`) {
  29974. wrap = first;
  29975. rawUrl = rawUrl.slice(1, -1);
  29976. }
  29977. if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) {
  29978. return matched;
  29979. }
  29980. return `url(${wrap}${await replacer(rawUrl)}${wrap})`;
  29981. }
  29982. async function minifyCSS(css, config) {
  29983. const { code, warnings } = await esbuild.transform(css, {
  29984. loader: 'css',
  29985. minify: true,
  29986. target: config.build.target || undefined
  29987. });
  29988. if (warnings.length) {
  29989. const msgs = await esbuild.formatMessages(warnings, { kind: 'warning' });
  29990. config.logger.warn(source.yellow(`warnings when minifying css:\n${msgs.join('\n')}`));
  29991. }
  29992. return code;
  29993. }
  29994. // #1845
  29995. // CSS @import can only appear at top of the file. We need to hoist all @import
  29996. // to top when multiple files are concatenated.
  29997. async function hoistAtImports(css) {
  29998. const postcss = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); });
  29999. return (await postcss.default([AtImportHoistPlugin]).process(css)).css;
  30000. }
  30001. const AtImportHoistPlugin = () => {
  30002. return {
  30003. postcssPlugin: 'vite-hoist-at-imports',
  30004. Once(root) {
  30005. const imports = [];
  30006. root.walkAtRules((rule) => {
  30007. if (rule.name === 'import') {
  30008. // record in reverse so that can simply prepend to preserve order
  30009. imports.unshift(rule);
  30010. }
  30011. });
  30012. imports.forEach((i) => root.prepend(i));
  30013. }
  30014. };
  30015. };
  30016. AtImportHoistPlugin.postcss = true;
  30017. const loadedPreprocessors = {};
  30018. function loadPreprocessor(lang, root) {
  30019. if (lang in loadedPreprocessors) {
  30020. return loadedPreprocessors[lang];
  30021. }
  30022. try {
  30023. // Search for the preprocessor in the root directory first, and fall back
  30024. // to the default require paths.
  30025. const fallbackPaths = require.resolve.paths(lang) || [];
  30026. const resolved = require.resolve(lang, { paths: [root, ...fallbackPaths] });
  30027. return (loadedPreprocessors[lang] = require(resolved));
  30028. }
  30029. catch (e) {
  30030. throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it?`);
  30031. }
  30032. }
  30033. // .scss/.sass processor
  30034. const scss = async (source, root, options, resolvers) => {
  30035. const render = loadPreprocessor("sass" /* sass */, root).render;
  30036. const internalImporter = (url, importer, done) => {
  30037. resolvers.sass(url, importer).then((resolved) => {
  30038. if (resolved) {
  30039. rebaseUrls(resolved, options.filename, options.alias)
  30040. .then(done)
  30041. .catch(done);
  30042. }
  30043. else {
  30044. done(null);
  30045. }
  30046. });
  30047. };
  30048. const importer = [internalImporter];
  30049. if (options.importer) {
  30050. Array.isArray(options.importer)
  30051. ? importer.push(...options.importer)
  30052. : importer.push(options.importer);
  30053. }
  30054. const finalOptions = {
  30055. ...options,
  30056. data: await getSource(source, options.filename, options.additionalData),
  30057. file: options.filename,
  30058. outFile: options.filename,
  30059. importer
  30060. };
  30061. try {
  30062. const result = await new Promise((resolve, reject) => {
  30063. render(finalOptions, (err, res) => {
  30064. if (err) {
  30065. reject(err);
  30066. }
  30067. else {
  30068. resolve(res);
  30069. }
  30070. });
  30071. });
  30072. const deps = result.stats.includedFiles;
  30073. return {
  30074. code: result.css.toString(),
  30075. errors: [],
  30076. deps
  30077. };
  30078. }
  30079. catch (e) {
  30080. // normalize SASS error
  30081. e.id = e.file;
  30082. e.frame = e.formatted;
  30083. return { code: '', errors: [e], deps: [] };
  30084. }
  30085. };
  30086. const sass = (source, root, options, aliasResolver) => scss(source, root, {
  30087. ...options,
  30088. indentedSyntax: true
  30089. }, aliasResolver);
  30090. /**
  30091. * relative url() inside \@imported sass and less files must be rebased to use
  30092. * root file as base.
  30093. */
  30094. async function rebaseUrls(file, rootFile, alias) {
  30095. file = path__default.resolve(file); // ensure os-specific flashes
  30096. // in the same dir, no need to rebase
  30097. const fileDir = path__default.dirname(file);
  30098. const rootDir = path__default.dirname(rootFile);
  30099. if (fileDir === rootDir) {
  30100. return { file };
  30101. }
  30102. // no url()
  30103. const content = fs__default.readFileSync(file, 'utf-8');
  30104. if (!cssUrlRE.test(content)) {
  30105. return { file };
  30106. }
  30107. const rebased = await rewriteCssUrls(content, (url) => {
  30108. if (url.startsWith('/'))
  30109. return url;
  30110. // match alias, no need to rewrite
  30111. for (const { find } of alias) {
  30112. const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
  30113. if (matches) {
  30114. return url;
  30115. }
  30116. }
  30117. const absolute = path__default.resolve(fileDir, url);
  30118. const relative = path__default.relative(rootDir, absolute);
  30119. return normalizePath$4(relative);
  30120. });
  30121. return {
  30122. file,
  30123. contents: rebased
  30124. };
  30125. }
  30126. // .less
  30127. const less = async (source, root, options, resolvers) => {
  30128. const nodeLess = loadPreprocessor("less" /* less */, root);
  30129. const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers);
  30130. source = await getSource(source, options.filename, options.additionalData);
  30131. let result;
  30132. try {
  30133. result = await nodeLess.render(source, {
  30134. ...options,
  30135. plugins: [viteResolverPlugin, ...(options.plugins || [])]
  30136. });
  30137. }
  30138. catch (e) {
  30139. const error = e;
  30140. // normalize error info
  30141. const normalizedError = new Error(error.message || error.type);
  30142. normalizedError.loc = {
  30143. file: error.filename || options.filename,
  30144. line: error.line,
  30145. column: error.column
  30146. };
  30147. return { code: '', errors: [normalizedError], deps: [] };
  30148. }
  30149. return {
  30150. code: result.css.toString(),
  30151. deps: result.imports,
  30152. errors: []
  30153. };
  30154. };
  30155. /**
  30156. * Less manager, lazy initialized
  30157. */
  30158. let ViteLessManager;
  30159. function createViteLessPlugin(less, rootFile, alias, resolvers) {
  30160. if (!ViteLessManager) {
  30161. ViteLessManager = class ViteManager extends less.FileManager {
  30162. constructor(rootFile, resolvers, alias) {
  30163. super();
  30164. this.rootFile = rootFile;
  30165. this.resolvers = resolvers;
  30166. this.alias = alias;
  30167. }
  30168. supports() {
  30169. return true;
  30170. }
  30171. supportsSync() {
  30172. return false;
  30173. }
  30174. async loadFile(filename, dir, opts, env) {
  30175. const resolved = await this.resolvers.less(filename, path__default.join(dir, '*'));
  30176. if (resolved) {
  30177. const result = await rebaseUrls(resolved, this.rootFile, this.alias);
  30178. let contents;
  30179. if (result && 'contents' in result) {
  30180. contents = result.contents;
  30181. }
  30182. else {
  30183. contents = fs__default.readFileSync(resolved, 'utf-8');
  30184. }
  30185. return {
  30186. filename: path__default.resolve(resolved),
  30187. contents
  30188. };
  30189. }
  30190. else {
  30191. return super.loadFile(filename, dir, opts, env);
  30192. }
  30193. }
  30194. };
  30195. }
  30196. return {
  30197. install(_, pluginManager) {
  30198. pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias));
  30199. },
  30200. minVersion: [3, 0, 0]
  30201. };
  30202. }
  30203. // .styl
  30204. const styl = async (source, root, options) => {
  30205. var _a;
  30206. const nodeStylus = loadPreprocessor("stylus" /* stylus */, root);
  30207. // Get source with preprocessor options.additionalData. Make sure a new line separator
  30208. // is added to avoid any render error, as added stylus content may not have semi-colon separators
  30209. source = await getSource(source, options.filename, options.additionalData, '\n');
  30210. // Get preprocessor options.imports dependencies as stylus
  30211. // does not return them with its builtin `.deps()` method
  30212. const importsDeps = ((_a = options.imports) !== null && _a !== void 0 ? _a : []).map((dep) => path__default.resolve(dep));
  30213. try {
  30214. const ref = nodeStylus(source, options);
  30215. // if (map) ref.set('sourcemap', { inline: false, comment: false })
  30216. const result = ref.render();
  30217. // Concat imports deps with computed deps
  30218. const deps = [...ref.deps(), ...importsDeps];
  30219. return { code: result, errors: [], deps };
  30220. }
  30221. catch (e) {
  30222. return { code: '', errors: [e], deps: [] };
  30223. }
  30224. };
  30225. function getSource(source, filename, additionalData, sep = '') {
  30226. if (!additionalData)
  30227. return source;
  30228. if (typeof additionalData === 'function') {
  30229. return additionalData(source, filename);
  30230. }
  30231. return additionalData + sep + source;
  30232. }
  30233. const preProcessors = Object.freeze({
  30234. ["less" /* less */]: less,
  30235. ["sass" /* sass */]: sass,
  30236. ["scss" /* scss */]: scss,
  30237. ["styl" /* styl */]: styl,
  30238. ["stylus" /* stylus */]: styl
  30239. });
  30240. function isPreProcessor(lang) {
  30241. return lang && lang in preProcessors;
  30242. }
  30243. /* es-module-lexer 0.7.1 */
  30244. const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$d(E,g="@"){if(!C)return init.then(()=>parse$d(E));const I=E.length+1,D=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;D>0&&C.memory.grow(Math.ceil(D/65536));const w=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,w,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const L=[],k=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),D=C.se();let w;C.ip()&&(w=o(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),L.push({n:w,s:A,e:Q,ss:I,se:D,d:g,a:B});}for(;C.re();)k.push(E.slice(C.es(),C.ee()));function o(A){try{return (0, eval)(A)}catch{}}return [L,k,!!C.f()]}function Q(A,Q){const B=A.length;let C=0;for(;C<B;){const B=A.charCodeAt(C);Q[C++]=(255&B)<<8|B>>>8;}}function B(A,Q){const B=A.length;let C=0;for(;C<B;)Q[C]=A.charCodeAt(C++);}let C;const init=WebAssembly.compile((E="AGFzbQEAAAABXA1gAX8Bf2AEf39/fwBgAn9/AGAAAX9gAABgAX8AYAZ/f39/f38Bf2AEf39/fwF/YAN/f38Bf2AHf39/f39/fwF/YAV/f39/fwF/YAJ/fwF/YAh/f39/f39/fwF/AzIxAAECAwMDAwMDAwMDAwMDAwAEBQAGBAQAAAAABAQEBAQABgcICQoLDAACAAAACwMJDAQFAXABAQEFAwEAAQYPAn8BQfDwAAt/AEHw8AALB2QRBm1lbW9yeQIAAnNhAAABZQADAmlzAAQCaWUABQJzcwAGAnNlAAcCYWkACAJpZAAJAmlwAAoCZXMACwJlZQAMAnJpAA0CcmUADgFmAA8FcGFyc2UAEAtfX2hlYXBfYmFzZQMBCrc6MWgBAX9BACAANgK4CEEAKAKQCCIBIABBAXRqIgBBADsBAEEAIABBAmoiADYCvAhBACAANgLACEEAQQA2ApQIQQBBADYCpAhBAEEANgKcCEEAQQA2ApgIQQBBADYCrAhBAEEANgKgCCABC7IBAQJ/QQAoAqQIIgRBHGpBlAggBBtBACgCwAgiBTYCAEEAIAU2AqQIQQAgBDYCqAhBACAFQSBqNgLACCAFIAA2AggCQAJAQQAoAogIIANHDQAgBSACNgIMDAELAkBBACgChAggA0cNACAFIAJBAmo2AgwMAQsgBUEAKAKQCDYCDAsgBSABNgIAIAUgAzYCFCAFQQA2AhAgBSACNgIEIAVBADYCHCAFQQAoAoQIIANGOgAYC0gBAX9BACgCrAgiAkEIakGYCCACG0EAKALACCICNgIAQQAgAjYCrAhBACACQQxqNgLACCACQQA2AgggAiABNgIEIAIgADYCAAsIAEEAKALECAsVAEEAKAKcCCgCAEEAKAKQCGtBAXULFQBBACgCnAgoAgRBACgCkAhrQQF1CxUAQQAoApwIKAIIQQAoApAIa0EBdQsVAEEAKAKcCCgCDEEAKAKQCGtBAXULHgEBf0EAKAKcCCgCECIAQQAoApAIa0EBdUF/IAAbCzsBAX8CQEEAKAKcCCgCFCIAQQAoAoQIRw0AQX8PCwJAIABBACgCiAhHDQBBfg8LIABBACgCkAhrQQF1CwsAQQAoApwILQAYCxUAQQAoAqAIKAIAQQAoApAIa0EBdQsVAEEAKAKgCCgCBEEAKAKQCGtBAXULJQEBf0EAQQAoApwIIgBBHGpBlAggABsoAgAiADYCnAggAEEARwslAQF/QQBBACgCoAgiAEEIakGYCCAAGygCACIANgKgCCAAQQBHCwgAQQAtAMgIC6IMAQV/IwBBgPAAayIBJABBAEEBOgDICEEAQf//AzsBzghBAEEAKAKMCDYC0AhBAEEAKAKQCEF+aiICNgLkCEEAIAJBACgCuAhBAXRqIgM2AugIQQBBADsByghBAEEAOwHMCEEAQQA6ANQIQQBBADYCxAhBAEEAOgC0CEEAIAFBgNAAajYC2AhBACABQYAQajYC3AhBAEEAOgDgCAJAAkACQANAQQAgAkECaiIENgLkCAJAAkACQAJAIAIgA08NACAELwEAIgNBd2pBBUkNAyADQZt/aiIFQQRNDQEgA0EgRg0DAkAgA0EvRg0AIANBO0YNAwwGCwJAIAIvAQQiBEEqRg0AIARBL0cNBhARDAQLQQEQEgwDC0EAIQMgBCECQQAtALQIDQYMBQsCQAJAIAUOBQEFBQUAAQsgBBATRQ0BIAJBBGpB7QBB8ABB7wBB8gBB9AAQFEUNARAVDAELQQAvAcwIDQAgBBATRQ0AIAJBBGpB+ABB8ABB7wBB8gBB9AAQFEUNABAWQQAtAMgIDQBBAEEAKALkCCICNgLQCAwEC0EAQQAoAuQINgLQCAtBACgC6AghA0EAKALkCCECDAALC0EAIAI2AuQIQQBBADoAyAgLA0BBACACQQJqIgM2AuQIAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAJBACgC6AhPDQAgAy8BACIEQXdqQQVJDQ4gBEFgaiIFQQlNDQEgBEGgf2oiBUEJTQ0CAkACQAJAIARBhX9qIgNBAk0NACAEQS9HDRAgAi8BBCICQSpGDQEgAkEvRw0CEBEMEQsCQAJAIAMOAwARAQALAkBBACgC0AgiBC8BAEEpRw0AQQAoAqQIIgJFDQAgAigCBCAERw0AQQBBACgCqAgiAjYCpAgCQCACRQ0AIAJBADYCHAwBC0EAQQA2ApQICyABQQAvAcwIIgJqQQAtAOAIOgAAQQAgAkEBajsBzAhBACgC3AggAkECdGogBDYCAEEAQQA6AOAIDBALQQAvAcwIIgJFDQlBACACQX9qIgM7AcwIAkAgAkEALwHOCCIERw0AQQBBAC8ByghBf2oiAjsByghBAEEAKALYCCACQf//A3FBAXRqLwEAOwHOCAwICyAEQf//A0YNDyADQf//A3EgBEkNCQwPC0EBEBIMDwsCQAJAAkACQEEAKALQCCIELwEAIgIQF0UNACACQVVqIgNBA0sNAgJAAkACQCADDgQBBQIAAQsgBEF+ai8BAEFQakH//wNxQQpJDQMMBAsgBEF+ai8BAEErRg0CDAMLIARBfmovAQBBLUYNAQwCCwJAIAJB/QBGDQAgAkEpRw0BQQAoAtwIQQAvAcwIQQJ0aigCABAYRQ0BDAILQQAoAtwIQQAvAcwIIgNBAnRqKAIAEBkNASABIANqLQAADQELIAQQGg0AIAJFDQBBASEEIAJBL0ZBAC0A1AhBAEdxRQ0BCxAbQQAhBAtBACAEOgDUCAwNC0EALwHOCEH//wNGQQAvAcwIRXFBAC0AtAhFcSEDDA8LIAUOCgwLAQsLCwsCBwQMCyAFDgoCCgoHCgkKCgoIAgsQHAwJCxAdDAgLEB4MBwtBAC8BzAgiAg0BCxAfQQAhAwwIC0EAIAJBf2oiBDsBzAhBACgCsAgiAkUNBCACKAIUQQAoAtwIIARB//8DcUECdGooAgBHDQQCQCACKAIEDQAgAiADNgIECyACIAM2AgxBAEEANgKwCAwEC0EAQQAvAcwIIgJBAWo7AcwIQQAoAtwIIAJBAnRqQQAoAtAINgIADAMLIAMQE0UNAiACLwEKQfMARw0CIAIvAQhB8wBHDQIgAi8BBkHhAEcNAiACLwEEQewARw0CAkACQCACLwEMIgRBd2oiAkEXSw0AQQEgAnRBn4CABHENAQsgBEGgAUcNAwtBAEEBOgDgCAwCCyADEBNFDQEgAkEEakHtAEHwAEHvAEHyAEH0ABAURQ0BEBUMAQtBAC8BzAgNACADEBNFDQAgAkEEakH4AEHwAEHvAEHyAEH0ABAURQ0AEBYLQQBBACgC5Ag2AtAIC0EAKALkCCECDAALCyABQYDwAGokACADC1ABBH9BACgC5AhBAmohAEEAKALoCCEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2aiIDQQNLDQAgAw4EAQAAAQELC0EAIAI2AuQIC6EBAQN/QQBBACgC5AgiAUECajYC5AggAUEGaiEBQQAoAugIIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoiA0EDSw0EIAMOBAIEBAICCyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2AuQIDAELIAFBfmohAQtBACABNgLkCA8LIAFBAmohAQwACwsdAAJAQQAoApAIIABHDQBBAQ8LIABBfmovAQAQIAs/AQF/QQAhBgJAIAAvAQggBUcNACAALwEGIARHDQAgAC8BBCADRw0AIAAvAQIgAkcNACAALwEAIAFGIQYLIAYL7wQBBH9BAEEAKALkCCIAQQxqIgE2AuQIAkACQAJAAkACQEEBECgiAkFZaiIDQQdNDQAgAkEiRg0CIAJB+wBGDQIMAQsCQAJAIAMOCAMBAgMCAgIAAwtBAEEAKALkCEECajYC5AhBARAoQe0ARw0DQQAoAuQIIgMvAQZB4QBHDQMgAy8BBEH0AEcNAyADLwECQeUARw0DQQAoAtAILwEAQS5GDQMgACAAIANBCGpBACgCiAgQAQ8LQQAoAtwIQQAvAcwIIgNBAnRqIAA2AgBBACADQQFqOwHMCEEAKALQCC8BAEEuRg0CIABBACgC5AhBAmpBACAAEAFBAEEAKAKkCDYCsAhBAEEAKALkCEECajYC5AgCQAJAQQEQKCIDQSJGDQACQCADQSdHDQAQHQwCC0EAQQAoAuQIQX5qNgLkCA8LEBwLQQBBACgC5AhBAmo2AuQIAkBBARAoQVdqIgNBA0sNAAJAAkAgAw4EAQICAAELQQAoAqQIQQAoAuQIIgM2AgRBACADQQJqNgLkCEEBECgaQQAoAqQIIgNBAToAGCADQQAoAuQIIgI2AhBBACACQX5qNgLkCA8LQQAoAqQIIgNBAToAGCADQQAoAuQIIgI2AgwgAyACNgIEQQBBAC8BzAhBf2o7AcwIDwtBAEEAKALkCEF+ajYC5AgPC0EAKALkCCABRg0BC0EALwHMCA0BQQAoAuQIIQNBACgC6AghAQJAA0AgAyABTw0BAkACQCADLwEAIgJBJ0YNACACQSJHDQELIAAgAhApDwtBACADQQJqIgM2AuQIDAALCxAfCw8LQQBBACgC5AhBfmo2AuQIC7IGAQR/QQBBACgC5AgiAEEMaiIBNgLkCEEBECghAgJAAkACQAJAAkACQEEAKALkCCIDIAFHDQAgAhAsRQ0BCwJAAkACQAJAIAJBn39qIgFBC00NAAJAAkAgAkEqRg0AIAJB9gBGDQUgAkH7AEcNA0EAIANBAmo2AuQIQQEQKCEDQQAoAuQIIQEDQCADQf//A3EQKxpBACgC5AghAkEBECgaAkAgASACEC0iA0EsRw0AQQBBACgC5AhBAmo2AuQIQQEQKCEDC0EAKALkCCECAkAgA0H9AEYNACACIAFGDQwgAiEBIAJBACgC6AhNDQEMDAsLQQAgAkECajYC5AgMAQtBACADQQJqNgLkCEEBECgaQQAoAuQIIgIgAhAtGgtBARAoIQIMAQsgAQ4MBAABBgAFAAAAAAACBAtBACgC5AghAwJAIAJB5gBHDQAgAy8BBkHtAEcNACADLwEEQe8ARw0AIAMvAQJB8gBHDQBBACADQQhqNgLkCCAAQQEQKBApDwtBACADQX5qNgLkCAwCCwJAIAMvAQhB8wBHDQAgAy8BBkHzAEcNACADLwEEQeEARw0AIAMvAQJB7ABHDQAgAy8BChAgRQ0AQQAgA0EKajYC5AhBARAoIQJBACgC5AghAyACECsaIANBACgC5AgQAkEAQQAoAuQIQX5qNgLkCA8LQQAgA0EEaiIDNgLkCAtBACADQQRqIgI2AuQIQQBBADoAyAgDQEEAIAJBAmo2AuQIQQEQKCEDQQAoAuQIIQICQCADECtBIHJB+wBHDQBBAEEAKALkCEF+ajYC5AgPC0EAKALkCCIDIAJGDQEgAiADEAICQEEBECgiAkEsRg0AAkAgAkE9Rw0AQQBBACgC5AhBfmo2AuQIDwtBAEEAKALkCEF+ajYC5AgPC0EAKALkCCECDAALCw8LQQAgA0EKajYC5AhBARAoGkEAKALkCCEDC0EAIANBEGo2AuQIAkBBARAoIgJBKkcNAEEAQQAoAuQIQQJqNgLkCEEBECghAgtBACgC5AghAyACECsaIANBACgC5AgQAkEAQQAoAuQIQX5qNgLkCA8LIAMgA0EOahACDwsQHwt1AQF/AkACQCAAQV9qIgFBBUsNAEEBIAF0QTFxDQELIABBRmpB//8DcUEGSQ0AIABBWGpB//8DcUEHSSAAQSlHcQ0AAkAgAEGlf2oiAUEDSw0AIAEOBAEAAAEBCyAAQf0ARyAAQYV/akH//wNxQQRJcQ8LQQELPQEBf0EBIQECQCAAQfcAQegAQekAQewAQeUAECENACAAQeYAQe8AQfIAECINACAAQekAQeYAECMhAQsgAQutAQEDf0EBIQECQAJAAkACQAJAAkACQCAALwEAIgJBRWoiA0EDTQ0AIAJBm39qIgNBA00NASACQSlGDQMgAkH5AEcNAiAAQX5qQeYAQekAQe4AQeEAQewAQewAECQPCyADDgQCAQEFAgsgAw4EAgAAAwILQQAhAQsgAQ8LIABBfmpB5QBB7ABB8wAQIg8LIABBfmpB4wBB4QBB9ABB4wAQJQ8LIABBfmovAQBBPUYL7QMBAn9BACEBAkAgAC8BAEGcf2oiAkETSw0AAkACQAJAAkACQAJAAkACQCACDhQAAQIICAgICAgIAwQICAUIBggIBwALIABBfmovAQBBl39qIgJBA0sNBwJAAkAgAg4EAAkJAQALIABBfGpB9gBB7wAQIw8LIABBfGpB+QBB6QBB5QAQIg8LIABBfmovAQBBjX9qIgJBAUsNBgJAAkAgAg4CAAEACwJAIABBfGovAQAiAkHhAEYNACACQewARw0IIABBempB5QAQJg8LIABBempB4wAQJg8LIABBfGpB5ABB5QBB7ABB5QAQJQ8LIABBfmovAQBB7wBHDQUgAEF8ai8BAEHlAEcNBQJAIABBemovAQAiAkHwAEYNACACQeMARw0GIABBeGpB6QBB7gBB8wBB9ABB4QBB7gAQJA8LIABBeGpB9ABB+QAQIw8LQQEhASAAQX5qIgBB6QAQJg0EIABB8gBB5QBB9ABB9QBB8gAQIQ8LIABBfmpB5AAQJg8LIABBfmpB5ABB5QBB4gBB9QBB5wBB5wBB5QAQJw8LIABBfmpB4QBB9wBB4QBB6QAQJQ8LAkAgAEF+ai8BACICQe8ARg0AIAJB5QBHDQEgAEF8akHuABAmDwsgAEF8akH0AEHoAEHyABAiIQELIAELgwEBA38DQEEAQQAoAuQIIgBBAmoiATYC5AgCQAJAAkAgAEEAKALoCE8NACABLwEAIgFBpX9qIgJBAU0NAgJAIAFBdmoiAEEDTQ0AIAFBL0cNBAwCCyAADgQAAwMAAAsQHwsPCwJAAkAgAg4CAQABC0EAIABBBGo2AuQIDAELEC4aDAALC5EBAQR/QQAoAuQIIQBBACgC6AghAQJAA0AgACICQQJqIQAgAiABTw0BAkAgAC8BACIDQdwARg0AAkAgA0F2aiICQQNNDQAgA0EiRw0CQQAgADYC5AgPCyACDgQCAQECAgsgAkEEaiEAIAIvAQRBDUcNACACQQZqIAAgAi8BBkEKRhshAAwACwtBACAANgLkCBAfC5EBAQR/QQAoAuQIIQBBACgC6AghAQJAA0AgACICQQJqIQAgAiABTw0BAkAgAC8BACIDQdwARg0AAkAgA0F2aiICQQNNDQAgA0EnRw0CQQAgADYC5AgPCyACDgQCAQECAgsgAkEEaiEAIAIvAQRBDUcNACACQQZqIAAgAi8BBkEKRhshAAwACwtBACAANgLkCBAfC8kBAQV/QQAoAuQIIQBBACgC6AghAQNAIAAiAkECaiEAAkACQCACIAFPDQAgAC8BACIDQaR/aiIEQQRNDQEgA0EkRw0CIAIvAQRB+wBHDQJBAEEALwHKCCIAQQFqOwHKCEEAKALYCCAAQQF0akEALwHOCDsBAEEAIAJBBGo2AuQIQQBBAC8BzAhBAWoiADsBzghBACAAOwHMCA8LQQAgADYC5AgQHw8LAkACQCAEDgUBAgICAAELQQAgADYC5AgPCyACQQRqIQAMAAsLNQEBf0EAQQE6ALQIQQAoAuQIIQBBAEEAKALoCEECajYC5AhBACAAQQAoApAIa0EBdTYCxAgLNAEBf0EBIQECQCAAQXdqQf//A3FBBUkNACAAQYABckGgAUYNACAAQS5HIAAQLHEhAQsgAQtJAQN/QQAhBgJAIABBeGoiB0EAKAKQCCIISQ0AIAcgASACIAMgBCAFEBRFDQACQCAHIAhHDQBBAQ8LIABBdmovAQAQICEGCyAGC1kBA39BACEEAkAgAEF8aiIFQQAoApAIIgZJDQAgAC8BACADRw0AIABBfmovAQAgAkcNACAFLwEAIAFHDQACQCAFIAZHDQBBAQ8LIABBemovAQAQICEECyAEC0wBA39BACEDAkAgAEF+aiIEQQAoApAIIgVJDQAgAC8BACACRw0AIAQvAQAgAUcNAAJAIAQgBUcNAEEBDwsgAEF8ai8BABAgIQMLIAMLSwEDf0EAIQcCQCAAQXZqIghBACgCkAgiCUkNACAIIAEgAiADIAQgBSAGEC9FDQACQCAIIAlHDQBBAQ8LIABBdGovAQAQICEHCyAHC2YBA39BACEFAkAgAEF6aiIGQQAoApAIIgdJDQAgAC8BACAERw0AIABBfmovAQAgA0cNACAAQXxqLwEAIAJHDQAgBi8BACABRw0AAkAgBiAHRw0AQQEPCyAAQXhqLwEAECAhBQsgBQs9AQJ/QQAhAgJAQQAoApAIIgMgAEsNACAALwEAIAFHDQACQCADIABHDQBBAQ8LIABBfmovAQAQICECCyACC00BA39BACEIAkAgAEF0aiIJQQAoApAIIgpJDQAgCSABIAIgAyAEIAUgBiAHEDBFDQACQCAJIApHDQBBAQ8LIABBcmovAQAQICEICyAIC5wBAQN/QQAoAuQIIQECQANAAkACQCABLwEAIgJBL0cNAAJAIAEvAQIiAUEqRg0AIAFBL0cNBBARDAILIAAQEgwBCwJAAkAgAEUNACACQXdqIgFBF0sNAUEBIAF0QZ+AgARxRQ0BDAILIAIQKkUNAwwBCyACQaABRw0CC0EAQQAoAuQIIgNBAmoiATYC5AggA0EAKALoCEkNAAsLIAIL1wMBAX9BACgC5AghAgJAAkAgAUEiRg0AAkAgAUEnRw0AEB0MAgsQHw8LEBwLIAAgAkECakEAKALkCEEAKAKECBABQQBBACgC5AhBAmo2AuQIQQAQKCEAQQAoAuQIIQECQAJAIABB4QBHDQAgAUECakHzAEHzAEHlAEHyAEH0ABAUDQELQQAgAUF+ajYC5AgPC0EAIAFBDGo2AuQIAkBBARAoQfsARg0AQQAgATYC5AgPC0EAKALkCCICIQADQEEAIABBAmo2AuQIAkACQAJAQQEQKCIAQSJGDQAgAEEnRw0BEB1BAEEAKALkCEECajYC5AhBARAoIQAMAgsQHEEAQQAoAuQIQQJqNgLkCEEBECghAAwBCyAAECshAAsCQCAAQTpGDQBBACABNgLkCA8LQQBBACgC5AhBAmo2AuQIAkACQEEBECgiAEEiRg0AAkAgAEEnRw0AEB0MAgtBACABNgLkCA8LEBwLQQBBACgC5AhBAmo2AuQIAkACQEEBECgiAEEsRg0AIABB/QBGDQFBACABNgLkCA8LQQBBACgC5AhBAmo2AuQIQQEQKEH9AEYNAEEAKALkCCEADAELC0EAKAKkCCIBIAI2AhAgAUEAKALkCEECajYCDAswAQF/AkACQCAAQXdqIgFBF0sNAEEBIAF0QY2AgARxDQELIABBoAFGDQBBAA8LQQELbQECfwJAAkADQAJAIABB//8DcSIBQXdqIgJBF0sNAEEBIAJ0QZ+AgARxDQILIAFBoAFGDQEgACECIAEQLA0CQQAhAkEAQQAoAuQIIgBBAmo2AuQIIAAvAQIiAA0ADAILCyAAIQILIAJB//8DcQtoAQJ/QQEhAQJAAkAgAEFfaiICQQVLDQBBASACdEExcQ0BCyAAQfj/A3FBKEYNACAAQUZqQf//A3FBBkkNAAJAIABBpX9qIgJBA0sNACACQQFHDQELIABBhX9qQf//A3FBBEkhAQsgAQtgAQJ/AkBBACgC5AgiAi8BACIDQeEARw0AQQAgAkEEajYC5AhBARAoIQJBACgC5AghACACECsaQQAoAuQIIQFBARAoIQNBACgC5AghAgsCQCACIABGDQAgACABEAILIAMLiQEBBX9BACgC5AghAEEAKALoCCEBA38gAEECaiECAkACQCAAIAFPDQAgAi8BACIDQaR/aiIEQQFNDQEgAiEAIANBdmoiA0EDSw0CIAIhACADDgQAAgIAAAtBACACNgLkCBAfQQAPCwJAAkAgBA4CAQABC0EAIAI2AuQIQd0ADwsgAEEEaiEADAALC0kBAX9BACEHAkAgAC8BCiAGRw0AIAAvAQggBUcNACAALwEGIARHDQAgAC8BBCADRw0AIAAvAQIgAkcNACAALwEAIAFGIQcLIAcLUwEBf0EAIQgCQCAALwEMIAdHDQAgAC8BCiAGRw0AIAAvAQggBUcNACAALwEGIARHDQAgAC8BBCADRw0AIAAvAQIgAkcNACAALwEAIAFGIQgLIAgLCx8CAEGACAsCAAAAQYQICxABAAAAAgAAAAAEAABwOAAA","undefined"!=typeof Buffer?Buffer.from(E,"base64"):Uint8Array.from(atob(E),A=>A.charCodeAt(0)))).then(WebAssembly.instantiate).then(({exports:A})=>{C=A;});var E;
  30245. async function transformImportGlob(source, pos, importer, importIndex, root, normalizeUrl, preload = true) {
  30246. const isEager = source.slice(pos, pos + 21) === 'import.meta.globEager';
  30247. const isEagerDefault = isEager && source.slice(pos + 21, pos + 28) === 'Default';
  30248. const err = (msg) => {
  30249. const e = new Error(`Invalid glob import syntax: ${msg}`);
  30250. e.pos = pos;
  30251. return e;
  30252. };
  30253. importer = cleanUrl(importer);
  30254. const importerBasename = path__default.basename(importer);
  30255. let [pattern, endIndex] = lexGlobPattern(source, pos);
  30256. if (!pattern.startsWith('.') && !pattern.startsWith('/')) {
  30257. throw err(`pattern must start with "." or "/" (relative to project root)`);
  30258. }
  30259. let base;
  30260. let parentDepth = 0;
  30261. const isAbsolute = pattern.startsWith('/');
  30262. if (isAbsolute) {
  30263. base = path__default.resolve(root);
  30264. pattern = pattern.slice(1);
  30265. }
  30266. else {
  30267. base = path__default.dirname(importer);
  30268. while (pattern.startsWith('../')) {
  30269. pattern = pattern.slice(3);
  30270. base = path__default.resolve(base, '../');
  30271. parentDepth++;
  30272. }
  30273. if (pattern.startsWith('./')) {
  30274. pattern = pattern.slice(2);
  30275. }
  30276. }
  30277. const files = out.sync(pattern, {
  30278. cwd: base,
  30279. ignore: ['**/node_modules/**']
  30280. });
  30281. const imports = [];
  30282. let importsString = ``;
  30283. let entries = ``;
  30284. for (let i = 0; i < files.length; i++) {
  30285. // skip importer itself
  30286. if (files[i] === importerBasename)
  30287. continue;
  30288. const file = isAbsolute
  30289. ? `/${files[i]}`
  30290. : parentDepth
  30291. ? `${'../'.repeat(parentDepth)}${files[i]}`
  30292. : `./${files[i]}`;
  30293. let importee = file;
  30294. if (normalizeUrl) {
  30295. [importee] = await normalizeUrl(file, pos);
  30296. }
  30297. imports.push(importee);
  30298. const identifier = `__glob_${importIndex}_${i}`;
  30299. if (isEager) {
  30300. importsString += `import ${isEagerDefault ? `` : `* as `}${identifier} from ${JSON.stringify(importee)};`;
  30301. entries += ` ${JSON.stringify(file)}: ${identifier},`;
  30302. }
  30303. else {
  30304. let imp = `import(${JSON.stringify(importee)})`;
  30305. if (!normalizeUrl && preload) {
  30306. imp =
  30307. `(${isModernFlag}` +
  30308. `? ${preloadMethod}(()=>${imp},"${preloadMarker}")` +
  30309. `: ${imp})`;
  30310. }
  30311. entries += ` ${JSON.stringify(file)}: () => ${imp},`;
  30312. }
  30313. }
  30314. return {
  30315. imports,
  30316. importsString,
  30317. exp: `{${entries}}`,
  30318. endIndex,
  30319. isEager,
  30320. pattern,
  30321. base
  30322. };
  30323. }
  30324. function lexGlobPattern(code, pos) {
  30325. let state = 0 /* inCall */;
  30326. let pattern = '';
  30327. let i = code.indexOf(`(`, pos) + 1;
  30328. outer: for (; i < code.length; i++) {
  30329. const char = code.charAt(i);
  30330. switch (state) {
  30331. case 0 /* inCall */:
  30332. if (char === `'`) {
  30333. state = 1 /* inSingleQuoteString */;
  30334. }
  30335. else if (char === `"`) {
  30336. state = 2 /* inDoubleQuoteString */;
  30337. }
  30338. else if (char === '`') {
  30339. state = 3 /* inTemplateString */;
  30340. }
  30341. else if (/\s/.test(char)) {
  30342. continue;
  30343. }
  30344. else {
  30345. error$3(i);
  30346. }
  30347. break;
  30348. case 1 /* inSingleQuoteString */:
  30349. if (char === `'`) {
  30350. break outer;
  30351. }
  30352. else {
  30353. pattern += char;
  30354. }
  30355. break;
  30356. case 2 /* inDoubleQuoteString */:
  30357. if (char === `"`) {
  30358. break outer;
  30359. }
  30360. else {
  30361. pattern += char;
  30362. }
  30363. break;
  30364. case 3 /* inTemplateString */:
  30365. if (char === '`') {
  30366. break outer;
  30367. }
  30368. else {
  30369. pattern += char;
  30370. }
  30371. break;
  30372. default:
  30373. throw new Error('unknown import.meta.glob lexer state');
  30374. }
  30375. }
  30376. return [pattern, code.indexOf(`)`, i) + 1];
  30377. }
  30378. function error$3(pos) {
  30379. const err = new Error(`import.meta.glob() can only accept string literals.`);
  30380. err.pos = pos;
  30381. throw err;
  30382. }
  30383. /**
  30384. * A flag for injected helpers. This flag will be set to `false` if the output
  30385. * target is not native es - so that injected helper logic can be conditionally
  30386. * dropped.
  30387. */
  30388. const isModernFlag = `__VITE_IS_MODERN__`;
  30389. const preloadMethod = `__vitePreload`;
  30390. const preloadMarker = `__VITE_PRELOAD__`;
  30391. const preloadBaseMarker = `__VITE_PRELOAD_BASE__`;
  30392. const preloadHelperId = 'vite/preload-helper';
  30393. const preloadMarkerRE = new RegExp(`"${preloadMarker}"`, 'g');
  30394. /**
  30395. * Helper for preloading CSS and direct imports of async chunks in parallel to
  30396. * the async chunk itself.
  30397. */
  30398. function detectScriptRel() {
  30399. // @ts-ignore
  30400. const relList = document.createElement('link').relList;
  30401. // @ts-ignore
  30402. return relList && relList.supports && relList.supports('modulepreload')
  30403. ? 'modulepreload'
  30404. : 'preload';
  30405. }
  30406. function preload(baseModule, deps) {
  30407. // @ts-ignore
  30408. if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
  30409. return baseModule();
  30410. }
  30411. return Promise.all(deps.map((dep) => {
  30412. // @ts-ignore
  30413. dep = `${base}${dep}`;
  30414. // @ts-ignore
  30415. if (dep in seen)
  30416. return;
  30417. // @ts-ignore
  30418. seen[dep] = true;
  30419. const isCss = dep.endsWith('.css');
  30420. const cssSelector = isCss ? '[rel="stylesheet"]' : '';
  30421. // @ts-ignore check if the file is already preloaded by SSR markup
  30422. if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
  30423. return;
  30424. }
  30425. // @ts-ignore
  30426. const link = document.createElement('link');
  30427. // @ts-ignore
  30428. link.rel = isCss ? 'stylesheet' : scriptRel;
  30429. if (!isCss) {
  30430. link.as = 'script';
  30431. link.crossOrigin = '';
  30432. }
  30433. link.href = dep;
  30434. // @ts-ignore
  30435. document.head.appendChild(link);
  30436. if (isCss) {
  30437. return new Promise((res, rej) => {
  30438. link.addEventListener('load', res);
  30439. link.addEventListener('error', rej);
  30440. });
  30441. }
  30442. })).then(() => baseModule());
  30443. }
  30444. /**
  30445. * Build only. During serve this is performed as part of ./importAnalysis.
  30446. */
  30447. function buildImportAnalysisPlugin(config) {
  30448. const ssr = !!config.build.ssr;
  30449. const insertPreload = !(ssr || !!config.build.lib);
  30450. const scriptRel = config.build.polyfillModulePreload
  30451. ? `'modulepreload'`
  30452. : `(${detectScriptRel.toString()})()`;
  30453. const preloadCode = `const scriptRel = ${scriptRel};const seen = {};const base = '${preloadBaseMarker}';export const ${preloadMethod} = ${preload.toString()}`;
  30454. return {
  30455. name: 'vite:import-analysis',
  30456. resolveId(id) {
  30457. if (id === preloadHelperId) {
  30458. return id;
  30459. }
  30460. },
  30461. load(id) {
  30462. if (id === preloadHelperId) {
  30463. return preloadCode.replace(preloadBaseMarker, config.base);
  30464. }
  30465. },
  30466. async transform(source, importer) {
  30467. if (importer.includes('node_modules') &&
  30468. !source.includes('import.meta.glob')) {
  30469. return;
  30470. }
  30471. await init;
  30472. let imports = [];
  30473. try {
  30474. imports = parse$d(source)[0];
  30475. }
  30476. catch (e) {
  30477. this.error(e, e.idx);
  30478. }
  30479. if (!imports.length) {
  30480. return null;
  30481. }
  30482. let s;
  30483. const str = () => s || (s = new MagicString(source));
  30484. let needPreloadHelper = false;
  30485. for (let index = 0; index < imports.length; index++) {
  30486. const { s: start, e: end, ss: expStart, d: dynamicIndex } = imports[index];
  30487. const isGlob = source.slice(start, end) === 'import.meta' &&
  30488. source.slice(end, end + 5) === '.glob';
  30489. // import.meta.glob
  30490. if (isGlob) {
  30491. const { importsString, exp, endIndex, isEager } = await transformImportGlob(source, start, importer, index, config.root, undefined, insertPreload);
  30492. str().prepend(importsString);
  30493. str().overwrite(expStart, endIndex, exp);
  30494. if (!isEager) {
  30495. needPreloadHelper = true;
  30496. }
  30497. continue;
  30498. }
  30499. if (dynamicIndex > -1 && insertPreload) {
  30500. needPreloadHelper = true;
  30501. const dynamicEnd = source.indexOf(`)`, end) + 1;
  30502. const original = source.slice(dynamicIndex, dynamicEnd);
  30503. const replacement = `${preloadMethod}(() => ${original},${isModernFlag}?"${preloadMarker}":void 0)`;
  30504. str().overwrite(dynamicIndex, dynamicEnd, replacement);
  30505. }
  30506. }
  30507. if (needPreloadHelper &&
  30508. insertPreload &&
  30509. !source.includes(`const ${preloadMethod} =`)) {
  30510. str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`);
  30511. }
  30512. if (s) {
  30513. return {
  30514. code: s.toString(),
  30515. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
  30516. };
  30517. }
  30518. },
  30519. renderChunk(code, _, { format }) {
  30520. // make sure we only perform the preload logic in modern builds.
  30521. if (code.indexOf(isModernFlag) > -1) {
  30522. const re = new RegExp(isModernFlag, 'g');
  30523. const isModern = String(format === 'es');
  30524. if (config.build.sourcemap) {
  30525. const s = new MagicString(code);
  30526. let match;
  30527. while ((match = re.exec(code))) {
  30528. s.overwrite(match.index, match.index + isModernFlag.length, isModern);
  30529. }
  30530. return {
  30531. code: s.toString(),
  30532. map: s.generateMap({ hires: true })
  30533. };
  30534. }
  30535. else {
  30536. return code.replace(re, isModern);
  30537. }
  30538. }
  30539. return null;
  30540. },
  30541. generateBundle({ format }, bundle) {
  30542. if (format !== 'es' || ssr) {
  30543. return;
  30544. }
  30545. for (const file in bundle) {
  30546. const chunk = bundle[file];
  30547. // can't use chunk.dynamicImports.length here since some modules e.g.
  30548. // dynamic import to constant json may get inlined.
  30549. if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) {
  30550. const code = chunk.code;
  30551. let imports;
  30552. try {
  30553. imports = parse$d(code)[0].filter((i) => i.d > -1);
  30554. }
  30555. catch (e) {
  30556. this.error(e, e.idx);
  30557. }
  30558. if (imports.length) {
  30559. const s = new MagicString(code);
  30560. for (let index = 0; index < imports.length; index++) {
  30561. const { s: start, e: end, d: dynamicIndex } = imports[index];
  30562. // check the chunk being imported
  30563. const url = code.slice(start, end);
  30564. const deps = new Set();
  30565. let hasRemovedPureCssChunk = false;
  30566. if (url[0] === `"` && url[url.length - 1] === `"`) {
  30567. const ownerFilename = chunk.fileName;
  30568. // literal import - trace direct imports and add to deps
  30569. const analyzed = new Set();
  30570. const addDeps = (filename) => {
  30571. if (filename === ownerFilename)
  30572. return;
  30573. if (analyzed.has(filename))
  30574. return;
  30575. analyzed.add(filename);
  30576. const chunk = bundle[filename];
  30577. if (chunk) {
  30578. deps.add(chunk.fileName);
  30579. const cssFiles = chunkToEmittedCssFileMap.get(chunk);
  30580. if (cssFiles) {
  30581. cssFiles.forEach((file) => {
  30582. deps.add(file);
  30583. });
  30584. }
  30585. chunk.imports.forEach(addDeps);
  30586. }
  30587. else {
  30588. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  30589. const chunk = removedPureCssFiles.get(filename);
  30590. if (chunk) {
  30591. const cssFiles = chunkToEmittedCssFileMap.get(chunk);
  30592. if (cssFiles && cssFiles.size > 0) {
  30593. cssFiles.forEach((file) => {
  30594. deps.add(config.base + file);
  30595. });
  30596. hasRemovedPureCssChunk = true;
  30597. }
  30598. s.overwrite(dynamicIndex, end + 1, 'Promise.resolve({})');
  30599. }
  30600. }
  30601. };
  30602. const normalizedFile = path__default.posix.join(path__default.posix.dirname(chunk.fileName), url.slice(1, -1));
  30603. addDeps(normalizedFile);
  30604. }
  30605. let markPos = code.indexOf(preloadMarker, end);
  30606. // fix issue #3051
  30607. if (markPos === -1 && imports.length === 1) {
  30608. markPos = code.indexOf(preloadMarker);
  30609. }
  30610. if (markPos > 0) {
  30611. s.overwrite(markPos - 1, markPos + preloadMarker.length + 1,
  30612. // the dep list includes the main chunk, so only need to
  30613. // preload when there are actual other deps.
  30614. deps.size > 1 ||
  30615. // main chunk is removed
  30616. (hasRemovedPureCssChunk && deps.size > 0)
  30617. ? `[${[...deps].map((d) => JSON.stringify(d)).join(',')}]`
  30618. : `[]`);
  30619. }
  30620. }
  30621. chunk.code = s.toString();
  30622. // TODO source map
  30623. }
  30624. // there may still be markers due to inlined dynamic imports, remove
  30625. // all the markers regardless
  30626. chunk.code = chunk.code.replace(preloadMarkerRE, 'void 0');
  30627. }
  30628. }
  30629. }
  30630. };
  30631. }
  30632. const modulePreloadPolyfillId = 'vite/modulepreload-polyfill';
  30633. function modulePreloadPolyfillPlugin(config) {
  30634. const skip = config.build.ssr;
  30635. let polyfillString;
  30636. return {
  30637. name: 'vite:modulepreload-polyfill',
  30638. resolveId(id) {
  30639. if (id === modulePreloadPolyfillId) {
  30640. return id;
  30641. }
  30642. },
  30643. load(id) {
  30644. if (id === modulePreloadPolyfillId) {
  30645. if (skip) {
  30646. return '';
  30647. }
  30648. if (!polyfillString) {
  30649. polyfillString =
  30650. `const p = ${polyfill.toString()};` + `${isModernFlag}&&p();`;
  30651. }
  30652. return polyfillString;
  30653. }
  30654. }
  30655. };
  30656. }
  30657. function polyfill() {
  30658. const relList = document.createElement('link').relList;
  30659. if (relList && relList.supports && relList.supports('modulepreload')) {
  30660. return;
  30661. }
  30662. for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
  30663. processPreload(link);
  30664. }
  30665. new MutationObserver((mutations) => {
  30666. for (const mutation of mutations) {
  30667. if (mutation.type !== 'childList') {
  30668. continue;
  30669. }
  30670. for (const node of mutation.addedNodes) {
  30671. if (node.tagName === 'LINK' && node.rel === 'modulepreload')
  30672. processPreload(node);
  30673. }
  30674. }
  30675. }).observe(document, { childList: true, subtree: true });
  30676. function getFetchOpts(script) {
  30677. const fetchOpts = {};
  30678. if (script.integrity)
  30679. fetchOpts.integrity = script.integrity;
  30680. if (script.referrerpolicy)
  30681. fetchOpts.referrerPolicy = script.referrerpolicy;
  30682. if (script.crossorigin === 'use-credentials')
  30683. fetchOpts.credentials = 'include';
  30684. else if (script.crossorigin === 'anonymous')
  30685. fetchOpts.credentials = 'omit';
  30686. else
  30687. fetchOpts.credentials = 'same-origin';
  30688. return fetchOpts;
  30689. }
  30690. function processPreload(link) {
  30691. if (link.ep)
  30692. // ep marker = processed
  30693. return;
  30694. link.ep = true;
  30695. // prepopulate the load record
  30696. const fetchOpts = getFetchOpts(link);
  30697. fetch(link.href, fetchOpts);
  30698. }
  30699. }
  30700. const htmlProxyRE = /\?html-proxy&index=(\d+)\.js$/;
  30701. const isHTMLProxy = (id) => htmlProxyRE.test(id);
  30702. const htmlCommentRE = /<!--[\s\S]*?-->/g;
  30703. const scriptModuleRE$1 = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)(.*?)<\/script>/gims;
  30704. function htmlInlineScriptProxyPlugin() {
  30705. return {
  30706. name: 'vite:html',
  30707. resolveId(id) {
  30708. if (htmlProxyRE.test(id)) {
  30709. return id;
  30710. }
  30711. },
  30712. load(id) {
  30713. const proxyMatch = id.match(htmlProxyRE);
  30714. if (proxyMatch) {
  30715. const index = Number(proxyMatch[1]);
  30716. const file = cleanUrl(id);
  30717. const html = fs__default.readFileSync(file, 'utf-8').replace(htmlCommentRE, '');
  30718. let match;
  30719. scriptModuleRE$1.lastIndex = 0;
  30720. for (let i = 0; i <= index; i++) {
  30721. match = scriptModuleRE$1.exec(html);
  30722. }
  30723. if (match) {
  30724. return match[2];
  30725. }
  30726. else {
  30727. throw new Error(`No matching html proxy module found from ${id}`);
  30728. }
  30729. }
  30730. }
  30731. };
  30732. }
  30733. // this extends the config in @vue/compiler-sfc with <link href>
  30734. const assetAttrsConfig = {
  30735. link: ['href'],
  30736. video: ['src', 'poster'],
  30737. source: ['src', 'srcset'],
  30738. img: ['src', 'srcset'],
  30739. image: ['xlink:href', 'href'],
  30740. use: ['xlink:href', 'href']
  30741. };
  30742. async function traverseHtml(html, filePath, visitor) {
  30743. // lazy load compiler
  30744. const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-b541373d.js'); }).then(function (n) { return n.compilerDom_cjs; });
  30745. // @vue/compiler-core doesn't like lowercase doctypes
  30746. html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
  30747. try {
  30748. const ast = parse(html, { comments: true });
  30749. transform(ast, {
  30750. nodeTransforms: [visitor]
  30751. });
  30752. }
  30753. catch (e) {
  30754. const parseError = {
  30755. loc: filePath,
  30756. frame: '',
  30757. ...formatParseError(e, filePath, html)
  30758. };
  30759. throw new Error(`Unable to parse ${JSON.stringify(parseError.loc)}\n${parseError.frame}`);
  30760. }
  30761. }
  30762. function getScriptInfo(node) {
  30763. let src;
  30764. let isModule = false;
  30765. for (let i = 0; i < node.props.length; i++) {
  30766. const p = node.props[i];
  30767. if (p.type === 6 /* ATTRIBUTE */) {
  30768. if (p.name === 'src') {
  30769. src = p;
  30770. }
  30771. else if (p.name === 'type' && p.value && p.value.content === 'module') {
  30772. isModule = true;
  30773. }
  30774. }
  30775. }
  30776. return { src, isModule };
  30777. }
  30778. function formatParseError(e, id, html) {
  30779. // normalize the error to rollup format
  30780. if (e.loc) {
  30781. e.frame = generateCodeFrame(html, e.loc.start.offset);
  30782. e.loc = {
  30783. file: id,
  30784. line: e.loc.start.line,
  30785. column: e.loc.start.column
  30786. };
  30787. }
  30788. return e;
  30789. }
  30790. /**
  30791. * Compiles index.html into an entry js module
  30792. */
  30793. function buildHtmlPlugin(config) {
  30794. const [preHooks, postHooks] = resolveHtmlTransforms(config.plugins);
  30795. const processedHtml = new Map();
  30796. const isExcludedUrl = (url) => url.startsWith('#') ||
  30797. isExternalUrl(url) ||
  30798. isDataUrl(url) ||
  30799. checkPublicFile(url, config);
  30800. return {
  30801. name: 'vite:build-html',
  30802. async transform(html, id) {
  30803. if (id.endsWith('.html')) {
  30804. const publicPath = `/${slash$3(path__default.relative(config.root, id))}`;
  30805. // pre-transform
  30806. html = await applyHtmlTransforms(html, preHooks, {
  30807. path: publicPath,
  30808. filename: id
  30809. });
  30810. let js = '';
  30811. const s = new MagicString(html);
  30812. const assetUrls = [];
  30813. let inlineModuleIndex = -1;
  30814. await traverseHtml(html, id, (node) => {
  30815. if (node.type !== 1 /* ELEMENT */) {
  30816. return;
  30817. }
  30818. let shouldRemove = false;
  30819. // script tags
  30820. if (node.tag === 'script') {
  30821. const { src, isModule } = getScriptInfo(node);
  30822. const url = src && src.value && src.value.content;
  30823. if (url && checkPublicFile(url, config)) {
  30824. // referencing public dir url, prefix with base
  30825. s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${config.base + url.slice(1)}"`);
  30826. }
  30827. if (isModule) {
  30828. inlineModuleIndex++;
  30829. if (url && !isExcludedUrl(url)) {
  30830. // <script type="module" src="..."/>
  30831. // add it as an import
  30832. js += `\nimport ${JSON.stringify(url)}`;
  30833. shouldRemove = true;
  30834. }
  30835. else if (node.children.length) {
  30836. // <script type="module">...</script>
  30837. js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
  30838. shouldRemove = true;
  30839. }
  30840. }
  30841. }
  30842. // For asset references in index.html, also generate an import
  30843. // statement for each - this will be handled by the asset plugin
  30844. const assetAttrs = assetAttrsConfig[node.tag];
  30845. if (assetAttrs) {
  30846. for (const p of node.props) {
  30847. if (p.type === 6 /* ATTRIBUTE */ &&
  30848. p.value &&
  30849. assetAttrs.includes(p.name)) {
  30850. const url = p.value.content;
  30851. if (!isExcludedUrl(url)) {
  30852. if (node.tag === 'link' && isCSSRequest(url)) {
  30853. // CSS references, convert to import
  30854. js += `\nimport ${JSON.stringify(url)}`;
  30855. shouldRemove = true;
  30856. }
  30857. else {
  30858. assetUrls.push(p);
  30859. }
  30860. }
  30861. else if (checkPublicFile(url, config)) {
  30862. s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`);
  30863. }
  30864. }
  30865. }
  30866. }
  30867. if (shouldRemove) {
  30868. // remove the script tag from the html. we are going to inject new
  30869. // ones in the end.
  30870. s.remove(node.loc.start.offset, node.loc.end.offset);
  30871. }
  30872. });
  30873. // for each encountered asset url, rewrite original html so that it
  30874. // references the post-build location.
  30875. for (const attr of assetUrls) {
  30876. const value = attr.value;
  30877. try {
  30878. const url = attr.name === 'srcset'
  30879. ? await processSrcSet(value.content, ({ url }) => urlToBuiltUrl(url, id, config, this))
  30880. : await urlToBuiltUrl(value.content, id, config, this);
  30881. s.overwrite(value.loc.start.offset, value.loc.end.offset, `"${url}"`);
  30882. }
  30883. catch (e) {
  30884. // #1885 preload may be pointing to urls that do not exist
  30885. // locally on disk
  30886. if (e.code !== 'ENOENT') {
  30887. throw e;
  30888. }
  30889. }
  30890. }
  30891. processedHtml.set(id, s.toString());
  30892. // inject module preload polyfill
  30893. if (config.build.polyfillModulePreload) {
  30894. js = `import "${modulePreloadPolyfillId}";\n${js}`;
  30895. }
  30896. return js;
  30897. }
  30898. },
  30899. async generateBundle(_, bundle) {
  30900. const analyzedChunk = new Map();
  30901. const getPreloadLinksForChunk = (chunk, seen = new Set()) => {
  30902. const tags = [];
  30903. chunk.imports.forEach((file) => {
  30904. const importee = bundle[file];
  30905. if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk' && !seen.has(file)) {
  30906. seen.add(file);
  30907. tags.push({
  30908. tag: 'link',
  30909. attrs: {
  30910. rel: 'modulepreload',
  30911. href: toPublicPath(file, config)
  30912. }
  30913. });
  30914. tags.push(...getPreloadLinksForChunk(importee, seen));
  30915. }
  30916. });
  30917. return tags;
  30918. };
  30919. const getCssTagsForChunk = (chunk, seen = new Set()) => {
  30920. const tags = [];
  30921. if (!analyzedChunk.has(chunk)) {
  30922. analyzedChunk.set(chunk, 1);
  30923. chunk.imports.forEach((file) => {
  30924. const importee = bundle[file];
  30925. if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk') {
  30926. tags.push(...getCssTagsForChunk(importee, seen));
  30927. }
  30928. });
  30929. }
  30930. const cssFiles = chunkToEmittedCssFileMap.get(chunk);
  30931. if (cssFiles) {
  30932. cssFiles.forEach((file) => {
  30933. if (!seen.has(file)) {
  30934. seen.add(file);
  30935. tags.push({
  30936. tag: 'link',
  30937. attrs: {
  30938. rel: 'stylesheet',
  30939. href: toPublicPath(file, config)
  30940. }
  30941. });
  30942. }
  30943. });
  30944. }
  30945. return tags;
  30946. };
  30947. for (const [id, html] of processedHtml) {
  30948. // resolve asset url references
  30949. let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => {
  30950. return config.base + getAssetFilename(fileHash, config) + postfix;
  30951. });
  30952. // find corresponding entry chunk
  30953. const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' &&
  30954. chunk.isEntry &&
  30955. chunk.facadeModuleId === id);
  30956. // inject chunk asset links
  30957. if (chunk) {
  30958. const assetTags = [
  30959. // js entry chunk for this page
  30960. {
  30961. tag: 'script',
  30962. attrs: {
  30963. type: 'module',
  30964. crossorigin: true,
  30965. src: toPublicPath(chunk.fileName, config)
  30966. }
  30967. },
  30968. // preload for imports
  30969. ...getPreloadLinksForChunk(chunk),
  30970. ...getCssTagsForChunk(chunk)
  30971. ];
  30972. result = injectToHead(result, assetTags);
  30973. }
  30974. // inject css link when cssCodeSplit is false
  30975. if (!config.build.cssCodeSplit) {
  30976. const cssChunk = Object.values(bundle).find((chunk) => chunk.type === 'asset' && chunk.name === 'style.css');
  30977. if (cssChunk) {
  30978. result = injectToHead(result, [
  30979. {
  30980. tag: 'link',
  30981. attrs: {
  30982. rel: 'stylesheet',
  30983. href: toPublicPath(cssChunk.fileName, config)
  30984. }
  30985. }
  30986. ]);
  30987. }
  30988. }
  30989. const shortEmitName = path__default.posix.relative(config.root, id);
  30990. result = await applyHtmlTransforms(result, postHooks, {
  30991. path: '/' + shortEmitName,
  30992. filename: id,
  30993. bundle,
  30994. chunk
  30995. });
  30996. this.emitFile({
  30997. type: 'asset',
  30998. fileName: shortEmitName,
  30999. source: result
  31000. });
  31001. }
  31002. }
  31003. };
  31004. }
  31005. function resolveHtmlTransforms(plugins) {
  31006. const preHooks = [];
  31007. const postHooks = [];
  31008. for (const plugin of plugins) {
  31009. const hook = plugin.transformIndexHtml;
  31010. if (hook) {
  31011. if (typeof hook === 'function') {
  31012. postHooks.push(hook);
  31013. }
  31014. else if (hook.enforce === 'pre') {
  31015. preHooks.push(hook.transform);
  31016. }
  31017. else {
  31018. postHooks.push(hook.transform);
  31019. }
  31020. }
  31021. }
  31022. return [preHooks, postHooks];
  31023. }
  31024. async function applyHtmlTransforms(html, hooks, ctx) {
  31025. const headTags = [];
  31026. const headPrependTags = [];
  31027. const bodyTags = [];
  31028. const bodyPrependTags = [];
  31029. for (const hook of hooks) {
  31030. const res = await hook(html, ctx);
  31031. if (!res) {
  31032. continue;
  31033. }
  31034. if (typeof res === 'string') {
  31035. html = res;
  31036. }
  31037. else {
  31038. let tags;
  31039. if (Array.isArray(res)) {
  31040. tags = res;
  31041. }
  31042. else {
  31043. html = res.html || html;
  31044. tags = res.tags;
  31045. }
  31046. for (const tag of tags) {
  31047. if (tag.injectTo === 'body') {
  31048. bodyTags.push(tag);
  31049. }
  31050. else if (tag.injectTo === 'body-prepend') {
  31051. bodyPrependTags.push(tag);
  31052. }
  31053. else if (tag.injectTo === 'head') {
  31054. headTags.push(tag);
  31055. }
  31056. else {
  31057. headPrependTags.push(tag);
  31058. }
  31059. }
  31060. }
  31061. }
  31062. // inject tags
  31063. if (headPrependTags.length) {
  31064. html = injectToHead(html, headPrependTags, true);
  31065. }
  31066. if (headTags.length) {
  31067. html = injectToHead(html, headTags);
  31068. }
  31069. if (bodyPrependTags.length) {
  31070. html = injectToBody(html, bodyPrependTags, true);
  31071. }
  31072. if (bodyTags.length) {
  31073. html = injectToBody(html, bodyTags);
  31074. }
  31075. return html;
  31076. }
  31077. function toPublicPath(filename, config) {
  31078. return isExternalUrl(filename) ? filename : config.base + filename;
  31079. }
  31080. const headInjectRE = /<\/head>/;
  31081. const headPrependInjectRE = [/<head>/, /<!doctype html>/i];
  31082. function injectToHead(html, tags, prepend = false) {
  31083. const tagsHtml = serializeTags(tags);
  31084. if (prepend) {
  31085. // inject after head or doctype
  31086. for (const re of headPrependInjectRE) {
  31087. if (re.test(html)) {
  31088. return html.replace(re, `$&\n${tagsHtml}`);
  31089. }
  31090. }
  31091. }
  31092. else {
  31093. // inject before head close
  31094. if (headInjectRE.test(html)) {
  31095. return html.replace(headInjectRE, `${tagsHtml}\n $&`);
  31096. }
  31097. }
  31098. // if no <head> tag is present, just prepend
  31099. return tagsHtml + `\n` + html;
  31100. }
  31101. const bodyInjectRE = /<\/body>/;
  31102. const bodyPrependInjectRE = /<body[^>]*>/;
  31103. function injectToBody(html, tags, prepend = false) {
  31104. if (prepend) {
  31105. // inject after body open
  31106. const tagsHtml = `\n` + serializeTags(tags);
  31107. if (bodyPrependInjectRE.test(html)) {
  31108. return html.replace(bodyPrependInjectRE, `$&\n${tagsHtml}`);
  31109. }
  31110. // if no body, prepend
  31111. return tagsHtml + `\n` + html;
  31112. }
  31113. else {
  31114. // inject before body close
  31115. const tagsHtml = `\n` + serializeTags(tags);
  31116. if (bodyInjectRE.test(html)) {
  31117. return html.replace(bodyInjectRE, `${tagsHtml}\n$&`);
  31118. }
  31119. // if no body, append
  31120. return html + `\n` + tagsHtml;
  31121. }
  31122. }
  31123. const unaryTags = new Set(['link', 'meta', 'base']);
  31124. function serializeTag({ tag, attrs, children }) {
  31125. if (unaryTags.has(tag)) {
  31126. return `<${tag}${serializeAttrs(attrs)}>`;
  31127. }
  31128. else {
  31129. return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children)}</${tag}>`;
  31130. }
  31131. }
  31132. function serializeTags(tags) {
  31133. if (typeof tags === 'string') {
  31134. return tags;
  31135. }
  31136. else if (tags) {
  31137. return ` ${tags.map(serializeTag).join('\n ')}`;
  31138. }
  31139. return '';
  31140. }
  31141. function serializeAttrs(attrs) {
  31142. let res = '';
  31143. for (const key in attrs) {
  31144. if (typeof attrs[key] === 'boolean') {
  31145. res += attrs[key] ? ` ${key}` : ``;
  31146. }
  31147. else {
  31148. res += ` ${key}=${JSON.stringify(attrs[key])}`;
  31149. }
  31150. }
  31151. return res;
  31152. }
  31153. var stripBom = string => {
  31154. if (typeof string !== 'string') {
  31155. throw new TypeError(`Expected a string, got ${typeof string}`);
  31156. }
  31157. // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
  31158. // conversion translates it to FEFF (UTF-16 BOM)
  31159. if (string.charCodeAt(0) === 0xFEFF) {
  31160. return string.slice(1);
  31161. }
  31162. return string;
  31163. };
  31164. const singleComment = Symbol('singleComment');
  31165. const multiComment = Symbol('multiComment');
  31166. const stripWithoutWhitespace = () => '';
  31167. const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' ');
  31168. const isEscaped = (jsonString, quotePosition) => {
  31169. let index = quotePosition - 1;
  31170. let backslashCount = 0;
  31171. while (jsonString[index] === '\\') {
  31172. index -= 1;
  31173. backslashCount += 1;
  31174. }
  31175. return Boolean(backslashCount % 2);
  31176. };
  31177. var stripJsonComments = (jsonString, options = {}) => {
  31178. if (typeof jsonString !== 'string') {
  31179. throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``);
  31180. }
  31181. const strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
  31182. let insideString = false;
  31183. let insideComment = false;
  31184. let offset = 0;
  31185. let result = '';
  31186. for (let i = 0; i < jsonString.length; i++) {
  31187. const currentCharacter = jsonString[i];
  31188. const nextCharacter = jsonString[i + 1];
  31189. if (!insideComment && currentCharacter === '"') {
  31190. const escaped = isEscaped(jsonString, i);
  31191. if (!escaped) {
  31192. insideString = !insideString;
  31193. }
  31194. }
  31195. if (insideString) {
  31196. continue;
  31197. }
  31198. if (!insideComment && currentCharacter + nextCharacter === '//') {
  31199. result += jsonString.slice(offset, i);
  31200. offset = i;
  31201. insideComment = singleComment;
  31202. i++;
  31203. } else if (insideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
  31204. i++;
  31205. insideComment = false;
  31206. result += strip(jsonString, offset, i);
  31207. offset = i;
  31208. continue;
  31209. } else if (insideComment === singleComment && currentCharacter === '\n') {
  31210. insideComment = false;
  31211. result += strip(jsonString, offset, i);
  31212. offset = i;
  31213. } else if (!insideComment && currentCharacter + nextCharacter === '/*') {
  31214. result += jsonString.slice(offset, i);
  31215. offset = i;
  31216. insideComment = multiComment;
  31217. i++;
  31218. continue;
  31219. } else if (insideComment === multiComment && currentCharacter + nextCharacter === '*/') {
  31220. i++;
  31221. insideComment = false;
  31222. result += strip(jsonString, offset, i + 1);
  31223. offset = i + 1;
  31224. continue;
  31225. }
  31226. }
  31227. return result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
  31228. };
  31229. const debug$c = createDebugger('vite:esbuild');
  31230. async function transformWithEsbuild(code, filename, options, inMap) {
  31231. var _a, _b, _c;
  31232. // if the id ends with a valid ext, use it (e.g. vue blocks)
  31233. // otherwise, cleanup the query before checking the ext
  31234. const ext = path__default.extname(/\.\w+$/.test(filename) ? filename : cleanUrl(filename));
  31235. let loader = ext.slice(1);
  31236. if (loader === 'cjs' || loader === 'mjs') {
  31237. loader = 'js';
  31238. }
  31239. // these fields would affect the compilation result
  31240. // https://esbuild.github.io/content-types/#tsconfig-json
  31241. const meaningfulFields = [
  31242. 'jsxFactory',
  31243. 'jsxFragmentFactory',
  31244. 'useDefineForClassFields',
  31245. 'importsNotUsedAsValues'
  31246. ];
  31247. const compilerOptionsForFile = {};
  31248. if (loader === 'ts' || loader === 'tsx') {
  31249. const loadedTsconfig = await loadTsconfigJsonForFile(filename);
  31250. const loadedCompilerOptions = (_a = loadedTsconfig.compilerOptions) !== null && _a !== void 0 ? _a : {};
  31251. for (const field of meaningfulFields) {
  31252. if (field in loadedCompilerOptions) {
  31253. // @ts-ignore TypeScript can't tell they are of the same type
  31254. compilerOptionsForFile[field] = loadedCompilerOptions[field];
  31255. }
  31256. }
  31257. // align with TypeScript 4.3
  31258. // https://github.com/microsoft/TypeScript/pull/42663
  31259. if (((_b = loadedCompilerOptions.target) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'esnext') {
  31260. compilerOptionsForFile.useDefineForClassFields =
  31261. (_c = loadedCompilerOptions.useDefineForClassFields) !== null && _c !== void 0 ? _c : true;
  31262. }
  31263. }
  31264. const resolvedOptions = {
  31265. loader: loader,
  31266. sourcemap: true,
  31267. // ensure source file name contains full query
  31268. sourcefile: filename,
  31269. tsconfigRaw: { compilerOptions: compilerOptionsForFile },
  31270. ...options
  31271. };
  31272. delete resolvedOptions.include;
  31273. delete resolvedOptions.exclude;
  31274. delete resolvedOptions.jsxInject;
  31275. try {
  31276. const result = await esbuild.transform(code, resolvedOptions);
  31277. if (inMap) {
  31278. const nextMap = JSON.parse(result.map);
  31279. nextMap.sourcesContent = [];
  31280. return {
  31281. ...result,
  31282. map: combineSourcemaps(filename, [
  31283. nextMap,
  31284. inMap
  31285. ])
  31286. };
  31287. }
  31288. else {
  31289. return {
  31290. ...result,
  31291. map: JSON.parse(result.map)
  31292. };
  31293. }
  31294. }
  31295. catch (e) {
  31296. debug$c(`esbuild error with options used: `, resolvedOptions);
  31297. // patch error information
  31298. if (e.errors) {
  31299. e.frame = '';
  31300. e.errors.forEach((m) => {
  31301. e.frame += `\n` + prettifyMessage(m, code);
  31302. });
  31303. e.loc = e.errors[0].location;
  31304. }
  31305. throw e;
  31306. }
  31307. }
  31308. function esbuildPlugin(options = {}) {
  31309. const filter = createFilter$1(options.include || /\.(tsx?|jsx)$/, options.exclude || /\.js$/);
  31310. return {
  31311. name: 'vite:esbuild',
  31312. async transform(code, id) {
  31313. if (filter(id) || filter(cleanUrl(id))) {
  31314. const result = await transformWithEsbuild(code, id, options);
  31315. if (result.warnings.length) {
  31316. result.warnings.forEach((m) => {
  31317. this.warn(prettifyMessage(m, code));
  31318. });
  31319. }
  31320. if (options.jsxInject && /\.(?:j|t)sx\b/.test(id)) {
  31321. result.code = options.jsxInject + ';' + result.code;
  31322. }
  31323. return {
  31324. code: result.code,
  31325. map: result.map
  31326. };
  31327. }
  31328. }
  31329. };
  31330. }
  31331. const buildEsbuildPlugin = (config) => {
  31332. return {
  31333. name: 'vite:esbuild-transpile',
  31334. async renderChunk(code, chunk, opts) {
  31335. // @ts-ignore injected by @vitejs/plugin-legacy
  31336. if (opts.__vite_skip_esbuild__) {
  31337. return null;
  31338. }
  31339. const target = config.build.target;
  31340. const minify = config.build.minify === 'esbuild';
  31341. if ((!target || target === 'esnext') && !minify) {
  31342. return null;
  31343. }
  31344. return transformWithEsbuild(code, chunk.fileName, {
  31345. target: target || undefined,
  31346. minify
  31347. });
  31348. }
  31349. };
  31350. };
  31351. function prettifyMessage(m, code) {
  31352. let res = source.yellow(m.text);
  31353. if (m.location) {
  31354. const lines = code.split(/\r?\n/g);
  31355. const line = Number(m.location.line);
  31356. const column = Number(m.location.column);
  31357. const offset = lines
  31358. .slice(0, line - 1)
  31359. .map((l) => l.length)
  31360. .reduce((total, l) => total + l + 1, 0) + column;
  31361. res += `\n` + generateCodeFrame(code, offset, offset + 1);
  31362. }
  31363. return res + `\n`;
  31364. }
  31365. // modified from <https://github.com/TypeStrong/tsconfig/blob/v7.0.0/src/tsconfig.ts#L75-L95>
  31366. /**
  31367. * Copyright (c) 2015 TypeStrong
  31368. *
  31369. * Permission is hereby granted, free of charge, to any person obtaining a copy
  31370. * of this software and associated documentation files (the "Software"), to deal
  31371. * in the Software without restriction, including without limitation the rights
  31372. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  31373. * copies of the Software, and to permit persons to whom the Software is
  31374. * furnished to do so, subject to the following conditions:
  31375. *
  31376. * The above copyright notice and this permission notice shall be included in all
  31377. * copies or substantial portions of the Software.
  31378. *
  31379. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  31380. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31381. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  31382. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31383. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  31384. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  31385. * SOFTWARE.
  31386. */
  31387. async function findTSConfig(dir) {
  31388. const configFile = path__default.resolve(dir, 'tsconfig.json');
  31389. const stats = await stat$4(configFile);
  31390. if (isFile(stats)) {
  31391. return configFile;
  31392. }
  31393. const parentDir = path__default.dirname(dir);
  31394. if (dir === parentDir) {
  31395. return;
  31396. }
  31397. return findTSConfig(parentDir);
  31398. }
  31399. /**
  31400. * Check if a file exists.
  31401. */
  31402. function stat$4(filename) {
  31403. return new Promise((resolve, reject) => {
  31404. fs__default.stat(filename, (err, stats) => {
  31405. return err ? resolve() : resolve(stats);
  31406. });
  31407. });
  31408. }
  31409. /**
  31410. * Check filesystem stat is a directory.
  31411. */
  31412. function isFile(stats) {
  31413. return stats ? stats.isFile() || stats.isFIFO() : false;
  31414. }
  31415. // from <https://github.com/TypeStrong/tsconfig/pull/31>
  31416. // by @dominikg
  31417. /**
  31418. * replace dangling commas from pseudo-json string with single space
  31419. *
  31420. * limitations:
  31421. * - pseudo-json must not contain comments, use strip-json-comments before
  31422. * - only a single dangling comma before } or ] is removed
  31423. * stripDanglingComma('[1,2,]') === '[1,2 ]
  31424. * stripDanglingComma('[1,2,,]') === '[1,2, ]
  31425. *
  31426. * implementation heavily inspired by strip-json-comments
  31427. */
  31428. function stripDanglingComma(jsonString) {
  31429. /**
  31430. * Check if char at qoutePosition is escaped by an odd number of backslashes preceding it
  31431. */
  31432. function isEscaped(jsonString, quotePosition) {
  31433. let index = quotePosition - 1;
  31434. let backslashCount = 0;
  31435. while (jsonString[index] === '\\') {
  31436. index -= 1;
  31437. backslashCount += 1;
  31438. }
  31439. return backslashCount % 2 === 1;
  31440. }
  31441. let insideString = false;
  31442. let offset = 0;
  31443. let result = '';
  31444. let danglingCommaPos = null;
  31445. for (let i = 0; i < jsonString.length; i++) {
  31446. const currentCharacter = jsonString[i];
  31447. if (currentCharacter === '"') {
  31448. const escaped = isEscaped(jsonString, i);
  31449. if (!escaped) {
  31450. insideString = !insideString;
  31451. }
  31452. }
  31453. if (insideString) {
  31454. danglingCommaPos = null;
  31455. continue;
  31456. }
  31457. if (currentCharacter === ',') {
  31458. danglingCommaPos = i;
  31459. continue;
  31460. }
  31461. if (danglingCommaPos) {
  31462. if (currentCharacter === '}' || currentCharacter === ']') {
  31463. result += jsonString.slice(offset, danglingCommaPos) + ' ';
  31464. offset = danglingCommaPos + 1;
  31465. danglingCommaPos = null;
  31466. }
  31467. else if (!currentCharacter.match(/\s/)) {
  31468. danglingCommaPos = null;
  31469. }
  31470. }
  31471. }
  31472. return result + jsonString.substring(offset);
  31473. }
  31474. async function readTSConfig(configPath) {
  31475. const content = await new Promise((resolve, reject) => {
  31476. fs__default.readFile(configPath, 'utf-8', (err, data) => {
  31477. if (err) {
  31478. reject(err);
  31479. return;
  31480. }
  31481. resolve(stripJsonComments(stripBom(data)));
  31482. });
  31483. });
  31484. // tsconfig.json can be empty
  31485. if (/^\s*$/.test(content)) {
  31486. return {};
  31487. }
  31488. return JSON.parse(stripDanglingComma(content));
  31489. }
  31490. const tsconfigCache = new Map();
  31491. async function loadTsconfigJsonForFile(filename) {
  31492. const directory = path__default.dirname(filename);
  31493. const cached = tsconfigCache.get(directory);
  31494. if (cached) {
  31495. return cached;
  31496. }
  31497. let configPath = await findTSConfig(directory);
  31498. let tsconfig = {};
  31499. if (configPath) {
  31500. const visited = new Set();
  31501. visited.add(configPath);
  31502. tsconfig = await readTSConfig(configPath);
  31503. while (tsconfig.extends) {
  31504. const configRequire = require$$0$9.createRequire(configPath);
  31505. const extendsPath = configRequire.resolve(tsconfig.extends);
  31506. const extendedConfig = await readTSConfig(extendsPath);
  31507. if (visited.has(extendsPath)) {
  31508. throw new Error(`Circular dependency detected in the "extends" field of ${configPath}`);
  31509. }
  31510. visited.add(extendsPath);
  31511. tsconfig = {
  31512. extends: extendedConfig.extends,
  31513. compilerOptions: {
  31514. ...extendedConfig.compilerOptions,
  31515. ...tsconfig.compilerOptions
  31516. }
  31517. };
  31518. configPath = extendsPath;
  31519. }
  31520. }
  31521. tsconfigCache.set(directory, tsconfig);
  31522. return tsconfig;
  31523. }
  31524. var dist = {};
  31525. var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  31526. return (mod && mod.__esModule) ? mod : { "default": mod };
  31527. };
  31528. Object.defineProperty(dist, "__esModule", { value: true });
  31529. var Worker_1 = dist.Worker = void 0;
  31530. const os_1 = __importDefault(require$$0__default$1);
  31531. const worker_threads_1 = require$$1__default;
  31532. class Worker {
  31533. constructor(fn, options = {}) {
  31534. this.code = genWorkerCode(fn);
  31535. this.max = options.max || Math.max(1, os_1.default.cpus().length - 1);
  31536. this.pool = [];
  31537. this.idlePool = [];
  31538. this.queue = [];
  31539. }
  31540. async run(...args) {
  31541. const worker = await this._getAvailableWorker();
  31542. return new Promise((resolve, reject) => {
  31543. worker.currentResolve = resolve;
  31544. worker.currentReject = reject;
  31545. worker.postMessage(args);
  31546. });
  31547. }
  31548. stop() {
  31549. this.pool.forEach((w) => w.unref());
  31550. this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.')));
  31551. this.pool = [];
  31552. this.idlePool = [];
  31553. this.queue = [];
  31554. }
  31555. async _getAvailableWorker() {
  31556. // has idle one?
  31557. if (this.idlePool.length) {
  31558. return this.idlePool.shift();
  31559. }
  31560. // can spawn more?
  31561. if (this.pool.length < this.max) {
  31562. const worker = new worker_threads_1.Worker(this.code, { eval: true });
  31563. worker.on('message', (res) => {
  31564. worker.currentResolve && worker.currentResolve(res);
  31565. worker.currentResolve = null;
  31566. this._assignDoneWorker(worker);
  31567. });
  31568. worker.on('error', (err) => {
  31569. worker.currentReject && worker.currentReject(err);
  31570. worker.currentReject = null;
  31571. });
  31572. worker.on('exit', (code) => {
  31573. const i = this.pool.indexOf(worker);
  31574. if (i > -1)
  31575. this.pool.splice(i, 1);
  31576. if (code !== 0 && worker.currentReject) {
  31577. worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`));
  31578. worker.currentReject = null;
  31579. }
  31580. });
  31581. this.pool.push(worker);
  31582. return worker;
  31583. }
  31584. // no one is available, we have to wait
  31585. let resolve;
  31586. let reject;
  31587. const onWorkerAvailablePromise = new Promise((r, rj) => {
  31588. resolve = r;
  31589. reject = rj;
  31590. });
  31591. this.queue.push([resolve, reject]);
  31592. return onWorkerAvailablePromise;
  31593. }
  31594. _assignDoneWorker(worker) {
  31595. // someone's waiting already?
  31596. if (this.queue.length) {
  31597. const [resolve] = this.queue.shift();
  31598. resolve(worker);
  31599. return;
  31600. }
  31601. // take a rest.
  31602. this.idlePool.push(worker);
  31603. }
  31604. }
  31605. Worker_1 = dist.Worker = Worker;
  31606. function genWorkerCode(fn) {
  31607. return `
  31608. const doWork = ${fn.toString()}
  31609. const { parentPort } = require('worker_threads')
  31610. parentPort.on('message', async (args) => {
  31611. const res = await doWork(...args)
  31612. parentPort.postMessage(res)
  31613. })
  31614. `;
  31615. }
  31616. function terserPlugin(options) {
  31617. const worker = new Worker_1((basedir, code, options) => {
  31618. // when vite is linked, the worker thread won't share the same resolve
  31619. // root with vite itself, so we have to pass in the basedir and resolve
  31620. // terser first.
  31621. // eslint-disable-next-line node/no-restricted-require
  31622. const terserPath = require.resolve('vite/dist/node/terser', {
  31623. paths: [basedir]
  31624. });
  31625. return require(terserPath).minify(code, options);
  31626. });
  31627. return {
  31628. name: 'vite:terser',
  31629. async renderChunk(code, _chunk, outputOptions) {
  31630. const res = await worker.run(__dirname, code, {
  31631. safari10: true,
  31632. ...options,
  31633. sourceMap: !!outputOptions.sourcemap,
  31634. module: outputOptions.format.startsWith('es'),
  31635. toplevel: outputOptions.format === 'cjs'
  31636. });
  31637. return {
  31638. code: res.code,
  31639. map: res.map
  31640. };
  31641. },
  31642. closeBundle() {
  31643. worker.stop();
  31644. }
  31645. };
  31646. }
  31647. function manifestPlugin(config) {
  31648. const manifest = {};
  31649. let outputCount;
  31650. return {
  31651. name: 'vite:manifest',
  31652. buildStart() {
  31653. outputCount = 0;
  31654. },
  31655. generateBundle({ format }, bundle) {
  31656. var _a;
  31657. function getChunkName(chunk) {
  31658. if (chunk.facadeModuleId) {
  31659. let name = normalizePath$4(path__default.relative(config.root, chunk.facadeModuleId));
  31660. if (format === 'system' && !chunk.name.includes('-legacy')) {
  31661. const ext = path__default.extname(name);
  31662. name = name.slice(0, -ext.length) + `-legacy` + ext;
  31663. }
  31664. return name;
  31665. }
  31666. else {
  31667. return `_` + path__default.basename(chunk.fileName);
  31668. }
  31669. }
  31670. function getInternalImports(imports) {
  31671. const filteredImports = [];
  31672. for (const file of imports) {
  31673. if (bundle[file] === undefined) {
  31674. continue;
  31675. }
  31676. filteredImports.push(getChunkName(bundle[file]));
  31677. }
  31678. return filteredImports;
  31679. }
  31680. function createChunk(chunk) {
  31681. const manifestChunk = {
  31682. file: chunk.fileName
  31683. };
  31684. if (chunk.facadeModuleId) {
  31685. manifestChunk.src = getChunkName(chunk);
  31686. }
  31687. if (chunk.isEntry) {
  31688. manifestChunk.isEntry = true;
  31689. }
  31690. if (chunk.isDynamicEntry) {
  31691. manifestChunk.isDynamicEntry = true;
  31692. }
  31693. if (chunk.imports.length) {
  31694. const internalImports = getInternalImports(chunk.imports);
  31695. if (internalImports.length > 0) {
  31696. manifestChunk.imports = internalImports;
  31697. }
  31698. }
  31699. if (chunk.dynamicImports.length) {
  31700. const internalImports = getInternalImports(chunk.dynamicImports);
  31701. if (internalImports.length > 0) {
  31702. manifestChunk.dynamicImports = internalImports;
  31703. }
  31704. }
  31705. const cssFiles = chunkToEmittedCssFileMap.get(chunk);
  31706. if (cssFiles) {
  31707. manifestChunk.css = [...cssFiles];
  31708. }
  31709. const assets = chunkToEmittedAssetsMap.get(chunk);
  31710. if (assets)
  31711. [(manifestChunk.assets = [...assets])];
  31712. return manifestChunk;
  31713. }
  31714. for (const file in bundle) {
  31715. const chunk = bundle[file];
  31716. if (chunk.type === 'chunk') {
  31717. manifest[getChunkName(chunk)] = createChunk(chunk);
  31718. }
  31719. }
  31720. outputCount++;
  31721. const output = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.output;
  31722. const outputLength = Array.isArray(output) ? output.length : 1;
  31723. if (outputCount >= outputLength) {
  31724. this.emitFile({
  31725. fileName: `manifest.json`,
  31726. type: 'asset',
  31727. source: JSON.stringify(manifest, null, 2)
  31728. });
  31729. }
  31730. }
  31731. };
  31732. }
  31733. function walk$2(ast, { enter, leave }) {
  31734. return visit(ast, null, enter, leave);
  31735. }
  31736. let should_skip = false;
  31737. let should_remove = false;
  31738. let replacement = null;
  31739. const context = {
  31740. skip: () => should_skip = true,
  31741. remove: () => should_remove = true,
  31742. replace: (node) => replacement = node
  31743. };
  31744. function replace(parent, prop, index, node) {
  31745. if (parent) {
  31746. if (index !== null) {
  31747. parent[prop][index] = node;
  31748. } else {
  31749. parent[prop] = node;
  31750. }
  31751. }
  31752. }
  31753. function remove(parent, prop, index) {
  31754. if (parent) {
  31755. if (index !== null) {
  31756. parent[prop].splice(index, 1);
  31757. } else {
  31758. delete parent[prop];
  31759. }
  31760. }
  31761. }
  31762. function visit(
  31763. node,
  31764. parent,
  31765. enter,
  31766. leave,
  31767. prop,
  31768. index
  31769. ) {
  31770. if (node) {
  31771. if (enter) {
  31772. const _should_skip = should_skip;
  31773. const _should_remove = should_remove;
  31774. const _replacement = replacement;
  31775. should_skip = false;
  31776. should_remove = false;
  31777. replacement = null;
  31778. enter.call(context, node, parent, prop, index);
  31779. if (replacement) {
  31780. node = replacement;
  31781. replace(parent, prop, index, node);
  31782. }
  31783. if (should_remove) {
  31784. remove(parent, prop, index);
  31785. }
  31786. const skipped = should_skip;
  31787. const removed = should_remove;
  31788. should_skip = _should_skip;
  31789. should_remove = _should_remove;
  31790. replacement = _replacement;
  31791. if (skipped) return node;
  31792. if (removed) return null;
  31793. }
  31794. for (const key in node) {
  31795. const value = (node )[key];
  31796. if (typeof value !== 'object') {
  31797. continue;
  31798. }
  31799. else if (Array.isArray(value)) {
  31800. for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
  31801. if (value[j] !== null && typeof value[j].type === 'string') {
  31802. if (!visit(value[j], node, enter, leave, key, k)) {
  31803. // removed
  31804. j--;
  31805. }
  31806. }
  31807. }
  31808. }
  31809. else if (value !== null && typeof value.type === 'string') {
  31810. visit(value, node, enter, leave, key, null);
  31811. }
  31812. }
  31813. if (leave) {
  31814. const _replacement = replacement;
  31815. const _should_remove = should_remove;
  31816. replacement = null;
  31817. should_remove = false;
  31818. leave.call(context, node, parent, prop, index);
  31819. if (replacement) {
  31820. node = replacement;
  31821. replace(parent, prop, index, node);
  31822. }
  31823. if (should_remove) {
  31824. remove(parent, prop, index);
  31825. }
  31826. const removed = should_remove;
  31827. replacement = _replacement;
  31828. should_remove = _should_remove;
  31829. if (removed) return null;
  31830. }
  31831. }
  31832. return node;
  31833. }
  31834. const extractors = {
  31835. ArrayPattern(names, param) {
  31836. for (const element of param.elements) {
  31837. if (element)
  31838. extractors[element.type](names, element);
  31839. }
  31840. },
  31841. AssignmentPattern(names, param) {
  31842. extractors[param.left.type](names, param.left);
  31843. },
  31844. Identifier(names, param) {
  31845. names.push(param.name);
  31846. },
  31847. MemberExpression() { },
  31848. ObjectPattern(names, param) {
  31849. for (const prop of param.properties) {
  31850. // @ts-ignore Typescript reports that this is not a valid type
  31851. if (prop.type === 'RestElement') {
  31852. extractors.RestElement(names, prop);
  31853. }
  31854. else {
  31855. extractors[prop.value.type](names, prop.value);
  31856. }
  31857. }
  31858. },
  31859. RestElement(names, param) {
  31860. extractors[param.argument.type](names, param.argument);
  31861. }
  31862. };
  31863. const extractAssignedNames = function extractAssignedNames(param) {
  31864. const names = [];
  31865. extractors[param.type](names, param);
  31866. return names;
  31867. };
  31868. const blockDeclarations = {
  31869. const: true,
  31870. let: true
  31871. };
  31872. class Scope$1 {
  31873. constructor(options = {}) {
  31874. this.parent = options.parent;
  31875. this.isBlockScope = !!options.block;
  31876. this.declarations = Object.create(null);
  31877. if (options.params) {
  31878. options.params.forEach((param) => {
  31879. extractAssignedNames(param).forEach((name) => {
  31880. this.declarations[name] = true;
  31881. });
  31882. });
  31883. }
  31884. }
  31885. addDeclaration(node, isBlockDeclaration, isVar) {
  31886. if (!isBlockDeclaration && this.isBlockScope) {
  31887. // it's a `var` or function node, and this
  31888. // is a block scope, so we need to go up
  31889. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  31890. }
  31891. else if (node.id) {
  31892. extractAssignedNames(node.id).forEach((name) => {
  31893. this.declarations[name] = true;
  31894. });
  31895. }
  31896. }
  31897. contains(name) {
  31898. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  31899. }
  31900. }
  31901. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  31902. let scope = new Scope$1();
  31903. walk$2(ast, {
  31904. enter(n, parent) {
  31905. const node = n;
  31906. // function foo () {...}
  31907. // class Foo {...}
  31908. if (/(Function|Class)Declaration/.test(node.type)) {
  31909. scope.addDeclaration(node, false, false);
  31910. }
  31911. // var foo = 1
  31912. if (node.type === 'VariableDeclaration') {
  31913. const { kind } = node;
  31914. const isBlockDeclaration = blockDeclarations[kind];
  31915. // don't add const/let declarations in the body of a for loop #113
  31916. const parentType = parent ? parent.type : '';
  31917. if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) {
  31918. node.declarations.forEach((declaration) => {
  31919. scope.addDeclaration(declaration, isBlockDeclaration, true);
  31920. });
  31921. }
  31922. }
  31923. let newScope;
  31924. // create new function scope
  31925. if (/Function/.test(node.type)) {
  31926. const func = node;
  31927. newScope = new Scope$1({
  31928. parent: scope,
  31929. block: false,
  31930. params: func.params
  31931. });
  31932. // named function expressions - the name is considered
  31933. // part of the function's scope
  31934. if (func.type === 'FunctionExpression' && func.id) {
  31935. newScope.addDeclaration(func, false, false);
  31936. }
  31937. }
  31938. // create new block scope
  31939. if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
  31940. newScope = new Scope$1({
  31941. parent: scope,
  31942. block: true
  31943. });
  31944. }
  31945. // catch clause has its own block scope
  31946. if (node.type === 'CatchClause') {
  31947. newScope = new Scope$1({
  31948. parent: scope,
  31949. params: node.param ? [node.param] : [],
  31950. block: true
  31951. });
  31952. }
  31953. if (newScope) {
  31954. Object.defineProperty(node, propertyName, {
  31955. value: newScope,
  31956. configurable: true
  31957. });
  31958. scope = newScope;
  31959. }
  31960. },
  31961. leave(n) {
  31962. const node = n;
  31963. if (node[propertyName])
  31964. scope = scope.parent;
  31965. }
  31966. });
  31967. return scope;
  31968. };
  31969. // Helper since Typescript can't detect readonly arrays with Array.isArray
  31970. function isArray$2(arg) {
  31971. return Array.isArray(arg);
  31972. }
  31973. function ensureArray(thing) {
  31974. if (isArray$2(thing))
  31975. return thing;
  31976. if (thing == null)
  31977. return [];
  31978. return [thing];
  31979. }
  31980. function getMatcherString(id, resolutionBase) {
  31981. if (resolutionBase === false) {
  31982. return id;
  31983. }
  31984. // resolve('') is valid and will default to process.cwd()
  31985. const basePath = path$w.resolve(resolutionBase || '')
  31986. .split(path$w.sep)
  31987. .join('/')
  31988. // escape all possible (posix + win) path characters that might interfere with regex
  31989. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  31990. // Note that we use posix.join because:
  31991. // 1. the basePath has been normalized to use /
  31992. // 2. the incoming glob (id) matcher, also uses /
  31993. // otherwise Node will force backslash (\) on windows
  31994. return path$w.posix.join(basePath, id);
  31995. }
  31996. const createFilter = function createFilter(include, exclude, options) {
  31997. const resolutionBase = options && options.resolve;
  31998. const getMatcher = (id) => id instanceof RegExp
  31999. ? id
  32000. : {
  32001. test: (what) => {
  32002. // this refactor is a tad overly verbose but makes for easy debugging
  32003. const pattern = getMatcherString(id, resolutionBase);
  32004. const fn = picomatch$3(pattern, { dot: true });
  32005. const result = fn(what);
  32006. return result;
  32007. }
  32008. };
  32009. const includeMatchers = ensureArray(include).map(getMatcher);
  32010. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  32011. return function result(id) {
  32012. if (typeof id !== 'string')
  32013. return false;
  32014. if (/\0/.test(id))
  32015. return false;
  32016. const pathId = id.split(path$w.sep).join('/');
  32017. for (let i = 0; i < excludeMatchers.length; ++i) {
  32018. const matcher = excludeMatchers[i];
  32019. if (matcher.test(pathId))
  32020. return false;
  32021. }
  32022. for (let i = 0; i < includeMatchers.length; ++i) {
  32023. const matcher = includeMatchers[i];
  32024. if (matcher.test(pathId))
  32025. return true;
  32026. }
  32027. return !includeMatchers.length;
  32028. };
  32029. };
  32030. const reservedWords$1 = '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';
  32031. 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';
  32032. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' '));
  32033. forbiddenIdentifiers.add('');
  32034. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  32035. let identifier = str
  32036. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  32037. .replace(/[^$_a-zA-Z0-9]/g, '_');
  32038. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
  32039. identifier = `_${identifier}`;
  32040. }
  32041. return identifier || '_';
  32042. };
  32043. var path$h = path__default;
  32044. var commondir = function (basedir, relfiles) {
  32045. if (relfiles) {
  32046. var files = relfiles.map(function (r) {
  32047. return path$h.resolve(basedir, r);
  32048. });
  32049. }
  32050. else {
  32051. var files = basedir;
  32052. }
  32053. var res = files.slice(1).reduce(function (ps, file) {
  32054. if (!file.match(/^([A-Za-z]:)?\/|\\/)) {
  32055. throw new Error('relative path without a basedir');
  32056. }
  32057. var xs = file.split(/\/+|\\+/);
  32058. for (
  32059. var i = 0;
  32060. ps[i] === xs[i] && i < Math.min(ps.length, xs.length);
  32061. i++
  32062. );
  32063. return ps.slice(0, i);
  32064. }, files[0].split(/\/+|\\+/));
  32065. // Windows correctly handles paths with forward-slashes
  32066. return res.length > 1 ? res.join('/') : '/'
  32067. };
  32068. var old$1 = {};
  32069. // Copyright Joyent, Inc. and other Node contributors.
  32070. //
  32071. // Permission is hereby granted, free of charge, to any person obtaining a
  32072. // copy of this software and associated documentation files (the
  32073. // "Software"), to deal in the Software without restriction, including
  32074. // without limitation the rights to use, copy, modify, merge, publish,
  32075. // distribute, sublicense, and/or sell copies of the Software, and to permit
  32076. // persons to whom the Software is furnished to do so, subject to the
  32077. // following conditions:
  32078. //
  32079. // The above copyright notice and this permission notice shall be included
  32080. // in all copies or substantial portions of the Software.
  32081. //
  32082. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  32083. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  32084. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  32085. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  32086. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  32087. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  32088. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  32089. var pathModule = path__default;
  32090. var isWindows$3 = process.platform === 'win32';
  32091. var fs$i = fs__default;
  32092. // JavaScript implementation of realpath, ported from node pre-v6
  32093. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  32094. function rethrow() {
  32095. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  32096. // is fairly slow to generate.
  32097. var callback;
  32098. if (DEBUG) {
  32099. var backtrace = new Error;
  32100. callback = debugCallback;
  32101. } else
  32102. callback = missingCallback;
  32103. return callback;
  32104. function debugCallback(err) {
  32105. if (err) {
  32106. backtrace.message = err.message;
  32107. err = backtrace;
  32108. missingCallback(err);
  32109. }
  32110. }
  32111. function missingCallback(err) {
  32112. if (err) {
  32113. if (process.throwDeprecation)
  32114. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  32115. else if (!process.noDeprecation) {
  32116. var msg = 'fs: missing callback ' + (err.stack || err.message);
  32117. if (process.traceDeprecation)
  32118. console.trace(msg);
  32119. else
  32120. console.error(msg);
  32121. }
  32122. }
  32123. }
  32124. }
  32125. function maybeCallback(cb) {
  32126. return typeof cb === 'function' ? cb : rethrow();
  32127. }
  32128. // Regexp that finds the next partion of a (partial) path
  32129. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  32130. if (isWindows$3) {
  32131. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  32132. } else {
  32133. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  32134. }
  32135. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  32136. if (isWindows$3) {
  32137. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  32138. } else {
  32139. var splitRootRe = /^[\/]*/;
  32140. }
  32141. old$1.realpathSync = function realpathSync(p, cache) {
  32142. // make p is absolute
  32143. p = pathModule.resolve(p);
  32144. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  32145. return cache[p];
  32146. }
  32147. var original = p,
  32148. seenLinks = {},
  32149. knownHard = {};
  32150. // current character position in p
  32151. var pos;
  32152. // the partial path so far, including a trailing slash if any
  32153. var current;
  32154. // the partial path without a trailing slash (except when pointing at a root)
  32155. var base;
  32156. // the partial path scanned in the previous round, with slash
  32157. var previous;
  32158. start();
  32159. function start() {
  32160. // Skip over roots
  32161. var m = splitRootRe.exec(p);
  32162. pos = m[0].length;
  32163. current = m[0];
  32164. base = m[0];
  32165. previous = '';
  32166. // On windows, check that the root exists. On unix there is no need.
  32167. if (isWindows$3 && !knownHard[base]) {
  32168. fs$i.lstatSync(base);
  32169. knownHard[base] = true;
  32170. }
  32171. }
  32172. // walk down the path, swapping out linked pathparts for their real
  32173. // values
  32174. // NB: p.length changes.
  32175. while (pos < p.length) {
  32176. // find the next part
  32177. nextPartRe.lastIndex = pos;
  32178. var result = nextPartRe.exec(p);
  32179. previous = current;
  32180. current += result[0];
  32181. base = previous + result[1];
  32182. pos = nextPartRe.lastIndex;
  32183. // continue if not a symlink
  32184. if (knownHard[base] || (cache && cache[base] === base)) {
  32185. continue;
  32186. }
  32187. var resolvedLink;
  32188. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  32189. // some known symbolic link. no need to stat again.
  32190. resolvedLink = cache[base];
  32191. } else {
  32192. var stat = fs$i.lstatSync(base);
  32193. if (!stat.isSymbolicLink()) {
  32194. knownHard[base] = true;
  32195. if (cache) cache[base] = base;
  32196. continue;
  32197. }
  32198. // read the link if it wasn't read before
  32199. // dev/ino always return 0 on windows, so skip the check.
  32200. var linkTarget = null;
  32201. if (!isWindows$3) {
  32202. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  32203. if (seenLinks.hasOwnProperty(id)) {
  32204. linkTarget = seenLinks[id];
  32205. }
  32206. }
  32207. if (linkTarget === null) {
  32208. fs$i.statSync(base);
  32209. linkTarget = fs$i.readlinkSync(base);
  32210. }
  32211. resolvedLink = pathModule.resolve(previous, linkTarget);
  32212. // track this, if given a cache.
  32213. if (cache) cache[base] = resolvedLink;
  32214. if (!isWindows$3) seenLinks[id] = linkTarget;
  32215. }
  32216. // resolve the link, then start over
  32217. p = pathModule.resolve(resolvedLink, p.slice(pos));
  32218. start();
  32219. }
  32220. if (cache) cache[original] = p;
  32221. return p;
  32222. };
  32223. old$1.realpath = function realpath(p, cache, cb) {
  32224. if (typeof cb !== 'function') {
  32225. cb = maybeCallback(cache);
  32226. cache = null;
  32227. }
  32228. // make p is absolute
  32229. p = pathModule.resolve(p);
  32230. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  32231. return process.nextTick(cb.bind(null, null, cache[p]));
  32232. }
  32233. var original = p,
  32234. seenLinks = {},
  32235. knownHard = {};
  32236. // current character position in p
  32237. var pos;
  32238. // the partial path so far, including a trailing slash if any
  32239. var current;
  32240. // the partial path without a trailing slash (except when pointing at a root)
  32241. var base;
  32242. // the partial path scanned in the previous round, with slash
  32243. var previous;
  32244. start();
  32245. function start() {
  32246. // Skip over roots
  32247. var m = splitRootRe.exec(p);
  32248. pos = m[0].length;
  32249. current = m[0];
  32250. base = m[0];
  32251. previous = '';
  32252. // On windows, check that the root exists. On unix there is no need.
  32253. if (isWindows$3 && !knownHard[base]) {
  32254. fs$i.lstat(base, function(err) {
  32255. if (err) return cb(err);
  32256. knownHard[base] = true;
  32257. LOOP();
  32258. });
  32259. } else {
  32260. process.nextTick(LOOP);
  32261. }
  32262. }
  32263. // walk down the path, swapping out linked pathparts for their real
  32264. // values
  32265. function LOOP() {
  32266. // stop if scanned past end of path
  32267. if (pos >= p.length) {
  32268. if (cache) cache[original] = p;
  32269. return cb(null, p);
  32270. }
  32271. // find the next part
  32272. nextPartRe.lastIndex = pos;
  32273. var result = nextPartRe.exec(p);
  32274. previous = current;
  32275. current += result[0];
  32276. base = previous + result[1];
  32277. pos = nextPartRe.lastIndex;
  32278. // continue if not a symlink
  32279. if (knownHard[base] || (cache && cache[base] === base)) {
  32280. return process.nextTick(LOOP);
  32281. }
  32282. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  32283. // known symbolic link. no need to stat again.
  32284. return gotResolvedLink(cache[base]);
  32285. }
  32286. return fs$i.lstat(base, gotStat);
  32287. }
  32288. function gotStat(err, stat) {
  32289. if (err) return cb(err);
  32290. // if not a symlink, skip to the next path part
  32291. if (!stat.isSymbolicLink()) {
  32292. knownHard[base] = true;
  32293. if (cache) cache[base] = base;
  32294. return process.nextTick(LOOP);
  32295. }
  32296. // stat & read the link if not read before
  32297. // call gotTarget as soon as the link target is known
  32298. // dev/ino always return 0 on windows, so skip the check.
  32299. if (!isWindows$3) {
  32300. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  32301. if (seenLinks.hasOwnProperty(id)) {
  32302. return gotTarget(null, seenLinks[id], base);
  32303. }
  32304. }
  32305. fs$i.stat(base, function(err) {
  32306. if (err) return cb(err);
  32307. fs$i.readlink(base, function(err, target) {
  32308. if (!isWindows$3) seenLinks[id] = target;
  32309. gotTarget(err, target);
  32310. });
  32311. });
  32312. }
  32313. function gotTarget(err, target, base) {
  32314. if (err) return cb(err);
  32315. var resolvedLink = pathModule.resolve(previous, target);
  32316. if (cache) cache[base] = resolvedLink;
  32317. gotResolvedLink(resolvedLink);
  32318. }
  32319. function gotResolvedLink(resolvedLink) {
  32320. // resolve the link, then start over
  32321. p = pathModule.resolve(resolvedLink, p.slice(pos));
  32322. start();
  32323. }
  32324. };
  32325. var fs_realpath = realpath$2;
  32326. realpath$2.realpath = realpath$2;
  32327. realpath$2.sync = realpathSync;
  32328. realpath$2.realpathSync = realpathSync;
  32329. realpath$2.monkeypatch = monkeypatch;
  32330. realpath$2.unmonkeypatch = unmonkeypatch;
  32331. var fs$h = fs__default;
  32332. var origRealpath = fs$h.realpath;
  32333. var origRealpathSync = fs$h.realpathSync;
  32334. var version$1 = process.version;
  32335. var ok = /^v[0-5]\./.test(version$1);
  32336. var old = old$1;
  32337. function newError (er) {
  32338. return er && er.syscall === 'realpath' && (
  32339. er.code === 'ELOOP' ||
  32340. er.code === 'ENOMEM' ||
  32341. er.code === 'ENAMETOOLONG'
  32342. )
  32343. }
  32344. function realpath$2 (p, cache, cb) {
  32345. if (ok) {
  32346. return origRealpath(p, cache, cb)
  32347. }
  32348. if (typeof cache === 'function') {
  32349. cb = cache;
  32350. cache = null;
  32351. }
  32352. origRealpath(p, cache, function (er, result) {
  32353. if (newError(er)) {
  32354. old.realpath(p, cache, cb);
  32355. } else {
  32356. cb(er, result);
  32357. }
  32358. });
  32359. }
  32360. function realpathSync (p, cache) {
  32361. if (ok) {
  32362. return origRealpathSync(p, cache)
  32363. }
  32364. try {
  32365. return origRealpathSync(p, cache)
  32366. } catch (er) {
  32367. if (newError(er)) {
  32368. return old.realpathSync(p, cache)
  32369. } else {
  32370. throw er
  32371. }
  32372. }
  32373. }
  32374. function monkeypatch () {
  32375. fs$h.realpath = realpath$2;
  32376. fs$h.realpathSync = realpathSync;
  32377. }
  32378. function unmonkeypatch () {
  32379. fs$h.realpath = origRealpath;
  32380. fs$h.realpathSync = origRealpathSync;
  32381. }
  32382. var concatMap$1 = function (xs, fn) {
  32383. var res = [];
  32384. for (var i = 0; i < xs.length; i++) {
  32385. var x = fn(xs[i], i);
  32386. if (isArray$1(x)) res.push.apply(res, x);
  32387. else res.push(x);
  32388. }
  32389. return res;
  32390. };
  32391. var isArray$1 = Array.isArray || function (xs) {
  32392. return Object.prototype.toString.call(xs) === '[object Array]';
  32393. };
  32394. var balancedMatch = balanced$1;
  32395. function balanced$1(a, b, str) {
  32396. if (a instanceof RegExp) a = maybeMatch(a, str);
  32397. if (b instanceof RegExp) b = maybeMatch(b, str);
  32398. var r = range(a, b, str);
  32399. return r && {
  32400. start: r[0],
  32401. end: r[1],
  32402. pre: str.slice(0, r[0]),
  32403. body: str.slice(r[0] + a.length, r[1]),
  32404. post: str.slice(r[1] + b.length)
  32405. };
  32406. }
  32407. function maybeMatch(reg, str) {
  32408. var m = str.match(reg);
  32409. return m ? m[0] : null;
  32410. }
  32411. balanced$1.range = range;
  32412. function range(a, b, str) {
  32413. var begs, beg, left, right, result;
  32414. var ai = str.indexOf(a);
  32415. var bi = str.indexOf(b, ai + 1);
  32416. var i = ai;
  32417. if (ai >= 0 && bi > 0) {
  32418. if(a===b) {
  32419. return [ai, bi];
  32420. }
  32421. begs = [];
  32422. left = str.length;
  32423. while (i >= 0 && !result) {
  32424. if (i == ai) {
  32425. begs.push(i);
  32426. ai = str.indexOf(a, i + 1);
  32427. } else if (begs.length == 1) {
  32428. result = [ begs.pop(), bi ];
  32429. } else {
  32430. beg = begs.pop();
  32431. if (beg < left) {
  32432. left = beg;
  32433. right = bi;
  32434. }
  32435. bi = str.indexOf(b, i + 1);
  32436. }
  32437. i = ai < bi && ai >= 0 ? ai : bi;
  32438. }
  32439. if (begs.length) {
  32440. result = [ left, right ];
  32441. }
  32442. }
  32443. return result;
  32444. }
  32445. var concatMap = concatMap$1;
  32446. var balanced = balancedMatch;
  32447. var braceExpansion = expandTop;
  32448. var escSlash = '\0SLASH'+Math.random()+'\0';
  32449. var escOpen = '\0OPEN'+Math.random()+'\0';
  32450. var escClose = '\0CLOSE'+Math.random()+'\0';
  32451. var escComma = '\0COMMA'+Math.random()+'\0';
  32452. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  32453. function numeric(str) {
  32454. return parseInt(str, 10) == str
  32455. ? parseInt(str, 10)
  32456. : str.charCodeAt(0);
  32457. }
  32458. function escapeBraces(str) {
  32459. return str.split('\\\\').join(escSlash)
  32460. .split('\\{').join(escOpen)
  32461. .split('\\}').join(escClose)
  32462. .split('\\,').join(escComma)
  32463. .split('\\.').join(escPeriod);
  32464. }
  32465. function unescapeBraces(str) {
  32466. return str.split(escSlash).join('\\')
  32467. .split(escOpen).join('{')
  32468. .split(escClose).join('}')
  32469. .split(escComma).join(',')
  32470. .split(escPeriod).join('.');
  32471. }
  32472. // Basically just str.split(","), but handling cases
  32473. // where we have nested braced sections, which should be
  32474. // treated as individual members, like {a,{b,c},d}
  32475. function parseCommaParts(str) {
  32476. if (!str)
  32477. return [''];
  32478. var parts = [];
  32479. var m = balanced('{', '}', str);
  32480. if (!m)
  32481. return str.split(',');
  32482. var pre = m.pre;
  32483. var body = m.body;
  32484. var post = m.post;
  32485. var p = pre.split(',');
  32486. p[p.length-1] += '{' + body + '}';
  32487. var postParts = parseCommaParts(post);
  32488. if (post.length) {
  32489. p[p.length-1] += postParts.shift();
  32490. p.push.apply(p, postParts);
  32491. }
  32492. parts.push.apply(parts, p);
  32493. return parts;
  32494. }
  32495. function expandTop(str) {
  32496. if (!str)
  32497. return [];
  32498. // I don't know why Bash 4.3 does this, but it does.
  32499. // Anything starting with {} will have the first two bytes preserved
  32500. // but *only* at the top level, so {},a}b will not expand to anything,
  32501. // but a{},b}c will be expanded to [a}c,abc].
  32502. // One could argue that this is a bug in Bash, but since the goal of
  32503. // this module is to match Bash's rules, we escape a leading {}
  32504. if (str.substr(0, 2) === '{}') {
  32505. str = '\\{\\}' + str.substr(2);
  32506. }
  32507. return expand$1(escapeBraces(str), true).map(unescapeBraces);
  32508. }
  32509. function embrace(str) {
  32510. return '{' + str + '}';
  32511. }
  32512. function isPadded(el) {
  32513. return /^-?0\d/.test(el);
  32514. }
  32515. function lte(i, y) {
  32516. return i <= y;
  32517. }
  32518. function gte(i, y) {
  32519. return i >= y;
  32520. }
  32521. function expand$1(str, isTop) {
  32522. var expansions = [];
  32523. var m = balanced('{', '}', str);
  32524. if (!m || /\$$/.test(m.pre)) return [str];
  32525. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  32526. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  32527. var isSequence = isNumericSequence || isAlphaSequence;
  32528. var isOptions = m.body.indexOf(',') >= 0;
  32529. if (!isSequence && !isOptions) {
  32530. // {a},b}
  32531. if (m.post.match(/,.*\}/)) {
  32532. str = m.pre + '{' + m.body + escClose + m.post;
  32533. return expand$1(str);
  32534. }
  32535. return [str];
  32536. }
  32537. var n;
  32538. if (isSequence) {
  32539. n = m.body.split(/\.\./);
  32540. } else {
  32541. n = parseCommaParts(m.body);
  32542. if (n.length === 1) {
  32543. // x{{a,b}}y ==> x{a}y x{b}y
  32544. n = expand$1(n[0], false).map(embrace);
  32545. if (n.length === 1) {
  32546. var post = m.post.length
  32547. ? expand$1(m.post, false)
  32548. : [''];
  32549. return post.map(function(p) {
  32550. return m.pre + n[0] + p;
  32551. });
  32552. }
  32553. }
  32554. }
  32555. // at this point, n is the parts, and we know it's not a comma set
  32556. // with a single entry.
  32557. // no need to expand pre, since it is guaranteed to be free of brace-sets
  32558. var pre = m.pre;
  32559. var post = m.post.length
  32560. ? expand$1(m.post, false)
  32561. : [''];
  32562. var N;
  32563. if (isSequence) {
  32564. var x = numeric(n[0]);
  32565. var y = numeric(n[1]);
  32566. var width = Math.max(n[0].length, n[1].length);
  32567. var incr = n.length == 3
  32568. ? Math.abs(numeric(n[2]))
  32569. : 1;
  32570. var test = lte;
  32571. var reverse = y < x;
  32572. if (reverse) {
  32573. incr *= -1;
  32574. test = gte;
  32575. }
  32576. var pad = n.some(isPadded);
  32577. N = [];
  32578. for (var i = x; test(i, y); i += incr) {
  32579. var c;
  32580. if (isAlphaSequence) {
  32581. c = String.fromCharCode(i);
  32582. if (c === '\\')
  32583. c = '';
  32584. } else {
  32585. c = String(i);
  32586. if (pad) {
  32587. var need = width - c.length;
  32588. if (need > 0) {
  32589. var z = new Array(need + 1).join('0');
  32590. if (i < 0)
  32591. c = '-' + z + c.slice(1);
  32592. else
  32593. c = z + c;
  32594. }
  32595. }
  32596. }
  32597. N.push(c);
  32598. }
  32599. } else {
  32600. N = concatMap(n, function(el) { return expand$1(el, false) });
  32601. }
  32602. for (var j = 0; j < N.length; j++) {
  32603. for (var k = 0; k < post.length; k++) {
  32604. var expansion = pre + N[j] + post[k];
  32605. if (!isTop || isSequence || expansion)
  32606. expansions.push(expansion);
  32607. }
  32608. }
  32609. return expansions;
  32610. }
  32611. var minimatch_1 = minimatch$3;
  32612. minimatch$3.Minimatch = Minimatch$1;
  32613. var path$g = { sep: '/' };
  32614. try {
  32615. path$g = path__default;
  32616. } catch (er) {}
  32617. var GLOBSTAR$1 = minimatch$3.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
  32618. var expand = braceExpansion;
  32619. var plTypes = {
  32620. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  32621. '?': { open: '(?:', close: ')?' },
  32622. '+': { open: '(?:', close: ')+' },
  32623. '*': { open: '(?:', close: ')*' },
  32624. '@': { open: '(?:', close: ')' }
  32625. };
  32626. // any single thing other than /
  32627. // don't need to escape / when using new RegExp()
  32628. var qmark = '[^/]';
  32629. // * => any number of characters
  32630. var star = qmark + '*?';
  32631. // ** when dots are allowed. Anything goes, except .. and .
  32632. // not (^ or / followed by one or two dots followed by $ or /),
  32633. // followed by anything, any number of times.
  32634. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  32635. // not a ^ or / followed by a dot,
  32636. // followed by anything, any number of times.
  32637. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  32638. // characters that need to be escaped in RegExp.
  32639. var reSpecials = charSet('().*{}+?[]^$\\!');
  32640. // "abc" -> { a:true, b:true, c:true }
  32641. function charSet (s) {
  32642. return s.split('').reduce(function (set, c) {
  32643. set[c] = true;
  32644. return set
  32645. }, {})
  32646. }
  32647. // normalizes slashes.
  32648. var slashSplit = /\/+/;
  32649. minimatch$3.filter = filter;
  32650. function filter (pattern, options) {
  32651. options = options || {};
  32652. return function (p, i, list) {
  32653. return minimatch$3(p, pattern, options)
  32654. }
  32655. }
  32656. function ext (a, b) {
  32657. a = a || {};
  32658. b = b || {};
  32659. var t = {};
  32660. Object.keys(b).forEach(function (k) {
  32661. t[k] = b[k];
  32662. });
  32663. Object.keys(a).forEach(function (k) {
  32664. t[k] = a[k];
  32665. });
  32666. return t
  32667. }
  32668. minimatch$3.defaults = function (def) {
  32669. if (!def || !Object.keys(def).length) return minimatch$3
  32670. var orig = minimatch$3;
  32671. var m = function minimatch (p, pattern, options) {
  32672. return orig.minimatch(p, pattern, ext(def, options))
  32673. };
  32674. m.Minimatch = function Minimatch (pattern, options) {
  32675. return new orig.Minimatch(pattern, ext(def, options))
  32676. };
  32677. return m
  32678. };
  32679. Minimatch$1.defaults = function (def) {
  32680. if (!def || !Object.keys(def).length) return Minimatch$1
  32681. return minimatch$3.defaults(def).Minimatch
  32682. };
  32683. function minimatch$3 (p, pattern, options) {
  32684. if (typeof pattern !== 'string') {
  32685. throw new TypeError('glob pattern string required')
  32686. }
  32687. if (!options) options = {};
  32688. // shortcut: comments match nothing.
  32689. if (!options.nocomment && pattern.charAt(0) === '#') {
  32690. return false
  32691. }
  32692. // "" only matches ""
  32693. if (pattern.trim() === '') return p === ''
  32694. return new Minimatch$1(pattern, options).match(p)
  32695. }
  32696. function Minimatch$1 (pattern, options) {
  32697. if (!(this instanceof Minimatch$1)) {
  32698. return new Minimatch$1(pattern, options)
  32699. }
  32700. if (typeof pattern !== 'string') {
  32701. throw new TypeError('glob pattern string required')
  32702. }
  32703. if (!options) options = {};
  32704. pattern = pattern.trim();
  32705. // windows support: need to use /, not \
  32706. if (path$g.sep !== '/') {
  32707. pattern = pattern.split(path$g.sep).join('/');
  32708. }
  32709. this.options = options;
  32710. this.set = [];
  32711. this.pattern = pattern;
  32712. this.regexp = null;
  32713. this.negate = false;
  32714. this.comment = false;
  32715. this.empty = false;
  32716. // make the set of regexps etc.
  32717. this.make();
  32718. }
  32719. Minimatch$1.prototype.debug = function () {};
  32720. Minimatch$1.prototype.make = make;
  32721. function make () {
  32722. // don't do it more than once.
  32723. if (this._made) return
  32724. var pattern = this.pattern;
  32725. var options = this.options;
  32726. // empty patterns and comments match nothing.
  32727. if (!options.nocomment && pattern.charAt(0) === '#') {
  32728. this.comment = true;
  32729. return
  32730. }
  32731. if (!pattern) {
  32732. this.empty = true;
  32733. return
  32734. }
  32735. // step 1: figure out negation, etc.
  32736. this.parseNegate();
  32737. // step 2: expand braces
  32738. var set = this.globSet = this.braceExpand();
  32739. if (options.debug) this.debug = console.error;
  32740. this.debug(this.pattern, set);
  32741. // step 3: now we have a set, so turn each one into a series of path-portion
  32742. // matching patterns.
  32743. // These will be regexps, except in the case of "**", which is
  32744. // set to the GLOBSTAR object for globstar behavior,
  32745. // and will not contain any / characters
  32746. set = this.globParts = set.map(function (s) {
  32747. return s.split(slashSplit)
  32748. });
  32749. this.debug(this.pattern, set);
  32750. // glob --> regexps
  32751. set = set.map(function (s, si, set) {
  32752. return s.map(this.parse, this)
  32753. }, this);
  32754. this.debug(this.pattern, set);
  32755. // filter out everything that didn't compile properly.
  32756. set = set.filter(function (s) {
  32757. return s.indexOf(false) === -1
  32758. });
  32759. this.debug(this.pattern, set);
  32760. this.set = set;
  32761. }
  32762. Minimatch$1.prototype.parseNegate = parseNegate;
  32763. function parseNegate () {
  32764. var pattern = this.pattern;
  32765. var negate = false;
  32766. var options = this.options;
  32767. var negateOffset = 0;
  32768. if (options.nonegate) return
  32769. for (var i = 0, l = pattern.length
  32770. ; i < l && pattern.charAt(i) === '!'
  32771. ; i++) {
  32772. negate = !negate;
  32773. negateOffset++;
  32774. }
  32775. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  32776. this.negate = negate;
  32777. }
  32778. // Brace expansion:
  32779. // a{b,c}d -> abd acd
  32780. // a{b,}c -> abc ac
  32781. // a{0..3}d -> a0d a1d a2d a3d
  32782. // a{b,c{d,e}f}g -> abg acdfg acefg
  32783. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  32784. //
  32785. // Invalid sets are not expanded.
  32786. // a{2..}b -> a{2..}b
  32787. // a{b}c -> a{b}c
  32788. minimatch$3.braceExpand = function (pattern, options) {
  32789. return braceExpand(pattern, options)
  32790. };
  32791. Minimatch$1.prototype.braceExpand = braceExpand;
  32792. function braceExpand (pattern, options) {
  32793. if (!options) {
  32794. if (this instanceof Minimatch$1) {
  32795. options = this.options;
  32796. } else {
  32797. options = {};
  32798. }
  32799. }
  32800. pattern = typeof pattern === 'undefined'
  32801. ? this.pattern : pattern;
  32802. if (typeof pattern === 'undefined') {
  32803. throw new TypeError('undefined pattern')
  32804. }
  32805. if (options.nobrace ||
  32806. !pattern.match(/\{.*\}/)) {
  32807. // shortcut. no need to expand.
  32808. return [pattern]
  32809. }
  32810. return expand(pattern)
  32811. }
  32812. // parse a component of the expanded set.
  32813. // At this point, no pattern may contain "/" in it
  32814. // so we're going to return a 2d array, where each entry is the full
  32815. // pattern, split on '/', and then turned into a regular expression.
  32816. // A regexp is made at the end which joins each array with an
  32817. // escaped /, and another full one which joins each regexp with |.
  32818. //
  32819. // Following the lead of Bash 4.1, note that "**" only has special meaning
  32820. // when it is the *only* thing in a path portion. Otherwise, any series
  32821. // of * is equivalent to a single *. Globstar behavior is enabled by
  32822. // default, and can be disabled by setting options.noglobstar.
  32823. Minimatch$1.prototype.parse = parse$c;
  32824. var SUBPARSE = {};
  32825. function parse$c (pattern, isSub) {
  32826. if (pattern.length > 1024 * 64) {
  32827. throw new TypeError('pattern is too long')
  32828. }
  32829. var options = this.options;
  32830. // shortcuts
  32831. if (!options.noglobstar && pattern === '**') return GLOBSTAR$1
  32832. if (pattern === '') return ''
  32833. var re = '';
  32834. var hasMagic = !!options.nocase;
  32835. var escaping = false;
  32836. // ? => one single character
  32837. var patternListStack = [];
  32838. var negativeLists = [];
  32839. var stateChar;
  32840. var inClass = false;
  32841. var reClassStart = -1;
  32842. var classStart = -1;
  32843. // . and .. never match anything that doesn't start with .,
  32844. // even when options.dot is set.
  32845. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  32846. // not (start or / followed by . or .. followed by / or end)
  32847. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  32848. : '(?!\\.)';
  32849. var self = this;
  32850. function clearStateChar () {
  32851. if (stateChar) {
  32852. // we had some state-tracking character
  32853. // that wasn't consumed by this pass.
  32854. switch (stateChar) {
  32855. case '*':
  32856. re += star;
  32857. hasMagic = true;
  32858. break
  32859. case '?':
  32860. re += qmark;
  32861. hasMagic = true;
  32862. break
  32863. default:
  32864. re += '\\' + stateChar;
  32865. break
  32866. }
  32867. self.debug('clearStateChar %j %j', stateChar, re);
  32868. stateChar = false;
  32869. }
  32870. }
  32871. for (var i = 0, len = pattern.length, c
  32872. ; (i < len) && (c = pattern.charAt(i))
  32873. ; i++) {
  32874. this.debug('%s\t%s %s %j', pattern, i, re, c);
  32875. // skip over any that are escaped.
  32876. if (escaping && reSpecials[c]) {
  32877. re += '\\' + c;
  32878. escaping = false;
  32879. continue
  32880. }
  32881. switch (c) {
  32882. case '/':
  32883. // completely not allowed, even escaped.
  32884. // Should already be path-split by now.
  32885. return false
  32886. case '\\':
  32887. clearStateChar();
  32888. escaping = true;
  32889. continue
  32890. // the various stateChar values
  32891. // for the "extglob" stuff.
  32892. case '?':
  32893. case '*':
  32894. case '+':
  32895. case '@':
  32896. case '!':
  32897. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  32898. // all of those are literals inside a class, except that
  32899. // the glob [!a] means [^a] in regexp
  32900. if (inClass) {
  32901. this.debug(' in class');
  32902. if (c === '!' && i === classStart + 1) c = '^';
  32903. re += c;
  32904. continue
  32905. }
  32906. // if we already have a stateChar, then it means
  32907. // that there was something like ** or +? in there.
  32908. // Handle the stateChar, then proceed with this one.
  32909. self.debug('call clearStateChar %j', stateChar);
  32910. clearStateChar();
  32911. stateChar = c;
  32912. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  32913. // just clear the statechar *now*, rather than even diving into
  32914. // the patternList stuff.
  32915. if (options.noext) clearStateChar();
  32916. continue
  32917. case '(':
  32918. if (inClass) {
  32919. re += '(';
  32920. continue
  32921. }
  32922. if (!stateChar) {
  32923. re += '\\(';
  32924. continue
  32925. }
  32926. patternListStack.push({
  32927. type: stateChar,
  32928. start: i - 1,
  32929. reStart: re.length,
  32930. open: plTypes[stateChar].open,
  32931. close: plTypes[stateChar].close
  32932. });
  32933. // negation is (?:(?!js)[^/]*)
  32934. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  32935. this.debug('plType %j %j', stateChar, re);
  32936. stateChar = false;
  32937. continue
  32938. case ')':
  32939. if (inClass || !patternListStack.length) {
  32940. re += '\\)';
  32941. continue
  32942. }
  32943. clearStateChar();
  32944. hasMagic = true;
  32945. var pl = patternListStack.pop();
  32946. // negation is (?:(?!js)[^/]*)
  32947. // The others are (?:<pattern>)<type>
  32948. re += pl.close;
  32949. if (pl.type === '!') {
  32950. negativeLists.push(pl);
  32951. }
  32952. pl.reEnd = re.length;
  32953. continue
  32954. case '|':
  32955. if (inClass || !patternListStack.length || escaping) {
  32956. re += '\\|';
  32957. escaping = false;
  32958. continue
  32959. }
  32960. clearStateChar();
  32961. re += '|';
  32962. continue
  32963. // these are mostly the same in regexp and glob
  32964. case '[':
  32965. // swallow any state-tracking char before the [
  32966. clearStateChar();
  32967. if (inClass) {
  32968. re += '\\' + c;
  32969. continue
  32970. }
  32971. inClass = true;
  32972. classStart = i;
  32973. reClassStart = re.length;
  32974. re += c;
  32975. continue
  32976. case ']':
  32977. // a right bracket shall lose its special
  32978. // meaning and represent itself in
  32979. // a bracket expression if it occurs
  32980. // first in the list. -- POSIX.2 2.8.3.2
  32981. if (i === classStart + 1 || !inClass) {
  32982. re += '\\' + c;
  32983. escaping = false;
  32984. continue
  32985. }
  32986. // handle the case where we left a class open.
  32987. // "[z-a]" is valid, equivalent to "\[z-a\]"
  32988. if (inClass) {
  32989. // split where the last [ was, make sure we don't have
  32990. // an invalid re. if so, re-walk the contents of the
  32991. // would-be class to re-translate any characters that
  32992. // were passed through as-is
  32993. // TODO: It would probably be faster to determine this
  32994. // without a try/catch and a new RegExp, but it's tricky
  32995. // to do safely. For now, this is safe and works.
  32996. var cs = pattern.substring(classStart + 1, i);
  32997. try {
  32998. } catch (er) {
  32999. // not a valid class!
  33000. var sp = this.parse(cs, SUBPARSE);
  33001. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
  33002. hasMagic = hasMagic || sp[1];
  33003. inClass = false;
  33004. continue
  33005. }
  33006. }
  33007. // finish up the class.
  33008. hasMagic = true;
  33009. inClass = false;
  33010. re += c;
  33011. continue
  33012. default:
  33013. // swallow any state char that wasn't consumed
  33014. clearStateChar();
  33015. if (escaping) {
  33016. // no need
  33017. escaping = false;
  33018. } else if (reSpecials[c]
  33019. && !(c === '^' && inClass)) {
  33020. re += '\\';
  33021. }
  33022. re += c;
  33023. } // switch
  33024. } // for
  33025. // handle the case where we left a class open.
  33026. // "[abc" is valid, equivalent to "\[abc"
  33027. if (inClass) {
  33028. // split where the last [ was, and escape it
  33029. // this is a huge pita. We now have to re-walk
  33030. // the contents of the would-be class to re-translate
  33031. // any characters that were passed through as-is
  33032. cs = pattern.substr(classStart + 1);
  33033. sp = this.parse(cs, SUBPARSE);
  33034. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  33035. hasMagic = hasMagic || sp[1];
  33036. }
  33037. // handle the case where we had a +( thing at the *end*
  33038. // of the pattern.
  33039. // each pattern list stack adds 3 chars, and we need to go through
  33040. // and escape any | chars that were passed through as-is for the regexp.
  33041. // Go through and escape them, taking care not to double-escape any
  33042. // | chars that were already escaped.
  33043. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  33044. var tail = re.slice(pl.reStart + pl.open.length);
  33045. this.debug('setting tail', re, pl);
  33046. // maybe some even number of \, then maybe 1 \, followed by a |
  33047. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
  33048. if (!$2) {
  33049. // the | isn't already escaped, so escape it.
  33050. $2 = '\\';
  33051. }
  33052. // need to escape all those slashes *again*, without escaping the
  33053. // one that we need for escaping the | character. As it works out,
  33054. // escaping an even number of slashes can be done by simply repeating
  33055. // it exactly after itself. That's why this trick works.
  33056. //
  33057. // I am sorry that you have to see this.
  33058. return $1 + $1 + $2 + '|'
  33059. });
  33060. this.debug('tail=%j\n %s', tail, tail, pl, re);
  33061. var t = pl.type === '*' ? star
  33062. : pl.type === '?' ? qmark
  33063. : '\\' + pl.type;
  33064. hasMagic = true;
  33065. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  33066. }
  33067. // handle trailing things that only matter at the very end.
  33068. clearStateChar();
  33069. if (escaping) {
  33070. // trailing \\
  33071. re += '\\\\';
  33072. }
  33073. // only need to apply the nodot start if the re starts with
  33074. // something that could conceivably capture a dot
  33075. var addPatternStart = false;
  33076. switch (re.charAt(0)) {
  33077. case '.':
  33078. case '[':
  33079. case '(': addPatternStart = true;
  33080. }
  33081. // Hack to work around lack of negative lookbehind in JS
  33082. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  33083. // like 'a.xyz.yz' doesn't match. So, the first negative
  33084. // lookahead, has to look ALL the way ahead, to the end of
  33085. // the pattern.
  33086. for (var n = negativeLists.length - 1; n > -1; n--) {
  33087. var nl = negativeLists[n];
  33088. var nlBefore = re.slice(0, nl.reStart);
  33089. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  33090. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
  33091. var nlAfter = re.slice(nl.reEnd);
  33092. nlLast += nlAfter;
  33093. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  33094. // mean that we should *not* include the ) in the bit that is considered
  33095. // "after" the negated section.
  33096. var openParensBefore = nlBefore.split('(').length - 1;
  33097. var cleanAfter = nlAfter;
  33098. for (i = 0; i < openParensBefore; i++) {
  33099. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  33100. }
  33101. nlAfter = cleanAfter;
  33102. var dollar = '';
  33103. if (nlAfter === '' && isSub !== SUBPARSE) {
  33104. dollar = '$';
  33105. }
  33106. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  33107. re = newRe;
  33108. }
  33109. // if the re is not "" at this point, then we need to make sure
  33110. // it doesn't match against an empty path part.
  33111. // Otherwise a/* will match a/, which it should not.
  33112. if (re !== '' && hasMagic) {
  33113. re = '(?=.)' + re;
  33114. }
  33115. if (addPatternStart) {
  33116. re = patternStart + re;
  33117. }
  33118. // parsing just a piece of a larger pattern.
  33119. if (isSub === SUBPARSE) {
  33120. return [re, hasMagic]
  33121. }
  33122. // skip the regexp for non-magical patterns
  33123. // unescape anything in it, though, so that it'll be
  33124. // an exact match against a file etc.
  33125. if (!hasMagic) {
  33126. return globUnescape(pattern)
  33127. }
  33128. var flags = options.nocase ? 'i' : '';
  33129. try {
  33130. var regExp = new RegExp('^' + re + '$', flags);
  33131. } catch (er) {
  33132. // If it was an invalid regular expression, then it can't match
  33133. // anything. This trick looks for a character after the end of
  33134. // the string, which is of course impossible, except in multi-line
  33135. // mode, but it's not a /m regex.
  33136. return new RegExp('$.')
  33137. }
  33138. regExp._glob = pattern;
  33139. regExp._src = re;
  33140. return regExp
  33141. }
  33142. minimatch$3.makeRe = function (pattern, options) {
  33143. return new Minimatch$1(pattern, options || {}).makeRe()
  33144. };
  33145. Minimatch$1.prototype.makeRe = makeRe;
  33146. function makeRe () {
  33147. if (this.regexp || this.regexp === false) return this.regexp
  33148. // at this point, this.set is a 2d array of partial
  33149. // pattern strings, or "**".
  33150. //
  33151. // It's better to use .match(). This function shouldn't
  33152. // be used, really, but it's pretty convenient sometimes,
  33153. // when you just want to work with a regex.
  33154. var set = this.set;
  33155. if (!set.length) {
  33156. this.regexp = false;
  33157. return this.regexp
  33158. }
  33159. var options = this.options;
  33160. var twoStar = options.noglobstar ? star
  33161. : options.dot ? twoStarDot
  33162. : twoStarNoDot;
  33163. var flags = options.nocase ? 'i' : '';
  33164. var re = set.map(function (pattern) {
  33165. return pattern.map(function (p) {
  33166. return (p === GLOBSTAR$1) ? twoStar
  33167. : (typeof p === 'string') ? regExpEscape(p)
  33168. : p._src
  33169. }).join('\\\/')
  33170. }).join('|');
  33171. // must match entire pattern
  33172. // ending in a * or ** will make it less strict.
  33173. re = '^(?:' + re + ')$';
  33174. // can match anything, as long as it's not this.
  33175. if (this.negate) re = '^(?!' + re + ').*$';
  33176. try {
  33177. this.regexp = new RegExp(re, flags);
  33178. } catch (ex) {
  33179. this.regexp = false;
  33180. }
  33181. return this.regexp
  33182. }
  33183. minimatch$3.match = function (list, pattern, options) {
  33184. options = options || {};
  33185. var mm = new Minimatch$1(pattern, options);
  33186. list = list.filter(function (f) {
  33187. return mm.match(f)
  33188. });
  33189. if (mm.options.nonull && !list.length) {
  33190. list.push(pattern);
  33191. }
  33192. return list
  33193. };
  33194. Minimatch$1.prototype.match = match;
  33195. function match (f, partial) {
  33196. this.debug('match', f, this.pattern);
  33197. // short-circuit in the case of busted things.
  33198. // comments, etc.
  33199. if (this.comment) return false
  33200. if (this.empty) return f === ''
  33201. if (f === '/' && partial) return true
  33202. var options = this.options;
  33203. // windows: need to use /, not \
  33204. if (path$g.sep !== '/') {
  33205. f = f.split(path$g.sep).join('/');
  33206. }
  33207. // treat the test path as a set of pathparts.
  33208. f = f.split(slashSplit);
  33209. this.debug(this.pattern, 'split', f);
  33210. // just ONE of the pattern sets in this.set needs to match
  33211. // in order for it to be valid. If negating, then just one
  33212. // match means that we have failed.
  33213. // Either way, return on the first hit.
  33214. var set = this.set;
  33215. this.debug(this.pattern, 'set', set);
  33216. // Find the basename of the path by looking for the last non-empty segment
  33217. var filename;
  33218. var i;
  33219. for (i = f.length - 1; i >= 0; i--) {
  33220. filename = f[i];
  33221. if (filename) break
  33222. }
  33223. for (i = 0; i < set.length; i++) {
  33224. var pattern = set[i];
  33225. var file = f;
  33226. if (options.matchBase && pattern.length === 1) {
  33227. file = [filename];
  33228. }
  33229. var hit = this.matchOne(file, pattern, partial);
  33230. if (hit) {
  33231. if (options.flipNegate) return true
  33232. return !this.negate
  33233. }
  33234. }
  33235. // didn't get any hits. this is success if it's a negative
  33236. // pattern, failure otherwise.
  33237. if (options.flipNegate) return false
  33238. return this.negate
  33239. }
  33240. // set partial to true to test if, for example,
  33241. // "/a/b" matches the start of "/*/b/*/d"
  33242. // Partial means, if you run out of file before you run
  33243. // out of pattern, then that's fine, as long as all
  33244. // the parts match.
  33245. Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
  33246. var options = this.options;
  33247. this.debug('matchOne',
  33248. { 'this': this, file: file, pattern: pattern });
  33249. this.debug('matchOne', file.length, pattern.length);
  33250. for (var fi = 0,
  33251. pi = 0,
  33252. fl = file.length,
  33253. pl = pattern.length
  33254. ; (fi < fl) && (pi < pl)
  33255. ; fi++, pi++) {
  33256. this.debug('matchOne loop');
  33257. var p = pattern[pi];
  33258. var f = file[fi];
  33259. this.debug(pattern, p, f);
  33260. // should be impossible.
  33261. // some invalid regexp stuff in the set.
  33262. if (p === false) return false
  33263. if (p === GLOBSTAR$1) {
  33264. this.debug('GLOBSTAR', [pattern, p, f]);
  33265. // "**"
  33266. // a/**/b/**/c would match the following:
  33267. // a/b/x/y/z/c
  33268. // a/x/y/z/b/c
  33269. // a/b/x/b/x/c
  33270. // a/b/c
  33271. // To do this, take the rest of the pattern after
  33272. // the **, and see if it would match the file remainder.
  33273. // If so, return success.
  33274. // If not, the ** "swallows" a segment, and try again.
  33275. // This is recursively awful.
  33276. //
  33277. // a/**/b/**/c matching a/b/x/y/z/c
  33278. // - a matches a
  33279. // - doublestar
  33280. // - matchOne(b/x/y/z/c, b/**/c)
  33281. // - b matches b
  33282. // - doublestar
  33283. // - matchOne(x/y/z/c, c) -> no
  33284. // - matchOne(y/z/c, c) -> no
  33285. // - matchOne(z/c, c) -> no
  33286. // - matchOne(c, c) yes, hit
  33287. var fr = fi;
  33288. var pr = pi + 1;
  33289. if (pr === pl) {
  33290. this.debug('** at the end');
  33291. // a ** at the end will just swallow the rest.
  33292. // We have found a match.
  33293. // however, it will not swallow /.x, unless
  33294. // options.dot is set.
  33295. // . and .. are *never* matched by **, for explosively
  33296. // exponential reasons.
  33297. for (; fi < fl; fi++) {
  33298. if (file[fi] === '.' || file[fi] === '..' ||
  33299. (!options.dot && file[fi].charAt(0) === '.')) return false
  33300. }
  33301. return true
  33302. }
  33303. // ok, let's see if we can swallow whatever we can.
  33304. while (fr < fl) {
  33305. var swallowee = file[fr];
  33306. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  33307. // XXX remove this slice. Just pass the start index.
  33308. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  33309. this.debug('globstar found match!', fr, fl, swallowee);
  33310. // found a match.
  33311. return true
  33312. } else {
  33313. // can't swallow "." or ".." ever.
  33314. // can only swallow ".foo" when explicitly asked.
  33315. if (swallowee === '.' || swallowee === '..' ||
  33316. (!options.dot && swallowee.charAt(0) === '.')) {
  33317. this.debug('dot detected!', file, fr, pattern, pr);
  33318. break
  33319. }
  33320. // ** swallows a segment, and continue.
  33321. this.debug('globstar swallow a segment, and continue');
  33322. fr++;
  33323. }
  33324. }
  33325. // no match was found.
  33326. // However, in partial mode, we can't say this is necessarily over.
  33327. // If there's more *pattern* left, then
  33328. if (partial) {
  33329. // ran out of file
  33330. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  33331. if (fr === fl) return true
  33332. }
  33333. return false
  33334. }
  33335. // something other than **
  33336. // non-magic patterns just have to match exactly
  33337. // patterns with magic have been turned into regexps.
  33338. var hit;
  33339. if (typeof p === 'string') {
  33340. if (options.nocase) {
  33341. hit = f.toLowerCase() === p.toLowerCase();
  33342. } else {
  33343. hit = f === p;
  33344. }
  33345. this.debug('string match', p, f, hit);
  33346. } else {
  33347. hit = f.match(p);
  33348. this.debug('pattern match', p, f, hit);
  33349. }
  33350. if (!hit) return false
  33351. }
  33352. // Note: ending in / means that we'll get a final ""
  33353. // at the end of the pattern. This can only match a
  33354. // corresponding "" at the end of the file.
  33355. // If the file ends in /, then it can only match a
  33356. // a pattern that ends in /, unless the pattern just
  33357. // doesn't have any more for it. But, a/b/ should *not*
  33358. // match "a/b/*", even though "" matches against the
  33359. // [^/]*? pattern, except in partial mode, where it might
  33360. // simply not be reached yet.
  33361. // However, a/b/ should still satisfy a/*
  33362. // now either we fell off the end of the pattern, or we're done.
  33363. if (fi === fl && pi === pl) {
  33364. // ran out of pattern and filename at the same time.
  33365. // an exact hit!
  33366. return true
  33367. } else if (fi === fl) {
  33368. // ran out of file, but still had pattern left.
  33369. // this is ok if we're doing the match as part of
  33370. // a glob fs traversal.
  33371. return partial
  33372. } else if (pi === pl) {
  33373. // ran out of pattern, still have file left.
  33374. // this is only acceptable if we're on the very last
  33375. // empty segment of a file with a trailing slash.
  33376. // a/* should match a/b/
  33377. var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
  33378. return emptyFileEnd
  33379. }
  33380. // should be unreachable.
  33381. throw new Error('wtf?')
  33382. };
  33383. // replace stuff like \* with *
  33384. function globUnescape (s) {
  33385. return s.replace(/\\(.)/g, '$1')
  33386. }
  33387. function regExpEscape (s) {
  33388. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  33389. }
  33390. var inherits$1 = {exports: {}};
  33391. var inherits_browser = {exports: {}};
  33392. if (typeof Object.create === 'function') {
  33393. // implementation from standard node.js 'util' module
  33394. inherits_browser.exports = function inherits(ctor, superCtor) {
  33395. if (superCtor) {
  33396. ctor.super_ = superCtor;
  33397. ctor.prototype = Object.create(superCtor.prototype, {
  33398. constructor: {
  33399. value: ctor,
  33400. enumerable: false,
  33401. writable: true,
  33402. configurable: true
  33403. }
  33404. });
  33405. }
  33406. };
  33407. } else {
  33408. // old school shim for old browsers
  33409. inherits_browser.exports = function inherits(ctor, superCtor) {
  33410. if (superCtor) {
  33411. ctor.super_ = superCtor;
  33412. var TempCtor = function () {};
  33413. TempCtor.prototype = superCtor.prototype;
  33414. ctor.prototype = new TempCtor();
  33415. ctor.prototype.constructor = ctor;
  33416. }
  33417. };
  33418. }
  33419. try {
  33420. var util$6 = require$$0__default$3;
  33421. /* istanbul ignore next */
  33422. if (typeof util$6.inherits !== 'function') throw '';
  33423. inherits$1.exports = util$6.inherits;
  33424. } catch (e) {
  33425. /* istanbul ignore next */
  33426. inherits$1.exports = inherits_browser.exports;
  33427. }
  33428. var pathIsAbsolute = {exports: {}};
  33429. function posix(path) {
  33430. return path.charAt(0) === '/';
  33431. }
  33432. function win32(path) {
  33433. // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
  33434. var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  33435. var result = splitDeviceRe.exec(path);
  33436. var device = result[1] || '';
  33437. var isUnc = Boolean(device && device.charAt(1) !== ':');
  33438. // UNC paths are always absolute
  33439. return Boolean(result[2] || isUnc);
  33440. }
  33441. pathIsAbsolute.exports = process.platform === 'win32' ? win32 : posix;
  33442. pathIsAbsolute.exports.posix = posix;
  33443. pathIsAbsolute.exports.win32 = win32;
  33444. var common$6 = {};
  33445. common$6.setopts = setopts$2;
  33446. common$6.ownProp = ownProp$2;
  33447. common$6.makeAbs = makeAbs;
  33448. common$6.finish = finish;
  33449. common$6.mark = mark;
  33450. common$6.isIgnored = isIgnored$2;
  33451. common$6.childrenIgnored = childrenIgnored$2;
  33452. function ownProp$2 (obj, field) {
  33453. return Object.prototype.hasOwnProperty.call(obj, field)
  33454. }
  33455. var path$f = path__default;
  33456. var minimatch$2 = minimatch_1;
  33457. var isAbsolute$2 = pathIsAbsolute.exports;
  33458. var Minimatch = minimatch$2.Minimatch;
  33459. function alphasort (a, b) {
  33460. return a.localeCompare(b, 'en')
  33461. }
  33462. function setupIgnores (self, options) {
  33463. self.ignore = options.ignore || [];
  33464. if (!Array.isArray(self.ignore))
  33465. self.ignore = [self.ignore];
  33466. if (self.ignore.length) {
  33467. self.ignore = self.ignore.map(ignoreMap);
  33468. }
  33469. }
  33470. // ignore patterns are always in dot:true mode.
  33471. function ignoreMap (pattern) {
  33472. var gmatcher = null;
  33473. if (pattern.slice(-3) === '/**') {
  33474. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  33475. gmatcher = new Minimatch(gpattern, { dot: true });
  33476. }
  33477. return {
  33478. matcher: new Minimatch(pattern, { dot: true }),
  33479. gmatcher: gmatcher
  33480. }
  33481. }
  33482. function setopts$2 (self, pattern, options) {
  33483. if (!options)
  33484. options = {};
  33485. // base-matching: just use globstar for that.
  33486. if (options.matchBase && -1 === pattern.indexOf("/")) {
  33487. if (options.noglobstar) {
  33488. throw new Error("base matching requires globstar")
  33489. }
  33490. pattern = "**/" + pattern;
  33491. }
  33492. self.silent = !!options.silent;
  33493. self.pattern = pattern;
  33494. self.strict = options.strict !== false;
  33495. self.realpath = !!options.realpath;
  33496. self.realpathCache = options.realpathCache || Object.create(null);
  33497. self.follow = !!options.follow;
  33498. self.dot = !!options.dot;
  33499. self.mark = !!options.mark;
  33500. self.nodir = !!options.nodir;
  33501. if (self.nodir)
  33502. self.mark = true;
  33503. self.sync = !!options.sync;
  33504. self.nounique = !!options.nounique;
  33505. self.nonull = !!options.nonull;
  33506. self.nosort = !!options.nosort;
  33507. self.nocase = !!options.nocase;
  33508. self.stat = !!options.stat;
  33509. self.noprocess = !!options.noprocess;
  33510. self.absolute = !!options.absolute;
  33511. self.maxLength = options.maxLength || Infinity;
  33512. self.cache = options.cache || Object.create(null);
  33513. self.statCache = options.statCache || Object.create(null);
  33514. self.symlinks = options.symlinks || Object.create(null);
  33515. setupIgnores(self, options);
  33516. self.changedCwd = false;
  33517. var cwd = process.cwd();
  33518. if (!ownProp$2(options, "cwd"))
  33519. self.cwd = cwd;
  33520. else {
  33521. self.cwd = path$f.resolve(options.cwd);
  33522. self.changedCwd = self.cwd !== cwd;
  33523. }
  33524. self.root = options.root || path$f.resolve(self.cwd, "/");
  33525. self.root = path$f.resolve(self.root);
  33526. if (process.platform === "win32")
  33527. self.root = self.root.replace(/\\/g, "/");
  33528. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  33529. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  33530. self.cwdAbs = isAbsolute$2(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  33531. if (process.platform === "win32")
  33532. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  33533. self.nomount = !!options.nomount;
  33534. // disable comments and negation in Minimatch.
  33535. // Note that they are not supported in Glob itself anyway.
  33536. options.nonegate = true;
  33537. options.nocomment = true;
  33538. self.minimatch = new Minimatch(pattern, options);
  33539. self.options = self.minimatch.options;
  33540. }
  33541. function finish (self) {
  33542. var nou = self.nounique;
  33543. var all = nou ? [] : Object.create(null);
  33544. for (var i = 0, l = self.matches.length; i < l; i ++) {
  33545. var matches = self.matches[i];
  33546. if (!matches || Object.keys(matches).length === 0) {
  33547. if (self.nonull) {
  33548. // do like the shell, and spit out the literal glob
  33549. var literal = self.minimatch.globSet[i];
  33550. if (nou)
  33551. all.push(literal);
  33552. else
  33553. all[literal] = true;
  33554. }
  33555. } else {
  33556. // had matches
  33557. var m = Object.keys(matches);
  33558. if (nou)
  33559. all.push.apply(all, m);
  33560. else
  33561. m.forEach(function (m) {
  33562. all[m] = true;
  33563. });
  33564. }
  33565. }
  33566. if (!nou)
  33567. all = Object.keys(all);
  33568. if (!self.nosort)
  33569. all = all.sort(alphasort);
  33570. // at *some* point we statted all of these
  33571. if (self.mark) {
  33572. for (var i = 0; i < all.length; i++) {
  33573. all[i] = self._mark(all[i]);
  33574. }
  33575. if (self.nodir) {
  33576. all = all.filter(function (e) {
  33577. var notDir = !(/\/$/.test(e));
  33578. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  33579. if (notDir && c)
  33580. notDir = c !== 'DIR' && !Array.isArray(c);
  33581. return notDir
  33582. });
  33583. }
  33584. }
  33585. if (self.ignore.length)
  33586. all = all.filter(function(m) {
  33587. return !isIgnored$2(self, m)
  33588. });
  33589. self.found = all;
  33590. }
  33591. function mark (self, p) {
  33592. var abs = makeAbs(self, p);
  33593. var c = self.cache[abs];
  33594. var m = p;
  33595. if (c) {
  33596. var isDir = c === 'DIR' || Array.isArray(c);
  33597. var slash = p.slice(-1) === '/';
  33598. if (isDir && !slash)
  33599. m += '/';
  33600. else if (!isDir && slash)
  33601. m = m.slice(0, -1);
  33602. if (m !== p) {
  33603. var mabs = makeAbs(self, m);
  33604. self.statCache[mabs] = self.statCache[abs];
  33605. self.cache[mabs] = self.cache[abs];
  33606. }
  33607. }
  33608. return m
  33609. }
  33610. // lotta situps...
  33611. function makeAbs (self, f) {
  33612. var abs = f;
  33613. if (f.charAt(0) === '/') {
  33614. abs = path$f.join(self.root, f);
  33615. } else if (isAbsolute$2(f) || f === '') {
  33616. abs = f;
  33617. } else if (self.changedCwd) {
  33618. abs = path$f.resolve(self.cwd, f);
  33619. } else {
  33620. abs = path$f.resolve(f);
  33621. }
  33622. if (process.platform === 'win32')
  33623. abs = abs.replace(/\\/g, '/');
  33624. return abs
  33625. }
  33626. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  33627. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  33628. function isIgnored$2 (self, path) {
  33629. if (!self.ignore.length)
  33630. return false
  33631. return self.ignore.some(function(item) {
  33632. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  33633. })
  33634. }
  33635. function childrenIgnored$2 (self, path) {
  33636. if (!self.ignore.length)
  33637. return false
  33638. return self.ignore.some(function(item) {
  33639. return !!(item.gmatcher && item.gmatcher.match(path))
  33640. })
  33641. }
  33642. var sync$3 = globSync$1;
  33643. globSync$1.GlobSync = GlobSync$1;
  33644. var fs$g = fs__default;
  33645. var rp$1 = fs_realpath;
  33646. var minimatch$1 = minimatch_1;
  33647. var path$e = path__default;
  33648. var assert$3 = require$$6__default;
  33649. var isAbsolute$1 = pathIsAbsolute.exports;
  33650. var common$5 = common$6;
  33651. var setopts$1 = common$5.setopts;
  33652. var ownProp$1 = common$5.ownProp;
  33653. var childrenIgnored$1 = common$5.childrenIgnored;
  33654. var isIgnored$1 = common$5.isIgnored;
  33655. function globSync$1 (pattern, options) {
  33656. if (typeof options === 'function' || arguments.length === 3)
  33657. throw new TypeError('callback provided to sync glob\n'+
  33658. 'See: https://github.com/isaacs/node-glob/issues/167')
  33659. return new GlobSync$1(pattern, options).found
  33660. }
  33661. function GlobSync$1 (pattern, options) {
  33662. if (!pattern)
  33663. throw new Error('must provide pattern')
  33664. if (typeof options === 'function' || arguments.length === 3)
  33665. throw new TypeError('callback provided to sync glob\n'+
  33666. 'See: https://github.com/isaacs/node-glob/issues/167')
  33667. if (!(this instanceof GlobSync$1))
  33668. return new GlobSync$1(pattern, options)
  33669. setopts$1(this, pattern, options);
  33670. if (this.noprocess)
  33671. return this
  33672. var n = this.minimatch.set.length;
  33673. this.matches = new Array(n);
  33674. for (var i = 0; i < n; i ++) {
  33675. this._process(this.minimatch.set[i], i, false);
  33676. }
  33677. this._finish();
  33678. }
  33679. GlobSync$1.prototype._finish = function () {
  33680. assert$3(this instanceof GlobSync$1);
  33681. if (this.realpath) {
  33682. var self = this;
  33683. this.matches.forEach(function (matchset, index) {
  33684. var set = self.matches[index] = Object.create(null);
  33685. for (var p in matchset) {
  33686. try {
  33687. p = self._makeAbs(p);
  33688. var real = rp$1.realpathSync(p, self.realpathCache);
  33689. set[real] = true;
  33690. } catch (er) {
  33691. if (er.syscall === 'stat')
  33692. set[self._makeAbs(p)] = true;
  33693. else
  33694. throw er
  33695. }
  33696. }
  33697. });
  33698. }
  33699. common$5.finish(this);
  33700. };
  33701. GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
  33702. assert$3(this instanceof GlobSync$1);
  33703. // Get the first [n] parts of pattern that are all strings.
  33704. var n = 0;
  33705. while (typeof pattern[n] === 'string') {
  33706. n ++;
  33707. }
  33708. // now n is the index of the first one that is *not* a string.
  33709. // See if there's anything else
  33710. var prefix;
  33711. switch (n) {
  33712. // if not, then this is rather simple
  33713. case pattern.length:
  33714. this._processSimple(pattern.join('/'), index);
  33715. return
  33716. case 0:
  33717. // pattern *starts* with some non-trivial item.
  33718. // going to readdir(cwd), but not include the prefix in matches.
  33719. prefix = null;
  33720. break
  33721. default:
  33722. // pattern has some string bits in the front.
  33723. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  33724. // or 'relative' like '../baz'
  33725. prefix = pattern.slice(0, n).join('/');
  33726. break
  33727. }
  33728. var remain = pattern.slice(n);
  33729. // get the list of entries.
  33730. var read;
  33731. if (prefix === null)
  33732. read = '.';
  33733. else if (isAbsolute$1(prefix) || isAbsolute$1(pattern.join('/'))) {
  33734. if (!prefix || !isAbsolute$1(prefix))
  33735. prefix = '/' + prefix;
  33736. read = prefix;
  33737. } else
  33738. read = prefix;
  33739. var abs = this._makeAbs(read);
  33740. //if ignored, skip processing
  33741. if (childrenIgnored$1(this, read))
  33742. return
  33743. var isGlobStar = remain[0] === minimatch$1.GLOBSTAR;
  33744. if (isGlobStar)
  33745. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  33746. else
  33747. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  33748. };
  33749. GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  33750. var entries = this._readdir(abs, inGlobStar);
  33751. // if the abs isn't a dir, then nothing can match!
  33752. if (!entries)
  33753. return
  33754. // It will only match dot entries if it starts with a dot, or if
  33755. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  33756. var pn = remain[0];
  33757. var negate = !!this.minimatch.negate;
  33758. var rawGlob = pn._glob;
  33759. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  33760. var matchedEntries = [];
  33761. for (var i = 0; i < entries.length; i++) {
  33762. var e = entries[i];
  33763. if (e.charAt(0) !== '.' || dotOk) {
  33764. var m;
  33765. if (negate && !prefix) {
  33766. m = !e.match(pn);
  33767. } else {
  33768. m = e.match(pn);
  33769. }
  33770. if (m)
  33771. matchedEntries.push(e);
  33772. }
  33773. }
  33774. var len = matchedEntries.length;
  33775. // If there are no matched entries, then nothing matches.
  33776. if (len === 0)
  33777. return
  33778. // if this is the last remaining pattern bit, then no need for
  33779. // an additional stat *unless* the user has specified mark or
  33780. // stat explicitly. We know they exist, since readdir returned
  33781. // them.
  33782. if (remain.length === 1 && !this.mark && !this.stat) {
  33783. if (!this.matches[index])
  33784. this.matches[index] = Object.create(null);
  33785. for (var i = 0; i < len; i ++) {
  33786. var e = matchedEntries[i];
  33787. if (prefix) {
  33788. if (prefix.slice(-1) !== '/')
  33789. e = prefix + '/' + e;
  33790. else
  33791. e = prefix + e;
  33792. }
  33793. if (e.charAt(0) === '/' && !this.nomount) {
  33794. e = path$e.join(this.root, e);
  33795. }
  33796. this._emitMatch(index, e);
  33797. }
  33798. // This was the last one, and no stats were needed
  33799. return
  33800. }
  33801. // now test all matched entries as stand-ins for that part
  33802. // of the pattern.
  33803. remain.shift();
  33804. for (var i = 0; i < len; i ++) {
  33805. var e = matchedEntries[i];
  33806. var newPattern;
  33807. if (prefix)
  33808. newPattern = [prefix, e];
  33809. else
  33810. newPattern = [e];
  33811. this._process(newPattern.concat(remain), index, inGlobStar);
  33812. }
  33813. };
  33814. GlobSync$1.prototype._emitMatch = function (index, e) {
  33815. if (isIgnored$1(this, e))
  33816. return
  33817. var abs = this._makeAbs(e);
  33818. if (this.mark)
  33819. e = this._mark(e);
  33820. if (this.absolute) {
  33821. e = abs;
  33822. }
  33823. if (this.matches[index][e])
  33824. return
  33825. if (this.nodir) {
  33826. var c = this.cache[abs];
  33827. if (c === 'DIR' || Array.isArray(c))
  33828. return
  33829. }
  33830. this.matches[index][e] = true;
  33831. if (this.stat)
  33832. this._stat(e);
  33833. };
  33834. GlobSync$1.prototype._readdirInGlobStar = function (abs) {
  33835. // follow all symlinked directories forever
  33836. // just proceed as if this is a non-globstar situation
  33837. if (this.follow)
  33838. return this._readdir(abs, false)
  33839. var entries;
  33840. var lstat;
  33841. try {
  33842. lstat = fs$g.lstatSync(abs);
  33843. } catch (er) {
  33844. if (er.code === 'ENOENT') {
  33845. // lstat failed, doesn't exist
  33846. return null
  33847. }
  33848. }
  33849. var isSym = lstat && lstat.isSymbolicLink();
  33850. this.symlinks[abs] = isSym;
  33851. // If it's not a symlink or a dir, then it's definitely a regular file.
  33852. // don't bother doing a readdir in that case.
  33853. if (!isSym && lstat && !lstat.isDirectory())
  33854. this.cache[abs] = 'FILE';
  33855. else
  33856. entries = this._readdir(abs, false);
  33857. return entries
  33858. };
  33859. GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
  33860. if (inGlobStar && !ownProp$1(this.symlinks, abs))
  33861. return this._readdirInGlobStar(abs)
  33862. if (ownProp$1(this.cache, abs)) {
  33863. var c = this.cache[abs];
  33864. if (!c || c === 'FILE')
  33865. return null
  33866. if (Array.isArray(c))
  33867. return c
  33868. }
  33869. try {
  33870. return this._readdirEntries(abs, fs$g.readdirSync(abs))
  33871. } catch (er) {
  33872. this._readdirError(abs, er);
  33873. return null
  33874. }
  33875. };
  33876. GlobSync$1.prototype._readdirEntries = function (abs, entries) {
  33877. // if we haven't asked to stat everything, then just
  33878. // assume that everything in there exists, so we can avoid
  33879. // having to stat it a second time.
  33880. if (!this.mark && !this.stat) {
  33881. for (var i = 0; i < entries.length; i ++) {
  33882. var e = entries[i];
  33883. if (abs === '/')
  33884. e = abs + e;
  33885. else
  33886. e = abs + '/' + e;
  33887. this.cache[e] = true;
  33888. }
  33889. }
  33890. this.cache[abs] = entries;
  33891. // mark and cache dir-ness
  33892. return entries
  33893. };
  33894. GlobSync$1.prototype._readdirError = function (f, er) {
  33895. // handle errors, and cache the information
  33896. switch (er.code) {
  33897. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  33898. case 'ENOTDIR': // totally normal. means it *does* exist.
  33899. var abs = this._makeAbs(f);
  33900. this.cache[abs] = 'FILE';
  33901. if (abs === this.cwdAbs) {
  33902. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  33903. error.path = this.cwd;
  33904. error.code = er.code;
  33905. throw error
  33906. }
  33907. break
  33908. case 'ENOENT': // not terribly unusual
  33909. case 'ELOOP':
  33910. case 'ENAMETOOLONG':
  33911. case 'UNKNOWN':
  33912. this.cache[this._makeAbs(f)] = false;
  33913. break
  33914. default: // some unusual error. Treat as failure.
  33915. this.cache[this._makeAbs(f)] = false;
  33916. if (this.strict)
  33917. throw er
  33918. if (!this.silent)
  33919. console.error('glob error', er);
  33920. break
  33921. }
  33922. };
  33923. GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  33924. var entries = this._readdir(abs, inGlobStar);
  33925. // no entries means not a dir, so it can never have matches
  33926. // foo.txt/** doesn't match foo.txt
  33927. if (!entries)
  33928. return
  33929. // test without the globstar, and with every child both below
  33930. // and replacing the globstar.
  33931. var remainWithoutGlobStar = remain.slice(1);
  33932. var gspref = prefix ? [ prefix ] : [];
  33933. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  33934. // the noGlobStar pattern exits the inGlobStar state
  33935. this._process(noGlobStar, index, false);
  33936. var len = entries.length;
  33937. var isSym = this.symlinks[abs];
  33938. // If it's a symlink, and we're in a globstar, then stop
  33939. if (isSym && inGlobStar)
  33940. return
  33941. for (var i = 0; i < len; i++) {
  33942. var e = entries[i];
  33943. if (e.charAt(0) === '.' && !this.dot)
  33944. continue
  33945. // these two cases enter the inGlobStar state
  33946. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  33947. this._process(instead, index, true);
  33948. var below = gspref.concat(entries[i], remain);
  33949. this._process(below, index, true);
  33950. }
  33951. };
  33952. GlobSync$1.prototype._processSimple = function (prefix, index) {
  33953. // XXX review this. Shouldn't it be doing the mounting etc
  33954. // before doing stat? kinda weird?
  33955. var exists = this._stat(prefix);
  33956. if (!this.matches[index])
  33957. this.matches[index] = Object.create(null);
  33958. // If it doesn't exist, then just mark the lack of results
  33959. if (!exists)
  33960. return
  33961. if (prefix && isAbsolute$1(prefix) && !this.nomount) {
  33962. var trail = /[\/\\]$/.test(prefix);
  33963. if (prefix.charAt(0) === '/') {
  33964. prefix = path$e.join(this.root, prefix);
  33965. } else {
  33966. prefix = path$e.resolve(this.root, prefix);
  33967. if (trail)
  33968. prefix += '/';
  33969. }
  33970. }
  33971. if (process.platform === 'win32')
  33972. prefix = prefix.replace(/\\/g, '/');
  33973. // Mark this as a match
  33974. this._emitMatch(index, prefix);
  33975. };
  33976. // Returns either 'DIR', 'FILE', or false
  33977. GlobSync$1.prototype._stat = function (f) {
  33978. var abs = this._makeAbs(f);
  33979. var needDir = f.slice(-1) === '/';
  33980. if (f.length > this.maxLength)
  33981. return false
  33982. if (!this.stat && ownProp$1(this.cache, abs)) {
  33983. var c = this.cache[abs];
  33984. if (Array.isArray(c))
  33985. c = 'DIR';
  33986. // It exists, but maybe not how we need it
  33987. if (!needDir || c === 'DIR')
  33988. return c
  33989. if (needDir && c === 'FILE')
  33990. return false
  33991. // otherwise we have to stat, because maybe c=true
  33992. // if we know it exists, but not what it is.
  33993. }
  33994. var stat = this.statCache[abs];
  33995. if (!stat) {
  33996. var lstat;
  33997. try {
  33998. lstat = fs$g.lstatSync(abs);
  33999. } catch (er) {
  34000. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  34001. this.statCache[abs] = false;
  34002. return false
  34003. }
  34004. }
  34005. if (lstat && lstat.isSymbolicLink()) {
  34006. try {
  34007. stat = fs$g.statSync(abs);
  34008. } catch (er) {
  34009. stat = lstat;
  34010. }
  34011. } else {
  34012. stat = lstat;
  34013. }
  34014. }
  34015. this.statCache[abs] = stat;
  34016. var c = true;
  34017. if (stat)
  34018. c = stat.isDirectory() ? 'DIR' : 'FILE';
  34019. this.cache[abs] = this.cache[abs] || c;
  34020. if (needDir && c === 'FILE')
  34021. return false
  34022. return c
  34023. };
  34024. GlobSync$1.prototype._mark = function (p) {
  34025. return common$5.mark(this, p)
  34026. };
  34027. GlobSync$1.prototype._makeAbs = function (f) {
  34028. return common$5.makeAbs(this, f)
  34029. };
  34030. // Returns a wrapper function that returns a wrapped callback
  34031. // The wrapper function should do some stuff, and return a
  34032. // presumably different callback function.
  34033. // This makes sure that own properties are retained, so that
  34034. // decorations and such are not lost along the way.
  34035. var wrappy_1 = wrappy$2;
  34036. function wrappy$2 (fn, cb) {
  34037. if (fn && cb) return wrappy$2(fn)(cb)
  34038. if (typeof fn !== 'function')
  34039. throw new TypeError('need wrapper function')
  34040. Object.keys(fn).forEach(function (k) {
  34041. wrapper[k] = fn[k];
  34042. });
  34043. return wrapper
  34044. function wrapper() {
  34045. var args = new Array(arguments.length);
  34046. for (var i = 0; i < args.length; i++) {
  34047. args[i] = arguments[i];
  34048. }
  34049. var ret = fn.apply(this, args);
  34050. var cb = args[args.length-1];
  34051. if (typeof ret === 'function' && ret !== cb) {
  34052. Object.keys(cb).forEach(function (k) {
  34053. ret[k] = cb[k];
  34054. });
  34055. }
  34056. return ret
  34057. }
  34058. }
  34059. var once$3 = {exports: {}};
  34060. var wrappy$1 = wrappy_1;
  34061. once$3.exports = wrappy$1(once$2);
  34062. once$3.exports.strict = wrappy$1(onceStrict);
  34063. once$2.proto = once$2(function () {
  34064. Object.defineProperty(Function.prototype, 'once', {
  34065. value: function () {
  34066. return once$2(this)
  34067. },
  34068. configurable: true
  34069. });
  34070. Object.defineProperty(Function.prototype, 'onceStrict', {
  34071. value: function () {
  34072. return onceStrict(this)
  34073. },
  34074. configurable: true
  34075. });
  34076. });
  34077. function once$2 (fn) {
  34078. var f = function () {
  34079. if (f.called) return f.value
  34080. f.called = true;
  34081. return f.value = fn.apply(this, arguments)
  34082. };
  34083. f.called = false;
  34084. return f
  34085. }
  34086. function onceStrict (fn) {
  34087. var f = function () {
  34088. if (f.called)
  34089. throw new Error(f.onceError)
  34090. f.called = true;
  34091. return f.value = fn.apply(this, arguments)
  34092. };
  34093. var name = fn.name || 'Function wrapped with `once`';
  34094. f.onceError = name + " shouldn't be called more than once";
  34095. f.called = false;
  34096. return f
  34097. }
  34098. var wrappy = wrappy_1;
  34099. var reqs = Object.create(null);
  34100. var once$1 = once$3.exports;
  34101. var inflight_1 = wrappy(inflight$1);
  34102. function inflight$1 (key, cb) {
  34103. if (reqs[key]) {
  34104. reqs[key].push(cb);
  34105. return null
  34106. } else {
  34107. reqs[key] = [cb];
  34108. return makeres(key)
  34109. }
  34110. }
  34111. function makeres (key) {
  34112. return once$1(function RES () {
  34113. var cbs = reqs[key];
  34114. var len = cbs.length;
  34115. var args = slice(arguments);
  34116. // XXX It's somewhat ambiguous whether a new callback added in this
  34117. // pass should be queued for later execution if something in the
  34118. // list of callbacks throws, or if it should just be discarded.
  34119. // However, it's such an edge case that it hardly matters, and either
  34120. // choice is likely as surprising as the other.
  34121. // As it happens, we do go ahead and schedule it for later execution.
  34122. try {
  34123. for (var i = 0; i < len; i++) {
  34124. cbs[i].apply(null, args);
  34125. }
  34126. } finally {
  34127. if (cbs.length > len) {
  34128. // added more in the interim.
  34129. // de-zalgo, just in case, but don't call again.
  34130. cbs.splice(0, len);
  34131. process.nextTick(function () {
  34132. RES.apply(null, args);
  34133. });
  34134. } else {
  34135. delete reqs[key];
  34136. }
  34137. }
  34138. })
  34139. }
  34140. function slice (args) {
  34141. var length = args.length;
  34142. var array = [];
  34143. for (var i = 0; i < length; i++) array[i] = args[i];
  34144. return array
  34145. }
  34146. // Approach:
  34147. //
  34148. // 1. Get the minimatch set
  34149. // 2. For each pattern in the set, PROCESS(pattern, false)
  34150. // 3. Store matches per-set, then uniq them
  34151. //
  34152. // PROCESS(pattern, inGlobStar)
  34153. // Get the first [n] items from pattern that are all strings
  34154. // Join these together. This is PREFIX.
  34155. // If there is no more remaining, then stat(PREFIX) and
  34156. // add to matches if it succeeds. END.
  34157. //
  34158. // If inGlobStar and PREFIX is symlink and points to dir
  34159. // set ENTRIES = []
  34160. // else readdir(PREFIX) as ENTRIES
  34161. // If fail, END
  34162. //
  34163. // with ENTRIES
  34164. // If pattern[n] is GLOBSTAR
  34165. // // handle the case where the globstar match is empty
  34166. // // by pruning it out, and testing the resulting pattern
  34167. // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
  34168. // // handle other cases.
  34169. // for ENTRY in ENTRIES (not dotfiles)
  34170. // // attach globstar + tail onto the entry
  34171. // // Mark that this entry is a globstar match
  34172. // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
  34173. //
  34174. // else // not globstar
  34175. // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
  34176. // Test ENTRY against pattern[n]
  34177. // If fails, continue
  34178. // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
  34179. //
  34180. // Caveat:
  34181. // Cache all stats and readdirs results to minimize syscall. Since all
  34182. // we ever care about is existence and directory-ness, we can just keep
  34183. // `true` for files, and [children,...] for directories, or `false` for
  34184. // things that don't exist.
  34185. var glob_1 = glob;
  34186. var fs$f = fs__default;
  34187. var rp = fs_realpath;
  34188. var minimatch = minimatch_1;
  34189. var inherits = inherits$1.exports;
  34190. var EE$1 = require$$0__default$6.EventEmitter;
  34191. var path$d = path__default;
  34192. var assert$2 = require$$6__default;
  34193. var isAbsolute = pathIsAbsolute.exports;
  34194. var globSync = sync$3;
  34195. var common$4 = common$6;
  34196. var setopts = common$4.setopts;
  34197. var ownProp = common$4.ownProp;
  34198. var inflight = inflight_1;
  34199. var childrenIgnored = common$4.childrenIgnored;
  34200. var isIgnored = common$4.isIgnored;
  34201. var once = once$3.exports;
  34202. function glob (pattern, options, cb) {
  34203. if (typeof options === 'function') cb = options, options = {};
  34204. if (!options) options = {};
  34205. if (options.sync) {
  34206. if (cb)
  34207. throw new TypeError('callback provided to sync glob')
  34208. return globSync(pattern, options)
  34209. }
  34210. return new Glob(pattern, options, cb)
  34211. }
  34212. glob.sync = globSync;
  34213. var GlobSync = glob.GlobSync = globSync.GlobSync;
  34214. // old api surface
  34215. glob.glob = glob;
  34216. function extend (origin, add) {
  34217. if (add === null || typeof add !== 'object') {
  34218. return origin
  34219. }
  34220. var keys = Object.keys(add);
  34221. var i = keys.length;
  34222. while (i--) {
  34223. origin[keys[i]] = add[keys[i]];
  34224. }
  34225. return origin
  34226. }
  34227. glob.hasMagic = function (pattern, options_) {
  34228. var options = extend({}, options_);
  34229. options.noprocess = true;
  34230. var g = new Glob(pattern, options);
  34231. var set = g.minimatch.set;
  34232. if (!pattern)
  34233. return false
  34234. if (set.length > 1)
  34235. return true
  34236. for (var j = 0; j < set[0].length; j++) {
  34237. if (typeof set[0][j] !== 'string')
  34238. return true
  34239. }
  34240. return false
  34241. };
  34242. glob.Glob = Glob;
  34243. inherits(Glob, EE$1);
  34244. function Glob (pattern, options, cb) {
  34245. if (typeof options === 'function') {
  34246. cb = options;
  34247. options = null;
  34248. }
  34249. if (options && options.sync) {
  34250. if (cb)
  34251. throw new TypeError('callback provided to sync glob')
  34252. return new GlobSync(pattern, options)
  34253. }
  34254. if (!(this instanceof Glob))
  34255. return new Glob(pattern, options, cb)
  34256. setopts(this, pattern, options);
  34257. this._didRealPath = false;
  34258. // process each pattern in the minimatch set
  34259. var n = this.minimatch.set.length;
  34260. // The matches are stored as {<filename>: true,...} so that
  34261. // duplicates are automagically pruned.
  34262. // Later, we do an Object.keys() on these.
  34263. // Keep them as a list so we can fill in when nonull is set.
  34264. this.matches = new Array(n);
  34265. if (typeof cb === 'function') {
  34266. cb = once(cb);
  34267. this.on('error', cb);
  34268. this.on('end', function (matches) {
  34269. cb(null, matches);
  34270. });
  34271. }
  34272. var self = this;
  34273. this._processing = 0;
  34274. this._emitQueue = [];
  34275. this._processQueue = [];
  34276. this.paused = false;
  34277. if (this.noprocess)
  34278. return this
  34279. if (n === 0)
  34280. return done()
  34281. var sync = true;
  34282. for (var i = 0; i < n; i ++) {
  34283. this._process(this.minimatch.set[i], i, false, done);
  34284. }
  34285. sync = false;
  34286. function done () {
  34287. --self._processing;
  34288. if (self._processing <= 0) {
  34289. if (sync) {
  34290. process.nextTick(function () {
  34291. self._finish();
  34292. });
  34293. } else {
  34294. self._finish();
  34295. }
  34296. }
  34297. }
  34298. }
  34299. Glob.prototype._finish = function () {
  34300. assert$2(this instanceof Glob);
  34301. if (this.aborted)
  34302. return
  34303. if (this.realpath && !this._didRealpath)
  34304. return this._realpath()
  34305. common$4.finish(this);
  34306. this.emit('end', this.found);
  34307. };
  34308. Glob.prototype._realpath = function () {
  34309. if (this._didRealpath)
  34310. return
  34311. this._didRealpath = true;
  34312. var n = this.matches.length;
  34313. if (n === 0)
  34314. return this._finish()
  34315. var self = this;
  34316. for (var i = 0; i < this.matches.length; i++)
  34317. this._realpathSet(i, next);
  34318. function next () {
  34319. if (--n === 0)
  34320. self._finish();
  34321. }
  34322. };
  34323. Glob.prototype._realpathSet = function (index, cb) {
  34324. var matchset = this.matches[index];
  34325. if (!matchset)
  34326. return cb()
  34327. var found = Object.keys(matchset);
  34328. var self = this;
  34329. var n = found.length;
  34330. if (n === 0)
  34331. return cb()
  34332. var set = this.matches[index] = Object.create(null);
  34333. found.forEach(function (p, i) {
  34334. // If there's a problem with the stat, then it means that
  34335. // one or more of the links in the realpath couldn't be
  34336. // resolved. just return the abs value in that case.
  34337. p = self._makeAbs(p);
  34338. rp.realpath(p, self.realpathCache, function (er, real) {
  34339. if (!er)
  34340. set[real] = true;
  34341. else if (er.syscall === 'stat')
  34342. set[p] = true;
  34343. else
  34344. self.emit('error', er); // srsly wtf right here
  34345. if (--n === 0) {
  34346. self.matches[index] = set;
  34347. cb();
  34348. }
  34349. });
  34350. });
  34351. };
  34352. Glob.prototype._mark = function (p) {
  34353. return common$4.mark(this, p)
  34354. };
  34355. Glob.prototype._makeAbs = function (f) {
  34356. return common$4.makeAbs(this, f)
  34357. };
  34358. Glob.prototype.abort = function () {
  34359. this.aborted = true;
  34360. this.emit('abort');
  34361. };
  34362. Glob.prototype.pause = function () {
  34363. if (!this.paused) {
  34364. this.paused = true;
  34365. this.emit('pause');
  34366. }
  34367. };
  34368. Glob.prototype.resume = function () {
  34369. if (this.paused) {
  34370. this.emit('resume');
  34371. this.paused = false;
  34372. if (this._emitQueue.length) {
  34373. var eq = this._emitQueue.slice(0);
  34374. this._emitQueue.length = 0;
  34375. for (var i = 0; i < eq.length; i ++) {
  34376. var e = eq[i];
  34377. this._emitMatch(e[0], e[1]);
  34378. }
  34379. }
  34380. if (this._processQueue.length) {
  34381. var pq = this._processQueue.slice(0);
  34382. this._processQueue.length = 0;
  34383. for (var i = 0; i < pq.length; i ++) {
  34384. var p = pq[i];
  34385. this._processing--;
  34386. this._process(p[0], p[1], p[2], p[3]);
  34387. }
  34388. }
  34389. }
  34390. };
  34391. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  34392. assert$2(this instanceof Glob);
  34393. assert$2(typeof cb === 'function');
  34394. if (this.aborted)
  34395. return
  34396. this._processing++;
  34397. if (this.paused) {
  34398. this._processQueue.push([pattern, index, inGlobStar, cb]);
  34399. return
  34400. }
  34401. //console.error('PROCESS %d', this._processing, pattern)
  34402. // Get the first [n] parts of pattern that are all strings.
  34403. var n = 0;
  34404. while (typeof pattern[n] === 'string') {
  34405. n ++;
  34406. }
  34407. // now n is the index of the first one that is *not* a string.
  34408. // see if there's anything else
  34409. var prefix;
  34410. switch (n) {
  34411. // if not, then this is rather simple
  34412. case pattern.length:
  34413. this._processSimple(pattern.join('/'), index, cb);
  34414. return
  34415. case 0:
  34416. // pattern *starts* with some non-trivial item.
  34417. // going to readdir(cwd), but not include the prefix in matches.
  34418. prefix = null;
  34419. break
  34420. default:
  34421. // pattern has some string bits in the front.
  34422. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  34423. // or 'relative' like '../baz'
  34424. prefix = pattern.slice(0, n).join('/');
  34425. break
  34426. }
  34427. var remain = pattern.slice(n);
  34428. // get the list of entries.
  34429. var read;
  34430. if (prefix === null)
  34431. read = '.';
  34432. else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
  34433. if (!prefix || !isAbsolute(prefix))
  34434. prefix = '/' + prefix;
  34435. read = prefix;
  34436. } else
  34437. read = prefix;
  34438. var abs = this._makeAbs(read);
  34439. //if ignored, skip _processing
  34440. if (childrenIgnored(this, read))
  34441. return cb()
  34442. var isGlobStar = remain[0] === minimatch.GLOBSTAR;
  34443. if (isGlobStar)
  34444. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  34445. else
  34446. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  34447. };
  34448. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  34449. var self = this;
  34450. this._readdir(abs, inGlobStar, function (er, entries) {
  34451. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  34452. });
  34453. };
  34454. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  34455. // if the abs isn't a dir, then nothing can match!
  34456. if (!entries)
  34457. return cb()
  34458. // It will only match dot entries if it starts with a dot, or if
  34459. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  34460. var pn = remain[0];
  34461. var negate = !!this.minimatch.negate;
  34462. var rawGlob = pn._glob;
  34463. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  34464. var matchedEntries = [];
  34465. for (var i = 0; i < entries.length; i++) {
  34466. var e = entries[i];
  34467. if (e.charAt(0) !== '.' || dotOk) {
  34468. var m;
  34469. if (negate && !prefix) {
  34470. m = !e.match(pn);
  34471. } else {
  34472. m = e.match(pn);
  34473. }
  34474. if (m)
  34475. matchedEntries.push(e);
  34476. }
  34477. }
  34478. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  34479. var len = matchedEntries.length;
  34480. // If there are no matched entries, then nothing matches.
  34481. if (len === 0)
  34482. return cb()
  34483. // if this is the last remaining pattern bit, then no need for
  34484. // an additional stat *unless* the user has specified mark or
  34485. // stat explicitly. We know they exist, since readdir returned
  34486. // them.
  34487. if (remain.length === 1 && !this.mark && !this.stat) {
  34488. if (!this.matches[index])
  34489. this.matches[index] = Object.create(null);
  34490. for (var i = 0; i < len; i ++) {
  34491. var e = matchedEntries[i];
  34492. if (prefix) {
  34493. if (prefix !== '/')
  34494. e = prefix + '/' + e;
  34495. else
  34496. e = prefix + e;
  34497. }
  34498. if (e.charAt(0) === '/' && !this.nomount) {
  34499. e = path$d.join(this.root, e);
  34500. }
  34501. this._emitMatch(index, e);
  34502. }
  34503. // This was the last one, and no stats were needed
  34504. return cb()
  34505. }
  34506. // now test all matched entries as stand-ins for that part
  34507. // of the pattern.
  34508. remain.shift();
  34509. for (var i = 0; i < len; i ++) {
  34510. var e = matchedEntries[i];
  34511. if (prefix) {
  34512. if (prefix !== '/')
  34513. e = prefix + '/' + e;
  34514. else
  34515. e = prefix + e;
  34516. }
  34517. this._process([e].concat(remain), index, inGlobStar, cb);
  34518. }
  34519. cb();
  34520. };
  34521. Glob.prototype._emitMatch = function (index, e) {
  34522. if (this.aborted)
  34523. return
  34524. if (isIgnored(this, e))
  34525. return
  34526. if (this.paused) {
  34527. this._emitQueue.push([index, e]);
  34528. return
  34529. }
  34530. var abs = isAbsolute(e) ? e : this._makeAbs(e);
  34531. if (this.mark)
  34532. e = this._mark(e);
  34533. if (this.absolute)
  34534. e = abs;
  34535. if (this.matches[index][e])
  34536. return
  34537. if (this.nodir) {
  34538. var c = this.cache[abs];
  34539. if (c === 'DIR' || Array.isArray(c))
  34540. return
  34541. }
  34542. this.matches[index][e] = true;
  34543. var st = this.statCache[abs];
  34544. if (st)
  34545. this.emit('stat', e, st);
  34546. this.emit('match', e);
  34547. };
  34548. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  34549. if (this.aborted)
  34550. return
  34551. // follow all symlinked directories forever
  34552. // just proceed as if this is a non-globstar situation
  34553. if (this.follow)
  34554. return this._readdir(abs, false, cb)
  34555. var lstatkey = 'lstat\0' + abs;
  34556. var self = this;
  34557. var lstatcb = inflight(lstatkey, lstatcb_);
  34558. if (lstatcb)
  34559. fs$f.lstat(abs, lstatcb);
  34560. function lstatcb_ (er, lstat) {
  34561. if (er && er.code === 'ENOENT')
  34562. return cb()
  34563. var isSym = lstat && lstat.isSymbolicLink();
  34564. self.symlinks[abs] = isSym;
  34565. // If it's not a symlink or a dir, then it's definitely a regular file.
  34566. // don't bother doing a readdir in that case.
  34567. if (!isSym && lstat && !lstat.isDirectory()) {
  34568. self.cache[abs] = 'FILE';
  34569. cb();
  34570. } else
  34571. self._readdir(abs, false, cb);
  34572. }
  34573. };
  34574. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  34575. if (this.aborted)
  34576. return
  34577. cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb);
  34578. if (!cb)
  34579. return
  34580. //console.error('RD %j %j', +inGlobStar, abs)
  34581. if (inGlobStar && !ownProp(this.symlinks, abs))
  34582. return this._readdirInGlobStar(abs, cb)
  34583. if (ownProp(this.cache, abs)) {
  34584. var c = this.cache[abs];
  34585. if (!c || c === 'FILE')
  34586. return cb()
  34587. if (Array.isArray(c))
  34588. return cb(null, c)
  34589. }
  34590. fs$f.readdir(abs, readdirCb(this, abs, cb));
  34591. };
  34592. function readdirCb (self, abs, cb) {
  34593. return function (er, entries) {
  34594. if (er)
  34595. self._readdirError(abs, er, cb);
  34596. else
  34597. self._readdirEntries(abs, entries, cb);
  34598. }
  34599. }
  34600. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  34601. if (this.aborted)
  34602. return
  34603. // if we haven't asked to stat everything, then just
  34604. // assume that everything in there exists, so we can avoid
  34605. // having to stat it a second time.
  34606. if (!this.mark && !this.stat) {
  34607. for (var i = 0; i < entries.length; i ++) {
  34608. var e = entries[i];
  34609. if (abs === '/')
  34610. e = abs + e;
  34611. else
  34612. e = abs + '/' + e;
  34613. this.cache[e] = true;
  34614. }
  34615. }
  34616. this.cache[abs] = entries;
  34617. return cb(null, entries)
  34618. };
  34619. Glob.prototype._readdirError = function (f, er, cb) {
  34620. if (this.aborted)
  34621. return
  34622. // handle errors, and cache the information
  34623. switch (er.code) {
  34624. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  34625. case 'ENOTDIR': // totally normal. means it *does* exist.
  34626. var abs = this._makeAbs(f);
  34627. this.cache[abs] = 'FILE';
  34628. if (abs === this.cwdAbs) {
  34629. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  34630. error.path = this.cwd;
  34631. error.code = er.code;
  34632. this.emit('error', error);
  34633. this.abort();
  34634. }
  34635. break
  34636. case 'ENOENT': // not terribly unusual
  34637. case 'ELOOP':
  34638. case 'ENAMETOOLONG':
  34639. case 'UNKNOWN':
  34640. this.cache[this._makeAbs(f)] = false;
  34641. break
  34642. default: // some unusual error. Treat as failure.
  34643. this.cache[this._makeAbs(f)] = false;
  34644. if (this.strict) {
  34645. this.emit('error', er);
  34646. // If the error is handled, then we abort
  34647. // if not, we threw out of here
  34648. this.abort();
  34649. }
  34650. if (!this.silent)
  34651. console.error('glob error', er);
  34652. break
  34653. }
  34654. return cb()
  34655. };
  34656. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  34657. var self = this;
  34658. this._readdir(abs, inGlobStar, function (er, entries) {
  34659. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  34660. });
  34661. };
  34662. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  34663. //console.error('pgs2', prefix, remain[0], entries)
  34664. // no entries means not a dir, so it can never have matches
  34665. // foo.txt/** doesn't match foo.txt
  34666. if (!entries)
  34667. return cb()
  34668. // test without the globstar, and with every child both below
  34669. // and replacing the globstar.
  34670. var remainWithoutGlobStar = remain.slice(1);
  34671. var gspref = prefix ? [ prefix ] : [];
  34672. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  34673. // the noGlobStar pattern exits the inGlobStar state
  34674. this._process(noGlobStar, index, false, cb);
  34675. var isSym = this.symlinks[abs];
  34676. var len = entries.length;
  34677. // If it's a symlink, and we're in a globstar, then stop
  34678. if (isSym && inGlobStar)
  34679. return cb()
  34680. for (var i = 0; i < len; i++) {
  34681. var e = entries[i];
  34682. if (e.charAt(0) === '.' && !this.dot)
  34683. continue
  34684. // these two cases enter the inGlobStar state
  34685. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  34686. this._process(instead, index, true, cb);
  34687. var below = gspref.concat(entries[i], remain);
  34688. this._process(below, index, true, cb);
  34689. }
  34690. cb();
  34691. };
  34692. Glob.prototype._processSimple = function (prefix, index, cb) {
  34693. // XXX review this. Shouldn't it be doing the mounting etc
  34694. // before doing stat? kinda weird?
  34695. var self = this;
  34696. this._stat(prefix, function (er, exists) {
  34697. self._processSimple2(prefix, index, er, exists, cb);
  34698. });
  34699. };
  34700. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  34701. //console.error('ps2', prefix, exists)
  34702. if (!this.matches[index])
  34703. this.matches[index] = Object.create(null);
  34704. // If it doesn't exist, then just mark the lack of results
  34705. if (!exists)
  34706. return cb()
  34707. if (prefix && isAbsolute(prefix) && !this.nomount) {
  34708. var trail = /[\/\\]$/.test(prefix);
  34709. if (prefix.charAt(0) === '/') {
  34710. prefix = path$d.join(this.root, prefix);
  34711. } else {
  34712. prefix = path$d.resolve(this.root, prefix);
  34713. if (trail)
  34714. prefix += '/';
  34715. }
  34716. }
  34717. if (process.platform === 'win32')
  34718. prefix = prefix.replace(/\\/g, '/');
  34719. // Mark this as a match
  34720. this._emitMatch(index, prefix);
  34721. cb();
  34722. };
  34723. // Returns either 'DIR', 'FILE', or false
  34724. Glob.prototype._stat = function (f, cb) {
  34725. var abs = this._makeAbs(f);
  34726. var needDir = f.slice(-1) === '/';
  34727. if (f.length > this.maxLength)
  34728. return cb()
  34729. if (!this.stat && ownProp(this.cache, abs)) {
  34730. var c = this.cache[abs];
  34731. if (Array.isArray(c))
  34732. c = 'DIR';
  34733. // It exists, but maybe not how we need it
  34734. if (!needDir || c === 'DIR')
  34735. return cb(null, c)
  34736. if (needDir && c === 'FILE')
  34737. return cb()
  34738. // otherwise we have to stat, because maybe c=true
  34739. // if we know it exists, but not what it is.
  34740. }
  34741. var stat = this.statCache[abs];
  34742. if (stat !== undefined) {
  34743. if (stat === false)
  34744. return cb(null, stat)
  34745. else {
  34746. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  34747. if (needDir && type === 'FILE')
  34748. return cb()
  34749. else
  34750. return cb(null, type, stat)
  34751. }
  34752. }
  34753. var self = this;
  34754. var statcb = inflight('stat\0' + abs, lstatcb_);
  34755. if (statcb)
  34756. fs$f.lstat(abs, statcb);
  34757. function lstatcb_ (er, lstat) {
  34758. if (lstat && lstat.isSymbolicLink()) {
  34759. // If it's a symlink, then treat it as the target, unless
  34760. // the target does not exist, then treat it as a file.
  34761. return fs$f.stat(abs, function (er, stat) {
  34762. if (er)
  34763. self._stat2(f, abs, null, lstat, cb);
  34764. else
  34765. self._stat2(f, abs, er, stat, cb);
  34766. })
  34767. } else {
  34768. self._stat2(f, abs, er, lstat, cb);
  34769. }
  34770. }
  34771. };
  34772. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  34773. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  34774. this.statCache[abs] = false;
  34775. return cb()
  34776. }
  34777. var needDir = f.slice(-1) === '/';
  34778. this.statCache[abs] = stat;
  34779. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  34780. return cb(null, false, stat)
  34781. var c = true;
  34782. if (stat)
  34783. c = stat.isDirectory() ? 'DIR' : 'FILE';
  34784. this.cache[abs] = this.cache[abs] || c;
  34785. if (needDir && c === 'FILE')
  34786. return cb()
  34787. return cb(null, c, stat)
  34788. };
  34789. // @ts-check
  34790. /** @typedef { import('estree').BaseNode} BaseNode */
  34791. /** @typedef {{
  34792. skip: () => void;
  34793. remove: () => void;
  34794. replace: (node: BaseNode) => void;
  34795. }} WalkerContext */
  34796. class WalkerBase {
  34797. constructor() {
  34798. /** @type {boolean} */
  34799. this.should_skip = false;
  34800. /** @type {boolean} */
  34801. this.should_remove = false;
  34802. /** @type {BaseNode | null} */
  34803. this.replacement = null;
  34804. /** @type {WalkerContext} */
  34805. this.context = {
  34806. skip: () => (this.should_skip = true),
  34807. remove: () => (this.should_remove = true),
  34808. replace: (node) => (this.replacement = node)
  34809. };
  34810. }
  34811. /**
  34812. *
  34813. * @param {any} parent
  34814. * @param {string} prop
  34815. * @param {number} index
  34816. * @param {BaseNode} node
  34817. */
  34818. replace(parent, prop, index, node) {
  34819. if (parent) {
  34820. if (index !== null) {
  34821. parent[prop][index] = node;
  34822. } else {
  34823. parent[prop] = node;
  34824. }
  34825. }
  34826. }
  34827. /**
  34828. *
  34829. * @param {any} parent
  34830. * @param {string} prop
  34831. * @param {number} index
  34832. */
  34833. remove(parent, prop, index) {
  34834. if (parent) {
  34835. if (index !== null) {
  34836. parent[prop].splice(index, 1);
  34837. } else {
  34838. delete parent[prop];
  34839. }
  34840. }
  34841. }
  34842. }
  34843. // @ts-check
  34844. /** @typedef { import('estree').BaseNode} BaseNode */
  34845. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  34846. /** @typedef {(
  34847. * this: WalkerContext,
  34848. * node: BaseNode,
  34849. * parent: BaseNode,
  34850. * key: string,
  34851. * index: number
  34852. * ) => void} SyncHandler */
  34853. class SyncWalker extends WalkerBase {
  34854. /**
  34855. *
  34856. * @param {SyncHandler} enter
  34857. * @param {SyncHandler} leave
  34858. */
  34859. constructor(enter, leave) {
  34860. super();
  34861. /** @type {SyncHandler} */
  34862. this.enter = enter;
  34863. /** @type {SyncHandler} */
  34864. this.leave = leave;
  34865. }
  34866. /**
  34867. *
  34868. * @param {BaseNode} node
  34869. * @param {BaseNode} parent
  34870. * @param {string} [prop]
  34871. * @param {number} [index]
  34872. * @returns {BaseNode}
  34873. */
  34874. visit(node, parent, prop, index) {
  34875. if (node) {
  34876. if (this.enter) {
  34877. const _should_skip = this.should_skip;
  34878. const _should_remove = this.should_remove;
  34879. const _replacement = this.replacement;
  34880. this.should_skip = false;
  34881. this.should_remove = false;
  34882. this.replacement = null;
  34883. this.enter.call(this.context, node, parent, prop, index);
  34884. if (this.replacement) {
  34885. node = this.replacement;
  34886. this.replace(parent, prop, index, node);
  34887. }
  34888. if (this.should_remove) {
  34889. this.remove(parent, prop, index);
  34890. }
  34891. const skipped = this.should_skip;
  34892. const removed = this.should_remove;
  34893. this.should_skip = _should_skip;
  34894. this.should_remove = _should_remove;
  34895. this.replacement = _replacement;
  34896. if (skipped) return node;
  34897. if (removed) return null;
  34898. }
  34899. for (const key in node) {
  34900. const value = node[key];
  34901. if (typeof value !== "object") {
  34902. continue;
  34903. } else if (Array.isArray(value)) {
  34904. for (let i = 0; i < value.length; i += 1) {
  34905. if (value[i] !== null && typeof value[i].type === 'string') {
  34906. if (!this.visit(value[i], node, key, i)) {
  34907. // removed
  34908. i--;
  34909. }
  34910. }
  34911. }
  34912. } else if (value !== null && typeof value.type === "string") {
  34913. this.visit(value, node, key, null);
  34914. }
  34915. }
  34916. if (this.leave) {
  34917. const _replacement = this.replacement;
  34918. const _should_remove = this.should_remove;
  34919. this.replacement = null;
  34920. this.should_remove = false;
  34921. this.leave.call(this.context, node, parent, prop, index);
  34922. if (this.replacement) {
  34923. node = this.replacement;
  34924. this.replace(parent, prop, index, node);
  34925. }
  34926. if (this.should_remove) {
  34927. this.remove(parent, prop, index);
  34928. }
  34929. const removed = this.should_remove;
  34930. this.replacement = _replacement;
  34931. this.should_remove = _should_remove;
  34932. if (removed) return null;
  34933. }
  34934. }
  34935. return node;
  34936. }
  34937. }
  34938. // @ts-check
  34939. /** @typedef { import('estree').BaseNode} BaseNode */
  34940. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  34941. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  34942. /**
  34943. *
  34944. * @param {BaseNode} ast
  34945. * @param {{
  34946. * enter?: SyncHandler
  34947. * leave?: SyncHandler
  34948. * }} walker
  34949. * @returns {BaseNode}
  34950. */
  34951. function walk$1(ast, { enter, leave }) {
  34952. const instance = new SyncWalker(enter, leave);
  34953. return instance.visit(ast, null);
  34954. }
  34955. function isReference(node, parent) {
  34956. if (node.type === 'MemberExpression') {
  34957. return !node.computed && isReference(node.object, node);
  34958. }
  34959. if (node.type === 'Identifier') {
  34960. if (!parent)
  34961. return true;
  34962. switch (parent.type) {
  34963. // disregard `bar` in `foo.bar`
  34964. case 'MemberExpression': return parent.computed || node === parent.object;
  34965. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  34966. case 'MethodDefinition': return parent.computed;
  34967. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  34968. case 'FieldDefinition': return parent.computed || node === parent.value;
  34969. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  34970. case 'Property': return parent.computed || node === parent.value;
  34971. // disregard the `bar` in `export { foo as bar }` or
  34972. // the foo in `import { foo as bar }`
  34973. case 'ExportSpecifier':
  34974. case 'ImportSpecifier': return node === parent.local;
  34975. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  34976. case 'LabeledStatement':
  34977. case 'BreakStatement':
  34978. case 'ContinueStatement': return false;
  34979. default: return true;
  34980. }
  34981. }
  34982. return false;
  34983. }
  34984. var peerDependencies = {
  34985. rollup: "^2.38.3"
  34986. };
  34987. function tryParse(parse, code, id) {
  34988. try {
  34989. return parse(code, { allowReturnOutsideFunction: true });
  34990. } catch (err) {
  34991. err.message += ` in ${id}`;
  34992. throw err;
  34993. }
  34994. }
  34995. const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
  34996. const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
  34997. function hasCjsKeywords(code, ignoreGlobal) {
  34998. const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
  34999. return firstpass.test(code);
  35000. }
  35001. /* eslint-disable no-underscore-dangle */
  35002. function analyzeTopLevelStatements(parse, code, id) {
  35003. const ast = tryParse(parse, code, id);
  35004. let isEsModule = false;
  35005. let hasDefaultExport = false;
  35006. let hasNamedExports = false;
  35007. for (const node of ast.body) {
  35008. switch (node.type) {
  35009. case 'ExportDefaultDeclaration':
  35010. isEsModule = true;
  35011. hasDefaultExport = true;
  35012. break;
  35013. case 'ExportNamedDeclaration':
  35014. isEsModule = true;
  35015. if (node.declaration) {
  35016. hasNamedExports = true;
  35017. } else {
  35018. for (const specifier of node.specifiers) {
  35019. if (specifier.exported.name === 'default') {
  35020. hasDefaultExport = true;
  35021. } else {
  35022. hasNamedExports = true;
  35023. }
  35024. }
  35025. }
  35026. break;
  35027. case 'ExportAllDeclaration':
  35028. isEsModule = true;
  35029. if (node.exported && node.exported.name === 'default') {
  35030. hasDefaultExport = true;
  35031. } else {
  35032. hasNamedExports = true;
  35033. }
  35034. break;
  35035. case 'ImportDeclaration':
  35036. isEsModule = true;
  35037. break;
  35038. }
  35039. }
  35040. return { isEsModule, hasDefaultExport, hasNamedExports, ast };
  35041. }
  35042. const isWrappedId = (id, suffix) => id.endsWith(suffix);
  35043. const wrapId = (id, suffix) => `\0${id}${suffix}`;
  35044. const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
  35045. const PROXY_SUFFIX = '?commonjs-proxy';
  35046. const REQUIRE_SUFFIX = '?commonjs-require';
  35047. const EXTERNAL_SUFFIX = '?commonjs-external';
  35048. const EXPORTS_SUFFIX = '?commonjs-exports';
  35049. const MODULE_SUFFIX = '?commonjs-module';
  35050. const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
  35051. const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
  35052. const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
  35053. const HELPERS_ID = '\0commonjsHelpers.js';
  35054. // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
  35055. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
  35056. // This will no longer be necessary once Rollup switches to ES6 output, likely
  35057. // in Rollup 3
  35058. const HELPERS = `
  35059. export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  35060. export function getDefaultExportFromCjs (x) {
  35061. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  35062. }
  35063. export function getDefaultExportFromNamespaceIfPresent (n) {
  35064. return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  35065. }
  35066. export function getDefaultExportFromNamespaceIfNotNamed (n) {
  35067. return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  35068. }
  35069. export function getAugmentedNamespace(n) {
  35070. if (n.__esModule) return n;
  35071. var a = Object.defineProperty({}, '__esModule', {value: true});
  35072. Object.keys(n).forEach(function (k) {
  35073. var d = Object.getOwnPropertyDescriptor(n, k);
  35074. Object.defineProperty(a, k, d.get ? d : {
  35075. enumerable: true,
  35076. get: function () {
  35077. return n[k];
  35078. }
  35079. });
  35080. });
  35081. return a;
  35082. }
  35083. `;
  35084. const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
  35085. const HELPER_NON_DYNAMIC = `
  35086. export function commonjsRequire (path) {
  35087. ${FAILED_REQUIRE_ERROR}
  35088. }
  35089. `;
  35090. const getDynamicHelpers = (ignoreDynamicRequires) => `
  35091. export function createModule(modulePath) {
  35092. return {
  35093. path: modulePath,
  35094. exports: {},
  35095. require: function (path, base) {
  35096. return commonjsRequire(path, base == null ? modulePath : base);
  35097. }
  35098. };
  35099. }
  35100. export function commonjsRegister (path, loader) {
  35101. DYNAMIC_REQUIRE_LOADERS[path] = loader;
  35102. }
  35103. export function commonjsRegisterOrShort (path, to) {
  35104. const resolvedPath = commonjsResolveImpl(path, null, true);
  35105. if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  35106. DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  35107. } else {
  35108. DYNAMIC_REQUIRE_SHORTS[path] = to;
  35109. }
  35110. }
  35111. const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
  35112. const DYNAMIC_REQUIRE_CACHE = Object.create(null);
  35113. const DYNAMIC_REQUIRE_SHORTS = Object.create(null);
  35114. const DEFAULT_PARENT_MODULE = {
  35115. id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
  35116. };
  35117. const CHECKED_EXTENSIONS = ['', '.js', '.json'];
  35118. function normalize (path) {
  35119. path = path.replace(/\\\\/g, '/');
  35120. const parts = path.split('/');
  35121. const slashed = parts[0] === '';
  35122. for (let i = 1; i < parts.length; i++) {
  35123. if (parts[i] === '.' || parts[i] === '') {
  35124. parts.splice(i--, 1);
  35125. }
  35126. }
  35127. for (let i = 1; i < parts.length; i++) {
  35128. if (parts[i] !== '..') continue;
  35129. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  35130. parts.splice(--i, 2);
  35131. i--;
  35132. }
  35133. }
  35134. path = parts.join('/');
  35135. if (slashed && path[0] !== '/')
  35136. path = '/' + path;
  35137. else if (path.length === 0)
  35138. path = '.';
  35139. return path;
  35140. }
  35141. function join () {
  35142. if (arguments.length === 0)
  35143. return '.';
  35144. let joined;
  35145. for (let i = 0; i < arguments.length; ++i) {
  35146. let arg = arguments[i];
  35147. if (arg.length > 0) {
  35148. if (joined === undefined)
  35149. joined = arg;
  35150. else
  35151. joined += '/' + arg;
  35152. }
  35153. }
  35154. if (joined === undefined)
  35155. return '.';
  35156. return joined;
  35157. }
  35158. function isPossibleNodeModulesPath (modulePath) {
  35159. let c0 = modulePath[0];
  35160. if (c0 === '/' || c0 === '\\\\') return false;
  35161. let c1 = modulePath[1], c2 = modulePath[2];
  35162. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
  35163. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
  35164. if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))
  35165. return false;
  35166. return true;
  35167. }
  35168. function dirname (path) {
  35169. if (path.length === 0)
  35170. return '.';
  35171. let i = path.length - 1;
  35172. while (i > 0) {
  35173. const c = path.charCodeAt(i);
  35174. if ((c === 47 || c === 92) && i !== path.length - 1)
  35175. break;
  35176. i--;
  35177. }
  35178. if (i > 0)
  35179. return path.substr(0, i);
  35180. if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
  35181. return path.charAt(0);
  35182. return '.';
  35183. }
  35184. export function commonjsResolveImpl (path, originalModuleDir, testCache) {
  35185. const shouldTryNodeModules = isPossibleNodeModulesPath(path);
  35186. path = normalize(path);
  35187. let relPath;
  35188. if (path[0] === '/') {
  35189. originalModuleDir = '/';
  35190. }
  35191. while (true) {
  35192. if (!shouldTryNodeModules) {
  35193. relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
  35194. } else if (originalModuleDir) {
  35195. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  35196. } else {
  35197. relPath = normalize(join('node_modules', path));
  35198. }
  35199. if (relPath.endsWith('/..')) {
  35200. break; // Travelled too far up, avoid infinite loop
  35201. }
  35202. for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
  35203. const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
  35204. if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  35205. return resolvedPath;
  35206. }
  35207. if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {
  35208. return resolvedPath;
  35209. }
  35210. if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
  35211. return resolvedPath;
  35212. }
  35213. }
  35214. if (!shouldTryNodeModules) break;
  35215. const nextDir = normalize(originalModuleDir + '/..');
  35216. if (nextDir === originalModuleDir) break;
  35217. originalModuleDir = nextDir;
  35218. }
  35219. return null;
  35220. }
  35221. export function commonjsResolve (path, originalModuleDir) {
  35222. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  35223. if (resolvedPath !== null) {
  35224. return resolvedPath;
  35225. }
  35226. return require.resolve(path);
  35227. }
  35228. export function commonjsRequire (path, originalModuleDir) {
  35229. let resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
  35230. if (resolvedPath !== null) {
  35231. let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  35232. if (cachedModule) return cachedModule.exports;
  35233. let shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];
  35234. if (shortTo) {
  35235. cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];
  35236. if (cachedModule)
  35237. return cachedModule.exports;
  35238. resolvedPath = commonjsResolveImpl(shortTo, null, true);
  35239. }
  35240. const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
  35241. if (loader) {
  35242. DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
  35243. id: resolvedPath,
  35244. filename: resolvedPath,
  35245. path: dirname(resolvedPath),
  35246. exports: {},
  35247. parent: DEFAULT_PARENT_MODULE,
  35248. loaded: false,
  35249. children: [],
  35250. paths: [],
  35251. require: function (path, base) {
  35252. return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
  35253. }
  35254. };
  35255. try {
  35256. loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
  35257. } catch (error) {
  35258. delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
  35259. throw error;
  35260. }
  35261. cachedModule.loaded = true;
  35262. return cachedModule.exports;
  35263. };
  35264. }
  35265. ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
  35266. }
  35267. commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
  35268. commonjsRequire.resolve = commonjsResolve;
  35269. `;
  35270. function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {
  35271. return `${HELPERS}${
  35272. isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC
  35273. }`;
  35274. }
  35275. /* eslint-disable import/prefer-default-export */
  35276. function deconflict(scopes, globals, identifier) {
  35277. let i = 1;
  35278. let deconflicted = makeLegalIdentifier(identifier);
  35279. const hasConflicts = () =>
  35280. scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
  35281. while (hasConflicts()) {
  35282. deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
  35283. i += 1;
  35284. }
  35285. for (const scope of scopes) {
  35286. scope.declarations[deconflicted] = true;
  35287. }
  35288. return deconflicted;
  35289. }
  35290. function getName(id) {
  35291. const name = makeLegalIdentifier(path$w.basename(id, path$w.extname(id)));
  35292. if (name !== 'index') {
  35293. return name;
  35294. }
  35295. return makeLegalIdentifier(path$w.basename(path$w.dirname(id)));
  35296. }
  35297. function normalizePathSlashes(path) {
  35298. return path.replace(/\\/g, '/');
  35299. }
  35300. const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
  35301. const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
  35302. const normalizedPath = normalizePathSlashes(path);
  35303. return normalizedPath.startsWith(commonDir)
  35304. ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
  35305. : normalizedPath;
  35306. };
  35307. function getPackageEntryPoint(dirPath) {
  35308. let entryPoint = 'index.js';
  35309. try {
  35310. if (fs$v.existsSync(path$w.join(dirPath, 'package.json'))) {
  35311. entryPoint =
  35312. JSON.parse(fs$v.readFileSync(path$w.join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
  35313. entryPoint;
  35314. }
  35315. } catch (ignored) {
  35316. // ignored
  35317. }
  35318. return entryPoint;
  35319. }
  35320. function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
  35321. let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`;
  35322. for (const dir of dynamicRequireModuleDirPaths) {
  35323. const entryPoint = getPackageEntryPoint(dir);
  35324. code += `\ncommonjsRegisterOrShort(${JSON.stringify(
  35325. getVirtualPathForDynamicRequirePath(dir, commonDir)
  35326. )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(path$w.join(dir, entryPoint), commonDir))});`;
  35327. }
  35328. return code;
  35329. }
  35330. function getDynamicPackagesEntryIntro(
  35331. dynamicRequireModuleDirPaths,
  35332. dynamicRequireModuleSet
  35333. ) {
  35334. let dynamicImports = Array.from(
  35335. dynamicRequireModuleSet,
  35336. (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
  35337. ).join('\n');
  35338. if (dynamicRequireModuleDirPaths.length) {
  35339. dynamicImports += `require(${JSON.stringify(
  35340. wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
  35341. )});`;
  35342. }
  35343. return dynamicImports;
  35344. }
  35345. function isDynamicModuleImport(id, dynamicRequireModuleSet) {
  35346. const normalizedPath = normalizePathSlashes(id);
  35347. return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
  35348. }
  35349. function isDirectory(path) {
  35350. try {
  35351. if (fs$v.statSync(path).isDirectory()) return true;
  35352. } catch (ignored) {
  35353. // Nothing to do here
  35354. }
  35355. return false;
  35356. }
  35357. function getDynamicRequirePaths(patterns) {
  35358. const dynamicRequireModuleSet = new Set();
  35359. for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
  35360. const isNegated = pattern.startsWith('!');
  35361. const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
  35362. for (const path of glob_1.sync(isNegated ? pattern.substr(1) : pattern)) {
  35363. modifySet(normalizePathSlashes(path$w.resolve(path)));
  35364. if (isDirectory(path)) {
  35365. modifySet(normalizePathSlashes(path$w.resolve(path$w.join(path, getPackageEntryPoint(path)))));
  35366. }
  35367. }
  35368. }
  35369. const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
  35370. isDirectory(path)
  35371. );
  35372. return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
  35373. }
  35374. function getCommonJSMetaPromise(commonJSMetaPromises, id) {
  35375. let commonJSMetaPromise = commonJSMetaPromises.get(id);
  35376. if (commonJSMetaPromise) return commonJSMetaPromise.promise;
  35377. const promise = new Promise((resolve) => {
  35378. commonJSMetaPromise = {
  35379. resolve,
  35380. promise: null
  35381. };
  35382. commonJSMetaPromises.set(id, commonJSMetaPromise);
  35383. });
  35384. commonJSMetaPromise.promise = promise;
  35385. return promise;
  35386. }
  35387. function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {
  35388. const commonJSMetaPromise = commonJSMetaPromises.get(id);
  35389. if (commonJSMetaPromise) {
  35390. if (commonJSMetaPromise.resolve) {
  35391. commonJSMetaPromise.resolve(commonjsMeta);
  35392. commonJSMetaPromise.resolve = null;
  35393. }
  35394. } else {
  35395. commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
  35396. }
  35397. }
  35398. // e.g. id === "commonjsHelpers?commonjsRegister"
  35399. function getSpecificHelperProxy(id) {
  35400. return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
  35401. }
  35402. function getUnknownRequireProxy(id, requireReturnsDefault) {
  35403. if (requireReturnsDefault === true || id.endsWith('.json')) {
  35404. return `export {default} from ${JSON.stringify(id)};`;
  35405. }
  35406. const name = getName(id);
  35407. const exported =
  35408. requireReturnsDefault === 'auto'
  35409. ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
  35410. : requireReturnsDefault === 'preferred'
  35411. ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
  35412. : !requireReturnsDefault
  35413. ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
  35414. : `export default ${name};`;
  35415. return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
  35416. }
  35417. function getDynamicJsonProxy(id, commonDir) {
  35418. const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
  35419. return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
  35420. getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
  35421. )}, function (module, exports) {
  35422. module.exports = require(${JSON.stringify(normalizedPath)});
  35423. });`;
  35424. }
  35425. function getDynamicRequireProxy(normalizedPath, commonDir) {
  35426. return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
  35427. getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
  35428. )}, function (module, exports) {
  35429. ${fs$v.readFileSync(normalizedPath, { encoding: 'utf8' })}
  35430. });`;
  35431. }
  35432. async function getStaticRequireProxy(
  35433. id,
  35434. requireReturnsDefault,
  35435. esModulesWithDefaultExport,
  35436. esModulesWithNamedExports,
  35437. commonJsMetaPromises
  35438. ) {
  35439. const name = getName(id);
  35440. const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);
  35441. if (commonjsMeta && commonjsMeta.isCommonJS) {
  35442. return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
  35443. } else if (commonjsMeta === null) {
  35444. return getUnknownRequireProxy(id, requireReturnsDefault);
  35445. } else if (!requireReturnsDefault) {
  35446. return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
  35447. id
  35448. )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
  35449. } else if (
  35450. requireReturnsDefault !== true &&
  35451. (requireReturnsDefault === 'namespace' ||
  35452. !esModulesWithDefaultExport.has(id) ||
  35453. (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
  35454. ) {
  35455. return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
  35456. }
  35457. return `export { default } from ${JSON.stringify(id)};`;
  35458. }
  35459. /* eslint-disable no-param-reassign, no-undefined */
  35460. function getCandidatesForExtension(resolved, extension) {
  35461. return [resolved + extension, `${resolved}${path$w.sep}index${extension}`];
  35462. }
  35463. function getCandidates(resolved, extensions) {
  35464. return extensions.reduce(
  35465. (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
  35466. [resolved]
  35467. );
  35468. }
  35469. function getResolveId(extensions) {
  35470. function resolveExtensions(importee, importer) {
  35471. // not our problem
  35472. if (importee[0] !== '.' || !importer) return undefined;
  35473. const resolved = path$w.resolve(path$w.dirname(importer), importee);
  35474. const candidates = getCandidates(resolved, extensions);
  35475. for (let i = 0; i < candidates.length; i += 1) {
  35476. try {
  35477. const stats = fs$v.statSync(candidates[i]);
  35478. if (stats.isFile()) return { id: candidates[i] };
  35479. } catch (err) {
  35480. /* noop */
  35481. }
  35482. }
  35483. return undefined;
  35484. }
  35485. return function resolveId(importee, rawImporter) {
  35486. if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
  35487. return importee;
  35488. }
  35489. const importer =
  35490. rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
  35491. ? unwrapId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
  35492. : rawImporter;
  35493. // Except for exports, proxies are only importing resolved ids,
  35494. // no need to resolve again
  35495. if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
  35496. return importee;
  35497. }
  35498. const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
  35499. const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
  35500. let isModuleRegistration = false;
  35501. if (isProxyModule) {
  35502. importee = unwrapId(importee, PROXY_SUFFIX);
  35503. } else if (isRequiredModule) {
  35504. importee = unwrapId(importee, REQUIRE_SUFFIX);
  35505. isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
  35506. if (isModuleRegistration) {
  35507. importee = unwrapId(importee, DYNAMIC_REGISTER_SUFFIX);
  35508. }
  35509. }
  35510. if (
  35511. importee.startsWith(HELPERS_ID) ||
  35512. importee === DYNAMIC_PACKAGES_ID ||
  35513. importee.startsWith(DYNAMIC_JSON_PREFIX)
  35514. ) {
  35515. return importee;
  35516. }
  35517. if (importee.startsWith('\0')) {
  35518. return null;
  35519. }
  35520. return this.resolve(importee, importer, {
  35521. skipSelf: true,
  35522. custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } }
  35523. }).then((resolved) => {
  35524. if (!resolved) {
  35525. resolved = resolveExtensions(importee, importer);
  35526. }
  35527. if (resolved && isProxyModule) {
  35528. resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
  35529. resolved.external = false;
  35530. } else if (resolved && isModuleRegistration) {
  35531. resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
  35532. } else if (!resolved && (isProxyModule || isRequiredModule)) {
  35533. return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
  35534. }
  35535. return resolved;
  35536. });
  35537. };
  35538. }
  35539. function validateRollupVersion(rollupVersion, peerDependencyVersion) {
  35540. const [major, minor] = rollupVersion.split('.').map(Number);
  35541. const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
  35542. let minMajor = Infinity;
  35543. let minMinor = Infinity;
  35544. let foundVersion;
  35545. // eslint-disable-next-line no-cond-assign
  35546. while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
  35547. const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
  35548. if (foundMajor < minMajor) {
  35549. minMajor = foundMajor;
  35550. minMinor = foundMinor;
  35551. }
  35552. }
  35553. if (major < minMajor || (major === minMajor && minor < minMinor)) {
  35554. throw new Error(
  35555. `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
  35556. );
  35557. }
  35558. }
  35559. const operators = {
  35560. '==': (x) => equals(x.left, x.right, false),
  35561. '!=': (x) => not(operators['=='](x)),
  35562. '===': (x) => equals(x.left, x.right, true),
  35563. '!==': (x) => not(operators['==='](x)),
  35564. '!': (x) => isFalsy(x.argument),
  35565. '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
  35566. '||': (x) => isTruthy(x.left) || isTruthy(x.right)
  35567. };
  35568. function not(value) {
  35569. return value === null ? value : !value;
  35570. }
  35571. function equals(a, b, strict) {
  35572. if (a.type !== b.type) return null;
  35573. // eslint-disable-next-line eqeqeq
  35574. if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
  35575. return null;
  35576. }
  35577. function isTruthy(node) {
  35578. if (!node) return false;
  35579. if (node.type === 'Literal') return !!node.value;
  35580. if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
  35581. if (node.operator in operators) return operators[node.operator](node);
  35582. return null;
  35583. }
  35584. function isFalsy(node) {
  35585. return not(isTruthy(node));
  35586. }
  35587. function getKeypath(node) {
  35588. const parts = [];
  35589. while (node.type === 'MemberExpression') {
  35590. if (node.computed) return null;
  35591. parts.unshift(node.property.name);
  35592. // eslint-disable-next-line no-param-reassign
  35593. node = node.object;
  35594. }
  35595. if (node.type !== 'Identifier') return null;
  35596. const { name } = node;
  35597. parts.unshift(name);
  35598. return { name, keypath: parts.join('.') };
  35599. }
  35600. const KEY_COMPILED_ESM = '__esModule';
  35601. function isDefineCompiledEsm(node) {
  35602. const definedProperty =
  35603. getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');
  35604. if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
  35605. return isTruthy(definedProperty.value);
  35606. }
  35607. return false;
  35608. }
  35609. function getDefinePropertyCallName(node, targetName) {
  35610. const {
  35611. callee: { object, property }
  35612. } = node;
  35613. if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
  35614. if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
  35615. if (node.arguments.length !== 3) return;
  35616. const targetNames = targetName.split('.');
  35617. const [target, key, value] = node.arguments;
  35618. if (targetNames.length === 1) {
  35619. if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
  35620. return;
  35621. }
  35622. }
  35623. if (targetNames.length === 2) {
  35624. if (
  35625. target.type !== 'MemberExpression' ||
  35626. target.object.name !== targetNames[0] ||
  35627. target.property.name !== targetNames[1]
  35628. ) {
  35629. return;
  35630. }
  35631. }
  35632. if (value.type !== 'ObjectExpression' || !value.properties) return;
  35633. const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
  35634. if (!valueProperty || !valueProperty.value) return;
  35635. // eslint-disable-next-line consistent-return
  35636. return { key: key.value, value: valueProperty.value };
  35637. }
  35638. function isShorthandProperty(parent) {
  35639. return parent && parent.type === 'Property' && parent.shorthand;
  35640. }
  35641. function hasDefineEsmProperty(node) {
  35642. return node.properties.some((property) => {
  35643. if (
  35644. property.type === 'Property' &&
  35645. property.key.type === 'Identifier' &&
  35646. property.key.name === '__esModule' &&
  35647. isTruthy(property.value)
  35648. ) {
  35649. return true;
  35650. }
  35651. return false;
  35652. });
  35653. }
  35654. function wrapCode(magicString, uses, moduleName, exportsName) {
  35655. const args = [];
  35656. const passedArgs = [];
  35657. if (uses.module) {
  35658. args.push('module');
  35659. passedArgs.push(moduleName);
  35660. }
  35661. if (uses.exports) {
  35662. args.push('exports');
  35663. passedArgs.push(exportsName);
  35664. }
  35665. magicString
  35666. .trim()
  35667. .prepend(`(function (${args.join(', ')}) {\n`)
  35668. .append(`\n}(${passedArgs.join(', ')}));`);
  35669. }
  35670. function rewriteExportsAndGetExportsBlock(
  35671. magicString,
  35672. moduleName,
  35673. exportsName,
  35674. wrapped,
  35675. moduleExportsAssignments,
  35676. firstTopLevelModuleExportsAssignment,
  35677. exportsAssignmentsByName,
  35678. topLevelAssignments,
  35679. defineCompiledEsmExpressions,
  35680. deconflictedExportNames,
  35681. code,
  35682. HELPERS_NAME,
  35683. exportMode,
  35684. detectWrappedDefault,
  35685. defaultIsModuleExports
  35686. ) {
  35687. const exports = [];
  35688. const exportDeclarations = [];
  35689. if (exportMode === 'replace') {
  35690. getExportsForReplacedModuleExports(
  35691. magicString,
  35692. exports,
  35693. exportDeclarations,
  35694. moduleExportsAssignments,
  35695. firstTopLevelModuleExportsAssignment,
  35696. exportsName
  35697. );
  35698. } else {
  35699. exports.push(`${exportsName} as __moduleExports`);
  35700. if (wrapped) {
  35701. getExportsWhenWrapping(
  35702. exportDeclarations,
  35703. exportsName,
  35704. detectWrappedDefault,
  35705. HELPERS_NAME,
  35706. defaultIsModuleExports
  35707. );
  35708. } else {
  35709. getExports(
  35710. magicString,
  35711. exports,
  35712. exportDeclarations,
  35713. moduleExportsAssignments,
  35714. exportsAssignmentsByName,
  35715. deconflictedExportNames,
  35716. topLevelAssignments,
  35717. moduleName,
  35718. exportsName,
  35719. defineCompiledEsmExpressions,
  35720. HELPERS_NAME,
  35721. defaultIsModuleExports
  35722. );
  35723. }
  35724. }
  35725. if (exports.length) {
  35726. exportDeclarations.push(`export { ${exports.join(', ')} };`);
  35727. }
  35728. return `\n\n${exportDeclarations.join('\n')}`;
  35729. }
  35730. function getExportsForReplacedModuleExports(
  35731. magicString,
  35732. exports,
  35733. exportDeclarations,
  35734. moduleExportsAssignments,
  35735. firstTopLevelModuleExportsAssignment,
  35736. exportsName
  35737. ) {
  35738. for (const { left } of moduleExportsAssignments) {
  35739. magicString.overwrite(left.start, left.end, exportsName);
  35740. }
  35741. magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
  35742. exports.push(`${exportsName} as __moduleExports`);
  35743. exportDeclarations.push(`export default ${exportsName};`);
  35744. }
  35745. function getExportsWhenWrapping(
  35746. exportDeclarations,
  35747. exportsName,
  35748. detectWrappedDefault,
  35749. HELPERS_NAME,
  35750. defaultIsModuleExports
  35751. ) {
  35752. exportDeclarations.push(
  35753. `export default ${
  35754. detectWrappedDefault && defaultIsModuleExports === 'auto'
  35755. ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})`
  35756. : defaultIsModuleExports === false
  35757. ? `${exportsName}.default`
  35758. : exportsName
  35759. };`
  35760. );
  35761. }
  35762. function getExports(
  35763. magicString,
  35764. exports,
  35765. exportDeclarations,
  35766. moduleExportsAssignments,
  35767. exportsAssignmentsByName,
  35768. deconflictedExportNames,
  35769. topLevelAssignments,
  35770. moduleName,
  35771. exportsName,
  35772. defineCompiledEsmExpressions,
  35773. HELPERS_NAME,
  35774. defaultIsModuleExports
  35775. ) {
  35776. let deconflictedDefaultExportName;
  35777. // Collect and rewrite module.exports assignments
  35778. for (const { left } of moduleExportsAssignments) {
  35779. magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
  35780. }
  35781. // Collect and rewrite named exports
  35782. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  35783. const deconflicted = deconflictedExportNames[exportName];
  35784. let needsDeclaration = true;
  35785. for (const node of nodes) {
  35786. let replacement = `${deconflicted} = ${exportsName}.${exportName}`;
  35787. if (needsDeclaration && topLevelAssignments.has(node)) {
  35788. replacement = `var ${replacement}`;
  35789. needsDeclaration = false;
  35790. }
  35791. magicString.overwrite(node.start, node.left.end, replacement);
  35792. }
  35793. if (needsDeclaration) {
  35794. magicString.prepend(`var ${deconflicted};\n`);
  35795. }
  35796. if (exportName === 'default') {
  35797. deconflictedDefaultExportName = deconflicted;
  35798. } else {
  35799. exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
  35800. }
  35801. }
  35802. // Collect and rewrite exports.__esModule assignments
  35803. let isRestorableCompiledEsm = false;
  35804. for (const expression of defineCompiledEsmExpressions) {
  35805. isRestorableCompiledEsm = true;
  35806. const moduleExportsExpression =
  35807. expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
  35808. magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
  35809. }
  35810. if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
  35811. exportDeclarations.push(`export default ${exportsName};`);
  35812. } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
  35813. exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
  35814. } else {
  35815. exportDeclarations.push(
  35816. `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
  35817. );
  35818. }
  35819. }
  35820. function isRequireStatement(node, scope) {
  35821. if (!node) return false;
  35822. if (node.type !== 'CallExpression') return false;
  35823. // Weird case of `require()` or `module.require()` without arguments
  35824. if (node.arguments.length === 0) return false;
  35825. return isRequire(node.callee, scope);
  35826. }
  35827. function isRequire(node, scope) {
  35828. return (
  35829. (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
  35830. (node.type === 'MemberExpression' && isModuleRequire(node, scope))
  35831. );
  35832. }
  35833. function isModuleRequire({ object, property }, scope) {
  35834. return (
  35835. object.type === 'Identifier' &&
  35836. object.name === 'module' &&
  35837. property.type === 'Identifier' &&
  35838. property.name === 'require' &&
  35839. !scope.contains('module')
  35840. );
  35841. }
  35842. function isStaticRequireStatement(node, scope) {
  35843. if (!isRequireStatement(node, scope)) return false;
  35844. return !hasDynamicArguments(node);
  35845. }
  35846. function hasDynamicArguments(node) {
  35847. return (
  35848. node.arguments.length > 1 ||
  35849. (node.arguments[0].type !== 'Literal' &&
  35850. (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
  35851. );
  35852. }
  35853. const reservedMethod = { resolve: true, cache: true, main: true };
  35854. function isNodeRequirePropertyAccess(parent) {
  35855. return parent && parent.property && reservedMethod[parent.property.name];
  35856. }
  35857. function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
  35858. return ignoreRequire(requiredNode.arguments[0].value);
  35859. }
  35860. function getRequireStringArg(node) {
  35861. return node.arguments[0].type === 'Literal'
  35862. ? node.arguments[0].value
  35863. : node.arguments[0].quasis[0].value.cooked;
  35864. }
  35865. function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
  35866. if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
  35867. try {
  35868. const resolvedPath = normalizePathSlashes(resolve$4.sync(source, { basedir: path$w.dirname(id) }));
  35869. if (dynamicRequireModuleSet.has(resolvedPath)) {
  35870. return true;
  35871. }
  35872. } catch (ex) {
  35873. // Probably a node.js internal module
  35874. return false;
  35875. }
  35876. return false;
  35877. }
  35878. for (const attemptExt of ['', '.js', '.json']) {
  35879. const resolvedPath = normalizePathSlashes(path$w.resolve(path$w.dirname(id), source + attemptExt));
  35880. if (dynamicRequireModuleSet.has(resolvedPath)) {
  35881. return true;
  35882. }
  35883. }
  35884. return false;
  35885. }
  35886. function getRequireHandlers() {
  35887. const requiredSources = [];
  35888. const requiredBySource = Object.create(null);
  35889. const requiredByNode = new Map();
  35890. const requireExpressionsWithUsedReturnValue = [];
  35891. function addRequireStatement(sourceId, node, scope, usesReturnValue) {
  35892. const required = getRequired(sourceId);
  35893. requiredByNode.set(node, { scope, required });
  35894. if (usesReturnValue) {
  35895. required.nodesUsingRequired.push(node);
  35896. requireExpressionsWithUsedReturnValue.push(node);
  35897. }
  35898. }
  35899. function getRequired(sourceId) {
  35900. if (!requiredBySource[sourceId]) {
  35901. requiredSources.push(sourceId);
  35902. requiredBySource[sourceId] = {
  35903. source: sourceId,
  35904. name: null,
  35905. nodesUsingRequired: []
  35906. };
  35907. }
  35908. return requiredBySource[sourceId];
  35909. }
  35910. function rewriteRequireExpressionsAndGetImportBlock(
  35911. magicString,
  35912. topLevelDeclarations,
  35913. topLevelRequireDeclarators,
  35914. reassignedNames,
  35915. helpersName,
  35916. dynamicRegisterSources,
  35917. moduleName,
  35918. exportsName,
  35919. id,
  35920. exportMode
  35921. ) {
  35922. setRemainingImportNamesAndRewriteRequires(
  35923. requireExpressionsWithUsedReturnValue,
  35924. requiredByNode,
  35925. magicString
  35926. );
  35927. const imports = [];
  35928. imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
  35929. if (exportMode === 'module') {
  35930. imports.push(
  35931. `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
  35932. wrapId(id, MODULE_SUFFIX)
  35933. )}`
  35934. );
  35935. } else if (exportMode === 'exports') {
  35936. imports.push(
  35937. `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
  35938. );
  35939. }
  35940. for (const source of dynamicRegisterSources) {
  35941. imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
  35942. }
  35943. for (const source of requiredSources) {
  35944. if (!source.startsWith('\0')) {
  35945. imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
  35946. }
  35947. const { name, nodesUsingRequired } = requiredBySource[source];
  35948. imports.push(
  35949. `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
  35950. source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
  35951. )};`
  35952. );
  35953. }
  35954. return imports.length ? `${imports.join('\n')}\n\n` : '';
  35955. }
  35956. return {
  35957. addRequireStatement,
  35958. requiredSources,
  35959. rewriteRequireExpressionsAndGetImportBlock
  35960. };
  35961. }
  35962. function setRemainingImportNamesAndRewriteRequires(
  35963. requireExpressionsWithUsedReturnValue,
  35964. requiredByNode,
  35965. magicString
  35966. ) {
  35967. let uid = 0;
  35968. for (const requireExpression of requireExpressionsWithUsedReturnValue) {
  35969. const { required } = requiredByNode.get(requireExpression);
  35970. if (!required.name) {
  35971. let potentialName;
  35972. const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
  35973. do {
  35974. potentialName = `require$$${uid}`;
  35975. uid += 1;
  35976. } while (required.nodesUsingRequired.some(isUsedName));
  35977. required.name = potentialName;
  35978. }
  35979. magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
  35980. }
  35981. }
  35982. /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
  35983. const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
  35984. const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
  35985. function transformCommonjs(
  35986. parse,
  35987. code,
  35988. id,
  35989. isEsModule,
  35990. ignoreGlobal,
  35991. ignoreRequire,
  35992. ignoreDynamicRequires,
  35993. getIgnoreTryCatchRequireStatementMode,
  35994. sourceMap,
  35995. isDynamicRequireModulesEnabled,
  35996. dynamicRequireModuleSet,
  35997. disableWrap,
  35998. commonDir,
  35999. astCache,
  36000. defaultIsModuleExports
  36001. ) {
  36002. const ast = astCache || tryParse(parse, code, id);
  36003. const magicString = new MagicString(code);
  36004. const uses = {
  36005. module: false,
  36006. exports: false,
  36007. global: false,
  36008. require: false
  36009. };
  36010. let usesDynamicRequire = false;
  36011. const virtualDynamicRequirePath =
  36012. isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path$w.dirname(id), commonDir);
  36013. let scope = attachScopes(ast, 'scope');
  36014. let lexicalDepth = 0;
  36015. let programDepth = 0;
  36016. let currentTryBlockEnd = null;
  36017. let shouldWrap = false;
  36018. const globals = new Set();
  36019. // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
  36020. const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
  36021. const dynamicRegisterSources = new Set();
  36022. let hasRemovedRequire = false;
  36023. const {
  36024. addRequireStatement,
  36025. requiredSources,
  36026. rewriteRequireExpressionsAndGetImportBlock
  36027. } = getRequireHandlers();
  36028. // See which names are assigned to. This is necessary to prevent
  36029. // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
  36030. // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
  36031. const reassignedNames = new Set();
  36032. const topLevelDeclarations = [];
  36033. const topLevelRequireDeclarators = new Set();
  36034. const skippedNodes = new Set();
  36035. const moduleAccessScopes = new Set([scope]);
  36036. const exportsAccessScopes = new Set([scope]);
  36037. const moduleExportsAssignments = [];
  36038. let firstTopLevelModuleExportsAssignment = null;
  36039. const exportsAssignmentsByName = new Map();
  36040. const topLevelAssignments = new Set();
  36041. const topLevelDefineCompiledEsmExpressions = [];
  36042. walk$1(ast, {
  36043. enter(node, parent) {
  36044. if (skippedNodes.has(node)) {
  36045. this.skip();
  36046. return;
  36047. }
  36048. if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
  36049. currentTryBlockEnd = null;
  36050. }
  36051. programDepth += 1;
  36052. if (node.scope) ({ scope } = node);
  36053. if (functionType.test(node.type)) lexicalDepth += 1;
  36054. if (sourceMap) {
  36055. magicString.addSourcemapLocation(node.start);
  36056. magicString.addSourcemapLocation(node.end);
  36057. }
  36058. // eslint-disable-next-line default-case
  36059. switch (node.type) {
  36060. case 'TryStatement':
  36061. if (currentTryBlockEnd === null) {
  36062. currentTryBlockEnd = node.block.end;
  36063. }
  36064. return;
  36065. case 'AssignmentExpression':
  36066. if (node.left.type === 'MemberExpression') {
  36067. const flattened = getKeypath(node.left);
  36068. if (!flattened || scope.contains(flattened.name)) return;
  36069. const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
  36070. if (!exportsPatternMatch || flattened.keypath === 'exports') return;
  36071. const [, exportName] = exportsPatternMatch;
  36072. uses[flattened.name] = true;
  36073. // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
  36074. if (flattened.keypath === 'module.exports') {
  36075. moduleExportsAssignments.push(node);
  36076. if (programDepth > 3) {
  36077. moduleAccessScopes.add(scope);
  36078. } else if (!firstTopLevelModuleExportsAssignment) {
  36079. firstTopLevelModuleExportsAssignment = node;
  36080. }
  36081. if (defaultIsModuleExports === false) {
  36082. shouldWrap = true;
  36083. } else if (defaultIsModuleExports === 'auto') {
  36084. if (node.right.type === 'ObjectExpression') {
  36085. if (hasDefineEsmProperty(node.right)) {
  36086. shouldWrap = true;
  36087. }
  36088. } else if (defaultIsModuleExports === false) {
  36089. shouldWrap = true;
  36090. }
  36091. }
  36092. } else if (exportName === KEY_COMPILED_ESM) {
  36093. if (programDepth > 3) {
  36094. shouldWrap = true;
  36095. } else {
  36096. topLevelDefineCompiledEsmExpressions.push(node);
  36097. }
  36098. } else {
  36099. const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
  36100. nodes: [],
  36101. scopes: new Set()
  36102. };
  36103. exportsAssignments.nodes.push(node);
  36104. exportsAssignments.scopes.add(scope);
  36105. exportsAccessScopes.add(scope);
  36106. exportsAssignmentsByName.set(exportName, exportsAssignments);
  36107. if (programDepth <= 3) {
  36108. topLevelAssignments.add(node);
  36109. }
  36110. }
  36111. skippedNodes.add(node.left);
  36112. } else {
  36113. for (const name of extractAssignedNames(node.left)) {
  36114. reassignedNames.add(name);
  36115. }
  36116. }
  36117. return;
  36118. case 'CallExpression': {
  36119. if (isDefineCompiledEsm(node)) {
  36120. if (programDepth === 3 && parent.type === 'ExpressionStatement') {
  36121. // skip special handling for [module.]exports until we know we render this
  36122. skippedNodes.add(node.arguments[0]);
  36123. topLevelDefineCompiledEsmExpressions.push(node);
  36124. } else {
  36125. shouldWrap = true;
  36126. }
  36127. return;
  36128. }
  36129. if (
  36130. node.callee.object &&
  36131. node.callee.object.name === 'require' &&
  36132. node.callee.property.name === 'resolve' &&
  36133. hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
  36134. ) {
  36135. const requireNode = node.callee.object;
  36136. magicString.appendLeft(
  36137. node.end - 1,
  36138. `,${JSON.stringify(
  36139. path$w.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
  36140. )}`
  36141. );
  36142. magicString.overwrite(
  36143. requireNode.start,
  36144. requireNode.end,
  36145. `${HELPERS_NAME}.commonjsRequire`,
  36146. {
  36147. storeName: true
  36148. }
  36149. );
  36150. return;
  36151. }
  36152. if (!isStaticRequireStatement(node, scope)) return;
  36153. if (!isDynamicRequireModulesEnabled) {
  36154. skippedNodes.add(node.callee);
  36155. }
  36156. if (!isIgnoredRequireStatement(node, ignoreRequire)) {
  36157. skippedNodes.add(node.callee);
  36158. const usesReturnValue = parent.type !== 'ExpressionStatement';
  36159. let canConvertRequire = true;
  36160. let shouldRemoveRequireStatement = false;
  36161. if (currentTryBlockEnd !== null) {
  36162. ({
  36163. canConvertRequire,
  36164. shouldRemoveRequireStatement
  36165. } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
  36166. if (shouldRemoveRequireStatement) {
  36167. hasRemovedRequire = true;
  36168. }
  36169. }
  36170. let sourceId = getRequireStringArg(node);
  36171. const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
  36172. if (isDynamicRegister) {
  36173. sourceId = unwrapId(sourceId, DYNAMIC_REGISTER_SUFFIX);
  36174. if (sourceId.endsWith('.json')) {
  36175. sourceId = DYNAMIC_JSON_PREFIX + sourceId;
  36176. }
  36177. dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
  36178. } else {
  36179. if (
  36180. !sourceId.endsWith('.json') &&
  36181. hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
  36182. ) {
  36183. if (shouldRemoveRequireStatement) {
  36184. magicString.overwrite(node.start, node.end, `undefined`);
  36185. } else if (canConvertRequire) {
  36186. magicString.overwrite(
  36187. node.start,
  36188. node.end,
  36189. `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
  36190. getVirtualPathForDynamicRequirePath(sourceId, commonDir)
  36191. )}, ${JSON.stringify(
  36192. path$w.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
  36193. )})`
  36194. );
  36195. usesDynamicRequire = true;
  36196. }
  36197. return;
  36198. }
  36199. if (canConvertRequire) {
  36200. addRequireStatement(sourceId, node, scope, usesReturnValue);
  36201. }
  36202. }
  36203. if (usesReturnValue) {
  36204. if (shouldRemoveRequireStatement) {
  36205. magicString.overwrite(node.start, node.end, `undefined`);
  36206. return;
  36207. }
  36208. if (
  36209. parent.type === 'VariableDeclarator' &&
  36210. !scope.parent &&
  36211. parent.id.type === 'Identifier'
  36212. ) {
  36213. // This will allow us to reuse this variable name as the imported variable if it is not reassigned
  36214. // and does not conflict with variables in other places where this is imported
  36215. topLevelRequireDeclarators.add(parent);
  36216. }
  36217. } else {
  36218. // This is a bare import, e.g. `require('foo');`
  36219. if (!canConvertRequire && !shouldRemoveRequireStatement) {
  36220. return;
  36221. }
  36222. magicString.remove(parent.start, parent.end);
  36223. }
  36224. }
  36225. return;
  36226. }
  36227. case 'ConditionalExpression':
  36228. case 'IfStatement':
  36229. // skip dead branches
  36230. if (isFalsy(node.test)) {
  36231. skippedNodes.add(node.consequent);
  36232. } else if (node.alternate && isTruthy(node.test)) {
  36233. skippedNodes.add(node.alternate);
  36234. }
  36235. return;
  36236. case 'Identifier': {
  36237. const { name } = node;
  36238. if (!(isReference(node, parent) && !scope.contains(name))) return;
  36239. switch (name) {
  36240. case 'require':
  36241. if (isNodeRequirePropertyAccess(parent)) {
  36242. if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
  36243. if (parent.property.name === 'cache') {
  36244. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
  36245. storeName: true
  36246. });
  36247. }
  36248. }
  36249. return;
  36250. }
  36251. if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
  36252. magicString.appendLeft(
  36253. parent.end - 1,
  36254. `,${JSON.stringify(
  36255. path$w.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
  36256. )}`
  36257. );
  36258. }
  36259. if (!ignoreDynamicRequires) {
  36260. if (isShorthandProperty(parent)) {
  36261. magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
  36262. } else {
  36263. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
  36264. storeName: true
  36265. });
  36266. }
  36267. }
  36268. usesDynamicRequire = true;
  36269. return;
  36270. case 'module':
  36271. case 'exports':
  36272. shouldWrap = true;
  36273. uses[name] = true;
  36274. return;
  36275. case 'global':
  36276. uses.global = true;
  36277. if (!ignoreGlobal) {
  36278. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
  36279. storeName: true
  36280. });
  36281. }
  36282. return;
  36283. case 'define':
  36284. magicString.overwrite(node.start, node.end, 'undefined', {
  36285. storeName: true
  36286. });
  36287. return;
  36288. default:
  36289. globals.add(name);
  36290. return;
  36291. }
  36292. }
  36293. case 'MemberExpression':
  36294. if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
  36295. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
  36296. storeName: true
  36297. });
  36298. skippedNodes.add(node.object);
  36299. skippedNodes.add(node.property);
  36300. }
  36301. return;
  36302. case 'ReturnStatement':
  36303. // if top-level return, we need to wrap it
  36304. if (lexicalDepth === 0) {
  36305. shouldWrap = true;
  36306. }
  36307. return;
  36308. case 'ThisExpression':
  36309. // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
  36310. if (lexicalDepth === 0) {
  36311. uses.global = true;
  36312. if (!ignoreGlobal) {
  36313. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
  36314. storeName: true
  36315. });
  36316. }
  36317. }
  36318. return;
  36319. case 'UnaryExpression':
  36320. // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
  36321. if (node.operator === 'typeof') {
  36322. const flattened = getKeypath(node.argument);
  36323. if (!flattened) return;
  36324. if (scope.contains(flattened.name)) return;
  36325. if (
  36326. flattened.keypath === 'module.exports' ||
  36327. flattened.keypath === 'module' ||
  36328. flattened.keypath === 'exports'
  36329. ) {
  36330. magicString.overwrite(node.start, node.end, `'object'`, {
  36331. storeName: false
  36332. });
  36333. }
  36334. }
  36335. return;
  36336. case 'VariableDeclaration':
  36337. if (!scope.parent) {
  36338. topLevelDeclarations.push(node);
  36339. }
  36340. }
  36341. },
  36342. leave(node) {
  36343. programDepth -= 1;
  36344. if (node.scope) scope = scope.parent;
  36345. if (functionType.test(node.type)) lexicalDepth -= 1;
  36346. }
  36347. });
  36348. const nameBase = getName(id);
  36349. const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
  36350. const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
  36351. const deconflictedExportNames = Object.create(null);
  36352. for (const [exportName, { scopes }] of exportsAssignmentsByName) {
  36353. deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
  36354. }
  36355. // We cannot wrap ES/mixed modules
  36356. shouldWrap =
  36357. !isEsModule &&
  36358. !disableWrap &&
  36359. (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
  36360. const detectWrappedDefault =
  36361. shouldWrap &&
  36362. (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
  36363. if (
  36364. !(
  36365. requiredSources.length ||
  36366. dynamicRegisterSources.size ||
  36367. uses.module ||
  36368. uses.exports ||
  36369. uses.require ||
  36370. usesDynamicRequire ||
  36371. hasRemovedRequire ||
  36372. topLevelDefineCompiledEsmExpressions.length > 0
  36373. ) &&
  36374. (ignoreGlobal || !uses.global)
  36375. ) {
  36376. return { meta: { commonjs: { isCommonJS: false } } };
  36377. }
  36378. let leadingComment = '';
  36379. if (code.startsWith('/*')) {
  36380. const commentEnd = code.indexOf('*/', 2) + 2;
  36381. leadingComment = `${code.slice(0, commentEnd)}\n`;
  36382. magicString.remove(0, commentEnd).trim();
  36383. }
  36384. const exportMode = shouldWrap
  36385. ? uses.module
  36386. ? 'module'
  36387. : 'exports'
  36388. : firstTopLevelModuleExportsAssignment
  36389. ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
  36390. ? 'replace'
  36391. : 'module'
  36392. : moduleExportsAssignments.length === 0
  36393. ? 'exports'
  36394. : 'module';
  36395. const importBlock = rewriteRequireExpressionsAndGetImportBlock(
  36396. magicString,
  36397. topLevelDeclarations,
  36398. topLevelRequireDeclarators,
  36399. reassignedNames,
  36400. HELPERS_NAME,
  36401. dynamicRegisterSources,
  36402. moduleName,
  36403. exportsName,
  36404. id,
  36405. exportMode
  36406. );
  36407. const exportBlock = isEsModule
  36408. ? ''
  36409. : rewriteExportsAndGetExportsBlock(
  36410. magicString,
  36411. moduleName,
  36412. exportsName,
  36413. shouldWrap,
  36414. moduleExportsAssignments,
  36415. firstTopLevelModuleExportsAssignment,
  36416. exportsAssignmentsByName,
  36417. topLevelAssignments,
  36418. topLevelDefineCompiledEsmExpressions,
  36419. deconflictedExportNames,
  36420. code,
  36421. HELPERS_NAME,
  36422. exportMode,
  36423. detectWrappedDefault,
  36424. defaultIsModuleExports
  36425. );
  36426. if (shouldWrap) {
  36427. wrapCode(magicString, uses, moduleName, exportsName);
  36428. }
  36429. magicString
  36430. .trim()
  36431. .prepend(leadingComment + importBlock)
  36432. .append(exportBlock);
  36433. return {
  36434. code: magicString.toString(),
  36435. map: sourceMap ? magicString.generateMap() : null,
  36436. syntheticNamedExports: isEsModule ? false : '__moduleExports',
  36437. meta: { commonjs: { isCommonJS: !isEsModule } }
  36438. };
  36439. }
  36440. function commonjs(options = {}) {
  36441. const extensions = options.extensions || ['.js'];
  36442. const filter = createFilter(options.include, options.exclude);
  36443. const {
  36444. ignoreGlobal,
  36445. ignoreDynamicRequires,
  36446. requireReturnsDefault: requireReturnsDefaultOption,
  36447. esmExternals
  36448. } = options;
  36449. const getRequireReturnsDefault =
  36450. typeof requireReturnsDefaultOption === 'function'
  36451. ? requireReturnsDefaultOption
  36452. : () => requireReturnsDefaultOption;
  36453. let esmExternalIds;
  36454. const isEsmExternal =
  36455. typeof esmExternals === 'function'
  36456. ? esmExternals
  36457. : Array.isArray(esmExternals)
  36458. ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
  36459. : () => esmExternals;
  36460. const defaultIsModuleExports =
  36461. typeof options.defaultIsModuleExports === 'boolean' ? options.defaultIsModuleExports : 'auto';
  36462. const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
  36463. options.dynamicRequireTargets
  36464. );
  36465. const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
  36466. const commonDir = isDynamicRequireModulesEnabled
  36467. ? commondir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
  36468. : null;
  36469. const esModulesWithDefaultExport = new Set();
  36470. const esModulesWithNamedExports = new Set();
  36471. const commonJsMetaPromises = new Map();
  36472. const ignoreRequire =
  36473. typeof options.ignore === 'function'
  36474. ? options.ignore
  36475. : Array.isArray(options.ignore)
  36476. ? (id) => options.ignore.includes(id)
  36477. : () => false;
  36478. const getIgnoreTryCatchRequireStatementMode = (id) => {
  36479. const mode =
  36480. typeof options.ignoreTryCatch === 'function'
  36481. ? options.ignoreTryCatch(id)
  36482. : Array.isArray(options.ignoreTryCatch)
  36483. ? options.ignoreTryCatch.includes(id)
  36484. : options.ignoreTryCatch || false;
  36485. return {
  36486. canConvertRequire: mode !== 'remove' && mode !== true,
  36487. shouldRemoveRequireStatement: mode === 'remove'
  36488. };
  36489. };
  36490. const resolveId = getResolveId(extensions);
  36491. const sourceMap = options.sourceMap !== false;
  36492. function transformAndCheckExports(code, id) {
  36493. if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
  36494. // eslint-disable-next-line no-param-reassign
  36495. code =
  36496. getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
  36497. }
  36498. const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
  36499. this.parse,
  36500. code,
  36501. id
  36502. );
  36503. if (hasDefaultExport) {
  36504. esModulesWithDefaultExport.add(id);
  36505. }
  36506. if (hasNamedExports) {
  36507. esModulesWithNamedExports.add(id);
  36508. }
  36509. if (
  36510. !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
  36511. (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
  36512. ) {
  36513. return { meta: { commonjs: { isCommonJS: false } } };
  36514. }
  36515. // avoid wrapping as this is a commonjsRegister call
  36516. const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
  36517. if (disableWrap) {
  36518. // eslint-disable-next-line no-param-reassign
  36519. id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
  36520. }
  36521. return transformCommonjs(
  36522. this.parse,
  36523. code,
  36524. id,
  36525. isEsModule,
  36526. ignoreGlobal || isEsModule,
  36527. ignoreRequire,
  36528. ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
  36529. getIgnoreTryCatchRequireStatementMode,
  36530. sourceMap,
  36531. isDynamicRequireModulesEnabled,
  36532. dynamicRequireModuleSet,
  36533. disableWrap,
  36534. commonDir,
  36535. ast,
  36536. defaultIsModuleExports
  36537. );
  36538. }
  36539. return {
  36540. name: 'commonjs',
  36541. buildStart() {
  36542. validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
  36543. if (options.namedExports != null) {
  36544. this.warn(
  36545. 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
  36546. );
  36547. }
  36548. },
  36549. resolveId,
  36550. load(id) {
  36551. if (id === HELPERS_ID) {
  36552. return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
  36553. }
  36554. if (id.startsWith(HELPERS_ID)) {
  36555. return getSpecificHelperProxy(id);
  36556. }
  36557. if (isWrappedId(id, MODULE_SUFFIX)) {
  36558. const actualId = unwrapId(id, MODULE_SUFFIX);
  36559. let name = getName(actualId);
  36560. let code;
  36561. if (isDynamicRequireModulesEnabled) {
  36562. if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
  36563. name = `${name}_`;
  36564. }
  36565. code =
  36566. `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
  36567. `var ${name} = createModule(${JSON.stringify(
  36568. getVirtualPathForDynamicRequirePath(path$w.dirname(actualId), commonDir)
  36569. )});\n` +
  36570. `export {${name} as __module}`;
  36571. } else {
  36572. code = `var ${name} = {exports: {}}; export {${name} as __module}`;
  36573. }
  36574. return {
  36575. code,
  36576. syntheticNamedExports: '__module',
  36577. meta: { commonjs: { isCommonJS: false } }
  36578. };
  36579. }
  36580. if (isWrappedId(id, EXPORTS_SUFFIX)) {
  36581. const actualId = unwrapId(id, EXPORTS_SUFFIX);
  36582. const name = getName(actualId);
  36583. return {
  36584. code: `var ${name} = {}; export {${name} as __exports}`,
  36585. meta: { commonjs: { isCommonJS: false } }
  36586. };
  36587. }
  36588. if (isWrappedId(id, EXTERNAL_SUFFIX)) {
  36589. const actualId = unwrapId(id, EXTERNAL_SUFFIX);
  36590. return getUnknownRequireProxy(
  36591. actualId,
  36592. isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
  36593. );
  36594. }
  36595. if (id === DYNAMIC_PACKAGES_ID) {
  36596. return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
  36597. }
  36598. if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
  36599. return getDynamicJsonProxy(id, commonDir);
  36600. }
  36601. if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
  36602. return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
  36603. }
  36604. if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
  36605. return getDynamicRequireProxy(
  36606. normalizePathSlashes(unwrapId(id, DYNAMIC_REGISTER_SUFFIX)),
  36607. commonDir
  36608. );
  36609. }
  36610. if (isWrappedId(id, PROXY_SUFFIX)) {
  36611. const actualId = unwrapId(id, PROXY_SUFFIX);
  36612. return getStaticRequireProxy(
  36613. actualId,
  36614. getRequireReturnsDefault(actualId),
  36615. esModulesWithDefaultExport,
  36616. esModulesWithNamedExports,
  36617. commonJsMetaPromises
  36618. );
  36619. }
  36620. return null;
  36621. },
  36622. transform(code, rawId) {
  36623. let id = rawId;
  36624. if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
  36625. id = unwrapId(id, DYNAMIC_REGISTER_SUFFIX);
  36626. }
  36627. const extName = path$w.extname(id);
  36628. if (
  36629. extName !== '.cjs' &&
  36630. id !== DYNAMIC_PACKAGES_ID &&
  36631. !id.startsWith(DYNAMIC_JSON_PREFIX) &&
  36632. (!filter(id) || !extensions.includes(extName))
  36633. ) {
  36634. return null;
  36635. }
  36636. try {
  36637. return transformAndCheckExports.call(this, code, rawId);
  36638. } catch (err) {
  36639. return this.error(err, err.loc);
  36640. }
  36641. },
  36642. moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
  36643. if (commonjsMeta && commonjsMeta.isCommonJS != null) {
  36644. setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
  36645. return;
  36646. }
  36647. setCommonJSMetaPromise(commonJsMetaPromises, id, null);
  36648. }
  36649. };
  36650. }
  36651. var globby$1 = {exports: {}};
  36652. var arrayUnion$1 = (...arguments_) => {
  36653. return [...new Set([].concat(...arguments_))];
  36654. };
  36655. var dirGlob$1 = {exports: {}};
  36656. var pathType$1 = {};
  36657. const {promisify: promisify$6} = require$$0__default$3;
  36658. const fs$e = fs__default;
  36659. async function isType(fsStatType, statsMethodName, filePath) {
  36660. if (typeof filePath !== 'string') {
  36661. throw new TypeError(`Expected a string, got ${typeof filePath}`);
  36662. }
  36663. try {
  36664. const stats = await promisify$6(fs$e[fsStatType])(filePath);
  36665. return stats[statsMethodName]();
  36666. } catch (error) {
  36667. if (error.code === 'ENOENT') {
  36668. return false;
  36669. }
  36670. throw error;
  36671. }
  36672. }
  36673. function isTypeSync(fsStatType, statsMethodName, filePath) {
  36674. if (typeof filePath !== 'string') {
  36675. throw new TypeError(`Expected a string, got ${typeof filePath}`);
  36676. }
  36677. try {
  36678. return fs$e[fsStatType](filePath)[statsMethodName]();
  36679. } catch (error) {
  36680. if (error.code === 'ENOENT') {
  36681. return false;
  36682. }
  36683. throw error;
  36684. }
  36685. }
  36686. pathType$1.isFile = isType.bind(null, 'stat', 'isFile');
  36687. pathType$1.isDirectory = isType.bind(null, 'stat', 'isDirectory');
  36688. pathType$1.isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
  36689. pathType$1.isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
  36690. pathType$1.isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
  36691. pathType$1.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
  36692. const path$c = path__default;
  36693. const pathType = pathType$1;
  36694. const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];
  36695. const getPath = (filepath, cwd) => {
  36696. const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;
  36697. return path$c.isAbsolute(pth) ? pth : path$c.join(cwd, pth);
  36698. };
  36699. const addExtensions = (file, extensions) => {
  36700. if (path$c.extname(file)) {
  36701. return `**/${file}`;
  36702. }
  36703. return `**/${file}.${getExtensions(extensions)}`;
  36704. };
  36705. const getGlob = (directory, options) => {
  36706. if (options.files && !Array.isArray(options.files)) {
  36707. throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);
  36708. }
  36709. if (options.extensions && !Array.isArray(options.extensions)) {
  36710. throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);
  36711. }
  36712. if (options.files && options.extensions) {
  36713. return options.files.map(x => path$c.posix.join(directory, addExtensions(x, options.extensions)));
  36714. }
  36715. if (options.files) {
  36716. return options.files.map(x => path$c.posix.join(directory, `**/${x}`));
  36717. }
  36718. if (options.extensions) {
  36719. return [path$c.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];
  36720. }
  36721. return [path$c.posix.join(directory, '**')];
  36722. };
  36723. dirGlob$1.exports = async (input, options) => {
  36724. options = {
  36725. cwd: process.cwd(),
  36726. ...options
  36727. };
  36728. if (typeof options.cwd !== 'string') {
  36729. throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
  36730. }
  36731. const globs = await Promise.all([].concat(input).map(async x => {
  36732. const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));
  36733. return isDirectory ? getGlob(x, options) : x;
  36734. }));
  36735. return [].concat.apply([], globs); // eslint-disable-line prefer-spread
  36736. };
  36737. dirGlob$1.exports.sync = (input, options) => {
  36738. options = {
  36739. cwd: process.cwd(),
  36740. ...options
  36741. };
  36742. if (typeof options.cwd !== 'string') {
  36743. throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
  36744. }
  36745. const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);
  36746. return [].concat.apply([], globs); // eslint-disable-line prefer-spread
  36747. };
  36748. var gitignore$1 = {exports: {}};
  36749. // A simple implementation of make-array
  36750. function makeArray (subject) {
  36751. return Array.isArray(subject)
  36752. ? subject
  36753. : [subject]
  36754. }
  36755. const EMPTY = '';
  36756. const SPACE = ' ';
  36757. const ESCAPE = '\\';
  36758. const REGEX_TEST_BLANK_LINE = /^\s+$/;
  36759. const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
  36760. const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
  36761. const REGEX_SPLITALL_CRLF = /\r?\n/g;
  36762. // /foo,
  36763. // ./foo,
  36764. // ../foo,
  36765. // .
  36766. // ..
  36767. const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
  36768. const SLASH$1 = '/';
  36769. const KEY_IGNORE = typeof Symbol !== 'undefined'
  36770. ? Symbol.for('node-ignore')
  36771. /* istanbul ignore next */
  36772. : 'node-ignore';
  36773. const define = (object, key, value) =>
  36774. Object.defineProperty(object, key, {value});
  36775. const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
  36776. // Sanitize the range of a regular expression
  36777. // The cases are complicated, see test cases for details
  36778. const sanitizeRange = range => range.replace(
  36779. REGEX_REGEXP_RANGE,
  36780. (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)
  36781. ? match
  36782. // Invalid range (out of order) which is ok for gitignore rules but
  36783. // fatal for JavaScript regular expression, so eliminate it.
  36784. : EMPTY
  36785. );
  36786. // See fixtures #59
  36787. const cleanRangeBackSlash = slashes => {
  36788. const {length} = slashes;
  36789. return slashes.slice(0, length - length % 2)
  36790. };
  36791. // > If the pattern ends with a slash,
  36792. // > it is removed for the purpose of the following description,
  36793. // > but it would only find a match with a directory.
  36794. // > In other words, foo/ will match a directory foo and paths underneath it,
  36795. // > but will not match a regular file or a symbolic link foo
  36796. // > (this is consistent with the way how pathspec works in general in Git).
  36797. // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
  36798. // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
  36799. // you could use option `mark: true` with `glob`
  36800. // '`foo/`' should not continue with the '`..`'
  36801. const REPLACERS = [
  36802. // > Trailing spaces are ignored unless they are quoted with backslash ("\")
  36803. [
  36804. // (a\ ) -> (a )
  36805. // (a ) -> (a)
  36806. // (a \ ) -> (a )
  36807. /\\?\s+$/,
  36808. match => match.indexOf('\\') === 0
  36809. ? SPACE
  36810. : EMPTY
  36811. ],
  36812. // replace (\ ) with ' '
  36813. [
  36814. /\\\s/g,
  36815. () => SPACE
  36816. ],
  36817. // Escape metacharacters
  36818. // which is written down by users but means special for regular expressions.
  36819. // > There are 12 characters with special meanings:
  36820. // > - the backslash \,
  36821. // > - the caret ^,
  36822. // > - the dollar sign $,
  36823. // > - the period or dot .,
  36824. // > - the vertical bar or pipe symbol |,
  36825. // > - the question mark ?,
  36826. // > - the asterisk or star *,
  36827. // > - the plus sign +,
  36828. // > - the opening parenthesis (,
  36829. // > - the closing parenthesis ),
  36830. // > - and the opening square bracket [,
  36831. // > - the opening curly brace {,
  36832. // > These special characters are often called "metacharacters".
  36833. [
  36834. /[\\$.|*+(){^]/g,
  36835. match => `\\${match}`
  36836. ],
  36837. [
  36838. // > a question mark (?) matches a single character
  36839. /(?!\\)\?/g,
  36840. () => '[^/]'
  36841. ],
  36842. // leading slash
  36843. [
  36844. // > A leading slash matches the beginning of the pathname.
  36845. // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
  36846. // A leading slash matches the beginning of the pathname
  36847. /^\//,
  36848. () => '^'
  36849. ],
  36850. // replace special metacharacter slash after the leading slash
  36851. [
  36852. /\//g,
  36853. () => '\\/'
  36854. ],
  36855. [
  36856. // > A leading "**" followed by a slash means match in all directories.
  36857. // > For example, "**/foo" matches file or directory "foo" anywhere,
  36858. // > the same as pattern "foo".
  36859. // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
  36860. // > under directory "foo".
  36861. // Notice that the '*'s have been replaced as '\\*'
  36862. /^\^*\\\*\\\*\\\//,
  36863. // '**/foo' <-> 'foo'
  36864. () => '^(?:.*\\/)?'
  36865. ],
  36866. // starting
  36867. [
  36868. // there will be no leading '/'
  36869. // (which has been replaced by section "leading slash")
  36870. // If starts with '**', adding a '^' to the regular expression also works
  36871. /^(?=[^^])/,
  36872. function startingReplacer () {
  36873. // If has a slash `/` at the beginning or middle
  36874. return !/\/(?!$)/.test(this)
  36875. // > Prior to 2.22.1
  36876. // > If the pattern does not contain a slash /,
  36877. // > Git treats it as a shell glob pattern
  36878. // Actually, if there is only a trailing slash,
  36879. // git also treats it as a shell glob pattern
  36880. // After 2.22.1 (compatible but clearer)
  36881. // > If there is a separator at the beginning or middle (or both)
  36882. // > of the pattern, then the pattern is relative to the directory
  36883. // > level of the particular .gitignore file itself.
  36884. // > Otherwise the pattern may also match at any level below
  36885. // > the .gitignore level.
  36886. ? '(?:^|\\/)'
  36887. // > Otherwise, Git treats the pattern as a shell glob suitable for
  36888. // > consumption by fnmatch(3)
  36889. : '^'
  36890. }
  36891. ],
  36892. // two globstars
  36893. [
  36894. // Use lookahead assertions so that we could match more than one `'/**'`
  36895. /\\\/\\\*\\\*(?=\\\/|$)/g,
  36896. // Zero, one or several directories
  36897. // should not use '*', or it will be replaced by the next replacer
  36898. // Check if it is not the last `'/**'`
  36899. (_, index, str) => index + 6 < str.length
  36900. // case: /**/
  36901. // > A slash followed by two consecutive asterisks then a slash matches
  36902. // > zero or more directories.
  36903. // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
  36904. // '/**/'
  36905. ? '(?:\\/[^\\/]+)*'
  36906. // case: /**
  36907. // > A trailing `"/**"` matches everything inside.
  36908. // #21: everything inside but it should not include the current folder
  36909. : '\\/.+'
  36910. ],
  36911. // intermediate wildcards
  36912. [
  36913. // Never replace escaped '*'
  36914. // ignore rule '\*' will match the path '*'
  36915. // 'abc.*/' -> go
  36916. // 'abc.*' -> skip this rule
  36917. /(^|[^\\]+)\\\*(?=.+)/g,
  36918. // '*.js' matches '.js'
  36919. // '*.js' doesn't match 'abc'
  36920. (_, p1) => `${p1}[^\\/]*`
  36921. ],
  36922. [
  36923. // unescape, revert step 3 except for back slash
  36924. // For example, if a user escape a '\\*',
  36925. // after step 3, the result will be '\\\\\\*'
  36926. /\\\\\\(?=[$.|*+(){^])/g,
  36927. () => ESCAPE
  36928. ],
  36929. [
  36930. // '\\\\' -> '\\'
  36931. /\\\\/g,
  36932. () => ESCAPE
  36933. ],
  36934. [
  36935. // > The range notation, e.g. [a-zA-Z],
  36936. // > can be used to match one of the characters in a range.
  36937. // `\` is escaped by step 3
  36938. /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
  36939. (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE
  36940. // '\\[bar]' -> '\\\\[bar\\]'
  36941. ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`
  36942. : close === ']'
  36943. ? endEscape.length % 2 === 0
  36944. // A normal case, and it is a range notation
  36945. // '[bar]'
  36946. // '[bar\\\\]'
  36947. ? `[${sanitizeRange(range)}${endEscape}]`
  36948. // Invalid range notaton
  36949. // '[bar\\]' -> '[bar\\\\]'
  36950. : '[]'
  36951. : '[]'
  36952. ],
  36953. // ending
  36954. [
  36955. // 'js' will not match 'js.'
  36956. // 'ab' will not match 'abc'
  36957. /(?:[^*])$/,
  36958. // WTF!
  36959. // https://git-scm.com/docs/gitignore
  36960. // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
  36961. // which re-fixes #24, #38
  36962. // > If there is a separator at the end of the pattern then the pattern
  36963. // > will only match directories, otherwise the pattern can match both
  36964. // > files and directories.
  36965. // 'js*' will not match 'a.js'
  36966. // 'js/' will not match 'a.js'
  36967. // 'js' will match 'a.js' and 'a.js/'
  36968. match => /\/$/.test(match)
  36969. // foo/ will not match 'foo'
  36970. ? `${match}$`
  36971. // foo matches 'foo' and 'foo/'
  36972. : `${match}(?=$|\\/$)`
  36973. ],
  36974. // trailing wildcard
  36975. [
  36976. /(\^|\\\/)?\\\*$/,
  36977. (_, p1) => {
  36978. const prefix = p1
  36979. // '\^':
  36980. // '/*' does not match EMPTY
  36981. // '/*' does not match everything
  36982. // '\\\/':
  36983. // 'abc/*' does not match 'abc/'
  36984. ? `${p1}[^/]+`
  36985. // 'a*' matches 'a'
  36986. // 'a*' matches 'aa'
  36987. : '[^/]*';
  36988. return `${prefix}(?=$|\\/$)`
  36989. }
  36990. ],
  36991. ];
  36992. // A simple cache, because an ignore rule only has only one certain meaning
  36993. const regexCache = Object.create(null);
  36994. // @param {pattern}
  36995. const makeRegex = (pattern, negative, ignorecase) => {
  36996. const r = regexCache[pattern];
  36997. if (r) {
  36998. return r
  36999. }
  37000. // const replacers = negative
  37001. // ? NEGATIVE_REPLACERS
  37002. // : POSITIVE_REPLACERS
  37003. const source = REPLACERS.reduce(
  37004. (prev, current) => prev.replace(current[0], current[1].bind(pattern)),
  37005. pattern
  37006. );
  37007. return regexCache[pattern] = ignorecase
  37008. ? new RegExp(source, 'i')
  37009. : new RegExp(source)
  37010. };
  37011. const isString = subject => typeof subject === 'string';
  37012. // > A blank line matches no files, so it can serve as a separator for readability.
  37013. const checkPattern = pattern => pattern
  37014. && isString(pattern)
  37015. && !REGEX_TEST_BLANK_LINE.test(pattern)
  37016. // > A line starting with # serves as a comment.
  37017. && pattern.indexOf('#') !== 0;
  37018. const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);
  37019. class IgnoreRule {
  37020. constructor (
  37021. origin,
  37022. pattern,
  37023. negative,
  37024. regex
  37025. ) {
  37026. this.origin = origin;
  37027. this.pattern = pattern;
  37028. this.negative = negative;
  37029. this.regex = regex;
  37030. }
  37031. }
  37032. const createRule = (pattern, ignorecase) => {
  37033. const origin = pattern;
  37034. let negative = false;
  37035. // > An optional prefix "!" which negates the pattern;
  37036. if (pattern.indexOf('!') === 0) {
  37037. negative = true;
  37038. pattern = pattern.substr(1);
  37039. }
  37040. pattern = pattern
  37041. // > Put a backslash ("\") in front of the first "!" for patterns that
  37042. // > begin with a literal "!", for example, `"\!important!.txt"`.
  37043. .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')
  37044. // > Put a backslash ("\") in front of the first hash for patterns that
  37045. // > begin with a hash.
  37046. .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
  37047. const regex = makeRegex(pattern, negative, ignorecase);
  37048. return new IgnoreRule(
  37049. origin,
  37050. pattern,
  37051. negative,
  37052. regex
  37053. )
  37054. };
  37055. const throwError = (message, Ctor) => {
  37056. throw new Ctor(message)
  37057. };
  37058. const checkPath = (path, originalPath, doThrow) => {
  37059. if (!isString(path)) {
  37060. return doThrow(
  37061. `path must be a string, but got \`${originalPath}\``,
  37062. TypeError
  37063. )
  37064. }
  37065. // We don't know if we should ignore EMPTY, so throw
  37066. if (!path) {
  37067. return doThrow(`path must not be empty`, TypeError)
  37068. }
  37069. // Check if it is a relative path
  37070. if (checkPath.isNotRelative(path)) {
  37071. const r = '`path.relative()`d';
  37072. return doThrow(
  37073. `path should be a ${r} string, but got "${originalPath}"`,
  37074. RangeError
  37075. )
  37076. }
  37077. return true
  37078. };
  37079. const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);
  37080. checkPath.isNotRelative = isNotRelative;
  37081. checkPath.convert = p => p;
  37082. class Ignore {
  37083. constructor ({
  37084. ignorecase = true
  37085. } = {}) {
  37086. this._rules = [];
  37087. this._ignorecase = ignorecase;
  37088. define(this, KEY_IGNORE, true);
  37089. this._initCache();
  37090. }
  37091. _initCache () {
  37092. this._ignoreCache = Object.create(null);
  37093. this._testCache = Object.create(null);
  37094. }
  37095. _addPattern (pattern) {
  37096. // #32
  37097. if (pattern && pattern[KEY_IGNORE]) {
  37098. this._rules = this._rules.concat(pattern._rules);
  37099. this._added = true;
  37100. return
  37101. }
  37102. if (checkPattern(pattern)) {
  37103. const rule = createRule(pattern, this._ignorecase);
  37104. this._added = true;
  37105. this._rules.push(rule);
  37106. }
  37107. }
  37108. // @param {Array<string> | string | Ignore} pattern
  37109. add (pattern) {
  37110. this._added = false;
  37111. makeArray(
  37112. isString(pattern)
  37113. ? splitPattern(pattern)
  37114. : pattern
  37115. ).forEach(this._addPattern, this);
  37116. // Some rules have just added to the ignore,
  37117. // making the behavior changed.
  37118. if (this._added) {
  37119. this._initCache();
  37120. }
  37121. return this
  37122. }
  37123. // legacy
  37124. addPattern (pattern) {
  37125. return this.add(pattern)
  37126. }
  37127. // | ignored : unignored
  37128. // negative | 0:0 | 0:1 | 1:0 | 1:1
  37129. // -------- | ------- | ------- | ------- | --------
  37130. // 0 | TEST | TEST | SKIP | X
  37131. // 1 | TESTIF | SKIP | TEST | X
  37132. // - SKIP: always skip
  37133. // - TEST: always test
  37134. // - TESTIF: only test if checkUnignored
  37135. // - X: that never happen
  37136. // @param {boolean} whether should check if the path is unignored,
  37137. // setting `checkUnignored` to `false` could reduce additional
  37138. // path matching.
  37139. // @returns {TestResult} true if a file is ignored
  37140. _testOne (path, checkUnignored) {
  37141. let ignored = false;
  37142. let unignored = false;
  37143. this._rules.forEach(rule => {
  37144. const {negative} = rule;
  37145. if (
  37146. unignored === negative && ignored !== unignored
  37147. || negative && !ignored && !unignored && !checkUnignored
  37148. ) {
  37149. return
  37150. }
  37151. const matched = rule.regex.test(path);
  37152. if (matched) {
  37153. ignored = !negative;
  37154. unignored = negative;
  37155. }
  37156. });
  37157. return {
  37158. ignored,
  37159. unignored
  37160. }
  37161. }
  37162. // @returns {TestResult}
  37163. _test (originalPath, cache, checkUnignored, slices) {
  37164. const path = originalPath
  37165. // Supports nullable path
  37166. && checkPath.convert(originalPath);
  37167. checkPath(path, originalPath, throwError);
  37168. return this._t(path, cache, checkUnignored, slices)
  37169. }
  37170. _t (path, cache, checkUnignored, slices) {
  37171. if (path in cache) {
  37172. return cache[path]
  37173. }
  37174. if (!slices) {
  37175. // path/to/a.js
  37176. // ['path', 'to', 'a.js']
  37177. slices = path.split(SLASH$1);
  37178. }
  37179. slices.pop();
  37180. // If the path has no parent directory, just test it
  37181. if (!slices.length) {
  37182. return cache[path] = this._testOne(path, checkUnignored)
  37183. }
  37184. const parent = this._t(
  37185. slices.join(SLASH$1) + SLASH$1,
  37186. cache,
  37187. checkUnignored,
  37188. slices
  37189. );
  37190. // If the path contains a parent directory, check the parent first
  37191. return cache[path] = parent.ignored
  37192. // > It is not possible to re-include a file if a parent directory of
  37193. // > that file is excluded.
  37194. ? parent
  37195. : this._testOne(path, checkUnignored)
  37196. }
  37197. ignores (path) {
  37198. return this._test(path, this._ignoreCache, false).ignored
  37199. }
  37200. createFilter () {
  37201. return path => !this.ignores(path)
  37202. }
  37203. filter (paths) {
  37204. return makeArray(paths).filter(this.createFilter())
  37205. }
  37206. // @returns {TestResult}
  37207. test (path) {
  37208. return this._test(path, this._testCache, true)
  37209. }
  37210. }
  37211. const factory = options => new Ignore(options);
  37212. const returnFalse = () => false;
  37213. const isPathValid = path =>
  37214. checkPath(path && checkPath.convert(path), path, returnFalse);
  37215. factory.isPathValid = isPathValid;
  37216. // Fixes typescript
  37217. factory.default = factory;
  37218. var ignore = factory;
  37219. // Windows
  37220. // --------------------------------------------------------------
  37221. /* istanbul ignore if */
  37222. if (
  37223. // Detect `process` so that it can run in browsers.
  37224. typeof process !== 'undefined'
  37225. && (
  37226. process.env && process.env.IGNORE_TEST_WIN32
  37227. || process.platform === 'win32'
  37228. )
  37229. ) {
  37230. /* eslint no-control-regex: "off" */
  37231. const makePosix = str => /^\\\\\?\\/.test(str)
  37232. || /["<>|\u0000-\u001F]+/u.test(str)
  37233. ? str
  37234. : str.replace(/\\/g, '/');
  37235. checkPath.convert = makePosix;
  37236. // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
  37237. // 'd:\\foo'
  37238. const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
  37239. checkPath.isNotRelative = path =>
  37240. REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path)
  37241. || isNotRelative(path);
  37242. }
  37243. var slash$1 = path => {
  37244. const isExtendedLengthPath = /^\\\\\?\\/.test(path);
  37245. const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
  37246. if (isExtendedLengthPath || hasNonAscii) {
  37247. return path;
  37248. }
  37249. return path.replace(/\\/g, '/');
  37250. };
  37251. const {promisify: promisify$5} = require$$0__default$3;
  37252. const fs$d = fs__default;
  37253. const path$b = path__default;
  37254. const fastGlob$1 = out;
  37255. const gitIgnore = ignore;
  37256. const slash = slash$1;
  37257. const DEFAULT_IGNORE = [
  37258. '**/node_modules/**',
  37259. '**/flow-typed/**',
  37260. '**/coverage/**',
  37261. '**/.git'
  37262. ];
  37263. const readFileP = promisify$5(fs$d.readFile);
  37264. const mapGitIgnorePatternTo = base => ignore => {
  37265. if (ignore.startsWith('!')) {
  37266. return '!' + path$b.posix.join(base, ignore.slice(1));
  37267. }
  37268. return path$b.posix.join(base, ignore);
  37269. };
  37270. const parseGitIgnore = (content, options) => {
  37271. const base = slash(path$b.relative(options.cwd, path$b.dirname(options.fileName)));
  37272. return content
  37273. .split(/\r?\n/)
  37274. .filter(Boolean)
  37275. .filter(line => !line.startsWith('#'))
  37276. .map(mapGitIgnorePatternTo(base));
  37277. };
  37278. const reduceIgnore = files => {
  37279. const ignores = gitIgnore();
  37280. for (const file of files) {
  37281. ignores.add(parseGitIgnore(file.content, {
  37282. cwd: file.cwd,
  37283. fileName: file.filePath
  37284. }));
  37285. }
  37286. return ignores;
  37287. };
  37288. const ensureAbsolutePathForCwd = (cwd, p) => {
  37289. cwd = slash(cwd);
  37290. if (path$b.isAbsolute(p)) {
  37291. if (slash(p).startsWith(cwd)) {
  37292. return p;
  37293. }
  37294. throw new Error(`Path ${p} is not in cwd ${cwd}`);
  37295. }
  37296. return path$b.join(cwd, p);
  37297. };
  37298. const getIsIgnoredPredecate = (ignores, cwd) => {
  37299. return p => ignores.ignores(slash(path$b.relative(cwd, ensureAbsolutePathForCwd(cwd, p.path || p))));
  37300. };
  37301. const getFile = async (file, cwd) => {
  37302. const filePath = path$b.join(cwd, file);
  37303. const content = await readFileP(filePath, 'utf8');
  37304. return {
  37305. cwd,
  37306. filePath,
  37307. content
  37308. };
  37309. };
  37310. const getFileSync = (file, cwd) => {
  37311. const filePath = path$b.join(cwd, file);
  37312. const content = fs$d.readFileSync(filePath, 'utf8');
  37313. return {
  37314. cwd,
  37315. filePath,
  37316. content
  37317. };
  37318. };
  37319. const normalizeOptions = ({
  37320. ignore = [],
  37321. cwd = slash(process.cwd())
  37322. } = {}) => {
  37323. return {ignore, cwd};
  37324. };
  37325. gitignore$1.exports = async options => {
  37326. options = normalizeOptions(options);
  37327. const paths = await fastGlob$1('**/.gitignore', {
  37328. ignore: DEFAULT_IGNORE.concat(options.ignore),
  37329. cwd: options.cwd
  37330. });
  37331. const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
  37332. const ignores = reduceIgnore(files);
  37333. return getIsIgnoredPredecate(ignores, options.cwd);
  37334. };
  37335. gitignore$1.exports.sync = options => {
  37336. options = normalizeOptions(options);
  37337. const paths = fastGlob$1.sync('**/.gitignore', {
  37338. ignore: DEFAULT_IGNORE.concat(options.ignore),
  37339. cwd: options.cwd
  37340. });
  37341. const files = paths.map(file => getFileSync(file, options.cwd));
  37342. const ignores = reduceIgnore(files);
  37343. return getIsIgnoredPredecate(ignores, options.cwd);
  37344. };
  37345. const {Transform} = require$$0__default$2;
  37346. class ObjectTransform extends Transform {
  37347. constructor() {
  37348. super({
  37349. objectMode: true
  37350. });
  37351. }
  37352. }
  37353. class FilterStream$1 extends ObjectTransform {
  37354. constructor(filter) {
  37355. super();
  37356. this._filter = filter;
  37357. }
  37358. _transform(data, encoding, callback) {
  37359. if (this._filter(data)) {
  37360. this.push(data);
  37361. }
  37362. callback();
  37363. }
  37364. }
  37365. class UniqueStream$1 extends ObjectTransform {
  37366. constructor() {
  37367. super();
  37368. this._pushed = new Set();
  37369. }
  37370. _transform(data, encoding, callback) {
  37371. if (!this._pushed.has(data)) {
  37372. this.push(data);
  37373. this._pushed.add(data);
  37374. }
  37375. callback();
  37376. }
  37377. }
  37378. var streamUtils = {
  37379. FilterStream: FilterStream$1,
  37380. UniqueStream: UniqueStream$1
  37381. };
  37382. const fs$c = fs__default;
  37383. const arrayUnion = arrayUnion$1;
  37384. const merge2 = merge2_1;
  37385. const fastGlob = out;
  37386. const dirGlob = dirGlob$1.exports;
  37387. const gitignore = gitignore$1.exports;
  37388. const {FilterStream, UniqueStream} = streamUtils;
  37389. const DEFAULT_FILTER = () => false;
  37390. const isNegative = pattern => pattern[0] === '!';
  37391. const assertPatternsInput = patterns => {
  37392. if (!patterns.every(pattern => typeof pattern === 'string')) {
  37393. throw new TypeError('Patterns must be a string or an array of strings');
  37394. }
  37395. };
  37396. const checkCwdOption = (options = {}) => {
  37397. if (!options.cwd) {
  37398. return;
  37399. }
  37400. let stat;
  37401. try {
  37402. stat = fs$c.statSync(options.cwd);
  37403. } catch {
  37404. return;
  37405. }
  37406. if (!stat.isDirectory()) {
  37407. throw new Error('The `cwd` option must be a path to a directory');
  37408. }
  37409. };
  37410. const getPathString = p => p.stats instanceof fs$c.Stats ? p.path : p;
  37411. const generateGlobTasks = (patterns, taskOptions) => {
  37412. patterns = arrayUnion([].concat(patterns));
  37413. assertPatternsInput(patterns);
  37414. checkCwdOption(taskOptions);
  37415. const globTasks = [];
  37416. taskOptions = {
  37417. ignore: [],
  37418. expandDirectories: true,
  37419. ...taskOptions
  37420. };
  37421. for (const [index, pattern] of patterns.entries()) {
  37422. if (isNegative(pattern)) {
  37423. continue;
  37424. }
  37425. const ignore = patterns
  37426. .slice(index)
  37427. .filter(pattern => isNegative(pattern))
  37428. .map(pattern => pattern.slice(1));
  37429. const options = {
  37430. ...taskOptions,
  37431. ignore: taskOptions.ignore.concat(ignore)
  37432. };
  37433. globTasks.push({pattern, options});
  37434. }
  37435. return globTasks;
  37436. };
  37437. const globDirs = (task, fn) => {
  37438. let options = {};
  37439. if (task.options.cwd) {
  37440. options.cwd = task.options.cwd;
  37441. }
  37442. if (Array.isArray(task.options.expandDirectories)) {
  37443. options = {
  37444. ...options,
  37445. files: task.options.expandDirectories
  37446. };
  37447. } else if (typeof task.options.expandDirectories === 'object') {
  37448. options = {
  37449. ...options,
  37450. ...task.options.expandDirectories
  37451. };
  37452. }
  37453. return fn(task.pattern, options);
  37454. };
  37455. const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
  37456. const getFilterSync = options => {
  37457. return options && options.gitignore ?
  37458. gitignore.sync({cwd: options.cwd, ignore: options.ignore}) :
  37459. DEFAULT_FILTER;
  37460. };
  37461. const globToTask = task => glob => {
  37462. const {options} = task;
  37463. if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
  37464. options.ignore = dirGlob.sync(options.ignore);
  37465. }
  37466. return {
  37467. pattern: glob,
  37468. options
  37469. };
  37470. };
  37471. globby$1.exports = async (patterns, options) => {
  37472. const globTasks = generateGlobTasks(patterns, options);
  37473. const getFilter = async () => {
  37474. return options && options.gitignore ?
  37475. gitignore({cwd: options.cwd, ignore: options.ignore}) :
  37476. DEFAULT_FILTER;
  37477. };
  37478. const getTasks = async () => {
  37479. const tasks = await Promise.all(globTasks.map(async task => {
  37480. const globs = await getPattern(task, dirGlob);
  37481. return Promise.all(globs.map(globToTask(task)));
  37482. }));
  37483. return arrayUnion(...tasks);
  37484. };
  37485. const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
  37486. const paths = await Promise.all(tasks.map(task => fastGlob(task.pattern, task.options)));
  37487. return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
  37488. };
  37489. globby$1.exports.sync = (patterns, options) => {
  37490. const globTasks = generateGlobTasks(patterns, options);
  37491. const tasks = [];
  37492. for (const task of globTasks) {
  37493. const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
  37494. tasks.push(...newTask);
  37495. }
  37496. const filter = getFilterSync(options);
  37497. let matches = [];
  37498. for (const task of tasks) {
  37499. matches = arrayUnion(matches, fastGlob.sync(task.pattern, task.options));
  37500. }
  37501. return matches.filter(path_ => !filter(path_));
  37502. };
  37503. globby$1.exports.stream = (patterns, options) => {
  37504. const globTasks = generateGlobTasks(patterns, options);
  37505. const tasks = [];
  37506. for (const task of globTasks) {
  37507. const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
  37508. tasks.push(...newTask);
  37509. }
  37510. const filter = getFilterSync(options);
  37511. const filterStream = new FilterStream(p => !filter(p));
  37512. const uniqueStream = new UniqueStream();
  37513. return merge2(tasks.map(task => fastGlob.stream(task.pattern, task.options)))
  37514. .pipe(filterStream)
  37515. .pipe(uniqueStream);
  37516. };
  37517. globby$1.exports.generateGlobTasks = generateGlobTasks;
  37518. globby$1.exports.hasMagic = (patterns, options) => []
  37519. .concat(patterns)
  37520. .some(pattern => fastGlob.isDynamicPattern(pattern, options));
  37521. globby$1.exports.gitignore = gitignore;
  37522. var globby = globby$1.exports;
  37523. class VariableDynamicImportError extends Error {}
  37524. /* eslint-disable-next-line no-template-curly-in-string */
  37525. const example = 'For example: import(`./foo/${bar}.js`).';
  37526. function sanitizeString(str) {
  37527. if (str.includes('*')) {
  37528. throw new VariableDynamicImportError('A dynamic import cannot contain * characters.');
  37529. }
  37530. return str;
  37531. }
  37532. function templateLiteralToGlob(node) {
  37533. let glob = '';
  37534. for (let i = 0; i < node.quasis.length; i += 1) {
  37535. glob += sanitizeString(node.quasis[i].value.raw);
  37536. if (node.expressions[i]) {
  37537. glob += expressionToGlob(node.expressions[i]);
  37538. }
  37539. }
  37540. return glob;
  37541. }
  37542. function callExpressionToGlob(node) {
  37543. const { callee } = node;
  37544. if (
  37545. callee.type === 'MemberExpression' &&
  37546. callee.property.type === 'Identifier' &&
  37547. callee.property.name === 'concat'
  37548. ) {
  37549. return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`;
  37550. }
  37551. return '*';
  37552. }
  37553. function binaryExpressionToGlob(node) {
  37554. if (node.operator !== '+') {
  37555. throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
  37556. }
  37557. return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
  37558. }
  37559. function expressionToGlob(node) {
  37560. switch (node.type) {
  37561. case 'TemplateLiteral':
  37562. return templateLiteralToGlob(node);
  37563. case 'CallExpression':
  37564. return callExpressionToGlob(node);
  37565. case 'BinaryExpression':
  37566. return binaryExpressionToGlob(node);
  37567. case 'Literal': {
  37568. return sanitizeString(node.value);
  37569. }
  37570. default:
  37571. return '*';
  37572. }
  37573. }
  37574. function dynamicImportToGlob(node, sourceString) {
  37575. let glob = expressionToGlob(node);
  37576. if (!glob.includes('*')) {
  37577. return null;
  37578. }
  37579. glob = glob.replace(/\*\*/g, '*');
  37580. if (glob.startsWith('*')) {
  37581. throw new VariableDynamicImportError(
  37582. `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`
  37583. );
  37584. }
  37585. if (glob.startsWith('/')) {
  37586. throw new VariableDynamicImportError(
  37587. `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  37588. );
  37589. }
  37590. if (!glob.startsWith('./') && !glob.startsWith('../')) {
  37591. throw new VariableDynamicImportError(
  37592. `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  37593. );
  37594. }
  37595. // Disallow ./*.ext
  37596. const ownDirectoryStarExtension = /^\.\/\*\.[\w]+$/;
  37597. if (ownDirectoryStarExtension.test(glob)) {
  37598. throw new VariableDynamicImportError(
  37599. `${
  37600. `invalid import "${sourceString}". Variable imports cannot import their own directory, ` +
  37601. 'place imports in a separate directory or make the import filename more specific. '
  37602. }${example}`
  37603. );
  37604. }
  37605. if (path__default.extname(glob) === '') {
  37606. throw new VariableDynamicImportError(
  37607. `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`
  37608. );
  37609. }
  37610. return glob;
  37611. }
  37612. function dynamicImportVariables({ include, exclude, warnOnError } = {}) {
  37613. const filter = createFilter(include, exclude);
  37614. return {
  37615. name: 'rollup-plugin-dynamic-import-variables',
  37616. transform(code, id) {
  37617. if (!filter(id)) {
  37618. return null;
  37619. }
  37620. const parsed = this.parse(code);
  37621. let dynamicImportIndex = -1;
  37622. let ms;
  37623. walk$1(parsed, {
  37624. enter: (node) => {
  37625. if (node.type !== 'ImportExpression') {
  37626. return;
  37627. }
  37628. dynamicImportIndex += 1;
  37629. try {
  37630. // see if this is a variable dynamic import, and generate a glob expression
  37631. const glob = dynamicImportToGlob(node.source, code.substring(node.start, node.end));
  37632. if (!glob) {
  37633. // this was not a variable dynamic import
  37634. return;
  37635. }
  37636. // execute the glob
  37637. const result = globby.sync(glob, { cwd: path__default.dirname(id) });
  37638. const paths = result.map((r) =>
  37639. r.startsWith('./') || r.startsWith('../') ? r : `./${r}`
  37640. );
  37641. // create magic string if it wasn't created already
  37642. ms = ms || new MagicString(code);
  37643. // unpack variable dynamic import into a function with import statements per file, rollup
  37644. // will turn these into chunks automatically
  37645. ms.prepend(
  37646. `function __variableDynamicImportRuntime${dynamicImportIndex}__(path) {
  37647. switch (path) {
  37648. ${paths.map((p) => ` case '${p}': return import('${p}');`).join('\n')}
  37649. ${` default: return new Promise(function(resolve, reject) {
  37650. (typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(
  37651. reject.bind(null, new Error("Unknown variable dynamic import: " + path))
  37652. );
  37653. })\n`} }
  37654. }\n\n`
  37655. );
  37656. // call the runtime function instead of doing a dynamic import, the import specifier will
  37657. // be evaluated at runtime and the correct import will be returned by the injected function
  37658. ms.overwrite(
  37659. node.start,
  37660. node.start + 6,
  37661. `__variableDynamicImportRuntime${dynamicImportIndex}__`
  37662. );
  37663. } catch (error) {
  37664. if (error instanceof VariableDynamicImportError) {
  37665. // TODO: line number
  37666. if (warnOnError) {
  37667. this.warn(error);
  37668. } else {
  37669. this.error(error);
  37670. }
  37671. } else {
  37672. this.error(error);
  37673. }
  37674. }
  37675. }
  37676. });
  37677. if (ms && dynamicImportIndex !== -1) {
  37678. return {
  37679. code: ms.toString(),
  37680. map: ms.generateMap({
  37681. file: id,
  37682. includeContent: true,
  37683. hires: true
  37684. })
  37685. };
  37686. }
  37687. return null;
  37688. }
  37689. };
  37690. }
  37691. const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
  37692. const dataUriPrefix = `/@data-uri/`;
  37693. /**
  37694. * Build only, since importing from a data URI works natively.
  37695. */
  37696. function dataURIPlugin() {
  37697. let resolved;
  37698. return {
  37699. name: 'vite:data-uri',
  37700. buildStart() {
  37701. resolved = {};
  37702. },
  37703. resolveId(id) {
  37704. if (!dataUriRE.test(id)) {
  37705. return null;
  37706. }
  37707. const uri = new require$$0$a.URL(id);
  37708. if (uri.protocol !== 'data:') {
  37709. return null;
  37710. }
  37711. const match = uri.pathname.match(dataUriRE);
  37712. if (!match) {
  37713. return null;
  37714. }
  37715. const [, mime, format, data] = match;
  37716. if (mime !== 'text/javascript') {
  37717. throw new Error(`data URI with non-JavaScript mime type is not supported.`);
  37718. }
  37719. // decode data
  37720. const base64 = format && /base64/i.test(format.substring(1));
  37721. const content = base64
  37722. ? Buffer.from(data, 'base64').toString('utf-8')
  37723. : data;
  37724. resolved[id] = content;
  37725. return dataUriPrefix + id;
  37726. },
  37727. load(id) {
  37728. if (id.startsWith(dataUriPrefix)) {
  37729. id = id.slice(dataUriPrefix.length);
  37730. return resolved[id] || null;
  37731. }
  37732. }
  37733. };
  37734. }
  37735. /**
  37736. * @param {object} exports
  37737. * @param {Set<string>} keys
  37738. */
  37739. function loop(exports, keys) {
  37740. if (typeof exports === 'string') {
  37741. return exports;
  37742. }
  37743. if (exports) {
  37744. let idx, tmp;
  37745. if (Array.isArray(exports)) {
  37746. for (idx=0; idx < exports.length; idx++) {
  37747. if (tmp = loop(exports[idx], keys)) return tmp;
  37748. }
  37749. } else {
  37750. for (idx in exports) {
  37751. if (keys.has(idx)) {
  37752. return loop(exports[idx], keys);
  37753. }
  37754. }
  37755. }
  37756. }
  37757. }
  37758. /**
  37759. * @param {string} name The package name
  37760. * @param {string} entry The target entry, eg "."
  37761. * @param {number} [condition] Unmatched condition?
  37762. */
  37763. function bail(name, entry, condition) {
  37764. throw new Error(
  37765. condition
  37766. ? `No known conditions for "${entry}" entry in "${name}" package`
  37767. : `Missing "${entry}" export in "${name}" package`
  37768. );
  37769. }
  37770. /**
  37771. * @param {string} name the package name
  37772. * @param {string} entry the target path/import
  37773. */
  37774. function toName(name, entry) {
  37775. return entry === name ? '.'
  37776. : entry[0] === '.' ? entry
  37777. : entry.replace(new RegExp('^' + name + '\/'), './');
  37778. }
  37779. /**
  37780. * @param {object} pkg package.json contents
  37781. * @param {string} [entry] entry name or import path
  37782. * @param {object} [options]
  37783. * @param {boolean} [options.browser]
  37784. * @param {boolean} [options.require]
  37785. * @param {string[]} [options.conditions]
  37786. */
  37787. function resolve$1(pkg, entry='.', options={}) {
  37788. let { name, exports } = pkg;
  37789. if (exports) {
  37790. let { browser, require, conditions=[] } = options;
  37791. let target = toName(name, entry);
  37792. if (target[0] !== '.') target = './' + target;
  37793. if (typeof exports === 'string') {
  37794. return target === '.' ? exports : bail(name, target);
  37795. }
  37796. let allows = new Set(['default', ...conditions]);
  37797. allows.add(require ? 'require' : 'import');
  37798. allows.add(browser ? 'browser' : 'node');
  37799. let key, tmp, isSingle=false;
  37800. for (key in exports) {
  37801. isSingle = key[0] !== '.';
  37802. break;
  37803. }
  37804. if (isSingle) {
  37805. return target === '.'
  37806. ? loop(exports, allows) || bail(name, target, 1)
  37807. : bail(name, target);
  37808. }
  37809. if (tmp = exports[target]) {
  37810. return loop(tmp, allows) || bail(name, target, 1);
  37811. }
  37812. for (key in exports) {
  37813. tmp = key[key.length - 1];
  37814. if (tmp === '/' && target.startsWith(key)) {
  37815. return (tmp = loop(exports[key], allows))
  37816. ? (tmp + target.substring(key.length))
  37817. : bail(name, target, 1);
  37818. }
  37819. if (tmp === '*' && target.startsWith(key.slice(0, -1))) {
  37820. // do not trigger if no *content* to inject
  37821. if (target.substring(key.length - 1).length > 0) {
  37822. return (tmp = loop(exports[key], allows))
  37823. ? tmp.replace('*', target.substring(key.length - 1))
  37824. : bail(name, target, 1);
  37825. }
  37826. }
  37827. }
  37828. return bail(name, target);
  37829. }
  37830. }
  37831. // special id for paths marked with browser: false
  37832. // https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module
  37833. const browserExternalId = '__vite-browser-external';
  37834. const isDebug$5 = process.env.DEBUG;
  37835. const debug$b = createDebugger('vite:resolve-details', {
  37836. onlyWhenFocused: true
  37837. });
  37838. function resolvePlugin(baseOptions) {
  37839. const { root, isProduction, asSrc, ssrConfig, preferRelative = false } = baseOptions;
  37840. const requireOptions = {
  37841. ...baseOptions,
  37842. isRequire: true
  37843. };
  37844. let server;
  37845. const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig !== null && ssrConfig !== void 0 ? ssrConfig : {};
  37846. return {
  37847. name: 'vite:resolve',
  37848. configureServer(_server) {
  37849. server = _server;
  37850. },
  37851. resolveId(id, importer, resolveOpts, ssr) {
  37852. if (id.startsWith(browserExternalId)) {
  37853. return id;
  37854. }
  37855. // fast path for commonjs proxy modules
  37856. if (/\?commonjs/.test(id) || id === 'commonjsHelpers.js') {
  37857. return;
  37858. }
  37859. const targetWeb = !ssr || ssrTarget === 'webworker';
  37860. // this is passed by @rollup/plugin-commonjs
  37861. const isRequire = resolveOpts &&
  37862. resolveOpts.custom &&
  37863. resolveOpts.custom['node-resolve'] &&
  37864. resolveOpts.custom['node-resolve'].isRequire;
  37865. const options = isRequire ? requireOptions : baseOptions;
  37866. let res;
  37867. // explicit fs paths that starts with /@fs/*
  37868. if (asSrc && id.startsWith(FS_PREFIX)) {
  37869. const fsPath = fsPathFromId(id);
  37870. res = tryFsResolve(fsPath, options);
  37871. isDebug$5 && debug$b(`[@fs] ${source.cyan(id)} -> ${source.dim(res)}`);
  37872. // always return here even if res doesn't exist since /@fs/ is explicit
  37873. // if the file doesn't exist it should be a 404
  37874. return res || fsPath;
  37875. }
  37876. // URL
  37877. // /foo -> /fs-root/foo
  37878. if (asSrc && id.startsWith('/')) {
  37879. const fsPath = path__default.resolve(root, id.slice(1));
  37880. if ((res = tryFsResolve(fsPath, options))) {
  37881. isDebug$5 && debug$b(`[url] ${source.cyan(id)} -> ${source.dim(res)}`);
  37882. return res;
  37883. }
  37884. }
  37885. // relative
  37886. if (id.startsWith('.') || (preferRelative && /^\w/.test(id))) {
  37887. const basedir = importer ? path__default.dirname(importer) : process.cwd();
  37888. const fsPath = path__default.resolve(basedir, id);
  37889. // handle browser field mapping for relative imports
  37890. const normalizedFsPath = normalizePath$4(fsPath);
  37891. const pathFromBasedir = normalizedFsPath.slice(basedir.length);
  37892. if (pathFromBasedir.startsWith('/node_modules/')) {
  37893. // normalize direct imports from node_modules to bare imports, so the
  37894. // hashing logic is shared and we avoid duplicated modules #2503
  37895. const bareImport = pathFromBasedir.slice('/node_modules/'.length);
  37896. if ((res = tryNodeResolve(bareImport, importer, options, targetWeb, server, ssr)) &&
  37897. res.id.startsWith(normalizedFsPath)) {
  37898. return res;
  37899. }
  37900. }
  37901. if (targetWeb &&
  37902. (res = tryResolveBrowserMapping(fsPath, importer, options, true))) {
  37903. return res;
  37904. }
  37905. if ((res = tryFsResolve(fsPath, options))) {
  37906. isDebug$5 && debug$b(`[relative] ${source.cyan(id)} -> ${source.dim(res)}`);
  37907. const pkg = importer != null && idToPkgMap.get(importer);
  37908. if (pkg) {
  37909. idToPkgMap.set(res, pkg);
  37910. return {
  37911. id: res,
  37912. moduleSideEffects: pkg.hasSideEffects(res)
  37913. };
  37914. }
  37915. return res;
  37916. }
  37917. }
  37918. // absolute fs paths
  37919. if (path__default.isAbsolute(id) && (res = tryFsResolve(id, options))) {
  37920. isDebug$5 && debug$b(`[fs] ${source.cyan(id)} -> ${source.dim(res)}`);
  37921. return res;
  37922. }
  37923. // external
  37924. if (isExternalUrl(id)) {
  37925. return {
  37926. id,
  37927. external: true
  37928. };
  37929. }
  37930. // data uri: pass through (this only happens during build and will be
  37931. // handled by dedicated plugin)
  37932. if (isDataUrl(id)) {
  37933. return null;
  37934. }
  37935. // bare package imports, perform node resolve
  37936. if (bareImportRE.test(id)) {
  37937. if (asSrc &&
  37938. server &&
  37939. !ssr &&
  37940. (res = tryOptimizedResolve(id, server, importer))) {
  37941. return res;
  37942. }
  37943. if (targetWeb &&
  37944. (res = tryResolveBrowserMapping(id, importer, options, false))) {
  37945. return res;
  37946. }
  37947. if ((res = tryNodeResolve(id, importer, options, targetWeb, server, ssr))) {
  37948. return res;
  37949. }
  37950. // node built-ins.
  37951. // externalize if building for SSR, otherwise redirect to empty module
  37952. if (isBuiltin(id)) {
  37953. if (ssr) {
  37954. if (ssrNoExternal === true) {
  37955. let message = `Cannot bundle Node.js built-in "${id}"`;
  37956. if (importer) {
  37957. message += ` imported from "${path__default.relative(process.cwd(), importer)}"`;
  37958. }
  37959. message += `. Consider disabling ssr.noExternal or remove the built-in dependency.`;
  37960. this.error(message);
  37961. }
  37962. return {
  37963. id,
  37964. external: true
  37965. };
  37966. }
  37967. else {
  37968. if (!asSrc) {
  37969. debug$b(`externalized node built-in "${id}" to empty module. ` +
  37970. `(imported by: ${source.white.dim(importer)})`);
  37971. }
  37972. return isProduction
  37973. ? browserExternalId
  37974. : `${browserExternalId}:${id}`;
  37975. }
  37976. }
  37977. }
  37978. isDebug$5 && debug$b(`[fallthrough] ${source.dim(id)}`);
  37979. },
  37980. load(id) {
  37981. if (id.startsWith(browserExternalId)) {
  37982. return isProduction
  37983. ? `export default {}`
  37984. : `export default new Proxy({}, {
  37985. get() {
  37986. throw new Error('Module "${id.slice(browserExternalId.length + 1)}" has been externalized for browser compatibility and cannot be accessed in client code.')
  37987. }
  37988. })`;
  37989. }
  37990. }
  37991. };
  37992. }
  37993. function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true) {
  37994. let file = fsPath;
  37995. let postfix = '';
  37996. let postfixIndex = fsPath.indexOf('?');
  37997. if (postfixIndex < 0) {
  37998. postfixIndex = fsPath.indexOf('#');
  37999. }
  38000. if (postfixIndex > 0) {
  38001. file = fsPath.slice(0, postfixIndex);
  38002. postfix = fsPath.slice(postfixIndex);
  38003. }
  38004. let res;
  38005. if ((res = tryResolveFile(file, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  38006. return res;
  38007. }
  38008. for (const ext of options.extensions || DEFAULT_EXTENSIONS) {
  38009. if ((res = tryResolveFile(file + ext, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  38010. return res;
  38011. }
  38012. }
  38013. if ((res = tryResolveFile(file, postfix, options, tryIndex, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  38014. return res;
  38015. }
  38016. }
  38017. function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix, skipPackageJson) {
  38018. let isReadable = false;
  38019. try {
  38020. // #2051 if we don't have read permission on a directory, existsSync() still
  38021. // works and will result in massively slow subsequent checks (which are
  38022. // unnecessary in the first place)
  38023. fs__default.accessSync(file, fs__default.constants.R_OK);
  38024. isReadable = true;
  38025. }
  38026. catch (e) { }
  38027. if (isReadable) {
  38028. if (!fs__default.statSync(file).isDirectory()) {
  38029. return normalizePath$4(ensureVolumeInPath(file)) + postfix;
  38030. }
  38031. else if (tryIndex) {
  38032. if (!skipPackageJson) {
  38033. const pkgPath = file + '/package.json';
  38034. if (fs__default.existsSync(pkgPath)) {
  38035. // path points to a node package
  38036. const pkg = loadPackageData(pkgPath);
  38037. return resolvePackageEntry(file, pkg, options, targetWeb);
  38038. }
  38039. }
  38040. const index = tryFsResolve(file + '/index', options);
  38041. if (index)
  38042. return index + postfix;
  38043. }
  38044. }
  38045. if (tryPrefix) {
  38046. const prefixed = `${path__default.dirname(file)}/${tryPrefix}${path__default.basename(file)}`;
  38047. return tryResolveFile(prefixed, postfix, options, tryIndex, targetWeb);
  38048. }
  38049. }
  38050. const idToPkgMap = new Map();
  38051. function tryNodeResolve(id, importer, options, targetWeb, server, ssr) {
  38052. var _a, _b, _c;
  38053. const { root, dedupe, isBuild } = options;
  38054. // split id by last '>' for nested selected packages, for example:
  38055. // 'foo > bar > baz' => 'foo > bar' & 'baz'
  38056. // 'foo' => '' & 'foo'
  38057. const lastArrowIndex = id.lastIndexOf('>');
  38058. const nestedRoot = id.substring(0, lastArrowIndex).trim();
  38059. const nestedPath = id.substring(lastArrowIndex + 1).trim();
  38060. // check for deep import, e.g. "my-lib/foo"
  38061. const deepMatch = nestedPath.match(deepImportRE);
  38062. const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : nestedPath;
  38063. let basedir;
  38064. if (dedupe && dedupe.includes(pkgId)) {
  38065. basedir = root;
  38066. }
  38067. else if (importer &&
  38068. path__default.isAbsolute(importer) &&
  38069. fs__default.existsSync(cleanUrl(importer))) {
  38070. basedir = path__default.dirname(importer);
  38071. }
  38072. else {
  38073. basedir = root;
  38074. }
  38075. // nested node module, step-by-step resolve to the basedir of the nestedPath
  38076. if (nestedRoot) {
  38077. basedir = nestedResolveFrom(nestedRoot, basedir);
  38078. }
  38079. const pkg = resolvePackageData(pkgId, basedir);
  38080. if (!pkg) {
  38081. return;
  38082. }
  38083. let resolved = deepMatch
  38084. ? resolveDeepImport(id, pkg, options, targetWeb)
  38085. : resolvePackageEntry(id, pkg, options, targetWeb);
  38086. if (!resolved) {
  38087. return;
  38088. }
  38089. // link id to pkg for browser field mapping check
  38090. idToPkgMap.set(resolved, pkg);
  38091. if (isBuild) {
  38092. // Resolve package side effects for build so that rollup can better
  38093. // perform tree-shaking
  38094. return {
  38095. id: resolved,
  38096. moduleSideEffects: pkg.hasSideEffects(resolved)
  38097. };
  38098. }
  38099. else {
  38100. if (!resolved.includes('node_modules') || // linked
  38101. !server || // build
  38102. server._isRunningOptimizer || // optimizing
  38103. !server._optimizeDepsMetadata) {
  38104. return { id: resolved };
  38105. }
  38106. // if we reach here, it's a valid dep import that hasn't been optimized.
  38107. const isJsType = OPTIMIZABLE_ENTRY_RE.test(resolved);
  38108. const exclude = (_a = server.config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude;
  38109. if (!isJsType ||
  38110. (importer === null || importer === void 0 ? void 0 : importer.includes('node_modules')) ||
  38111. (exclude === null || exclude === void 0 ? void 0 : exclude.includes(pkgId)) ||
  38112. (exclude === null || exclude === void 0 ? void 0 : exclude.includes(id)) ||
  38113. SPECIAL_QUERY_RE.test(resolved)) {
  38114. // excluded from optimization
  38115. // Inject a version query to npm deps so that the browser
  38116. // can cache it without re-validation, but only do so for known js types.
  38117. // otherwise we may introduce duplicated modules for externalized files
  38118. // from pre-bundled deps.
  38119. const versionHash = (_b = server._optimizeDepsMetadata) === null || _b === void 0 ? void 0 : _b.browserHash;
  38120. if (versionHash && isJsType) {
  38121. resolved = injectQuery(resolved, `v=${versionHash}`);
  38122. }
  38123. }
  38124. else {
  38125. // this is a missing import.
  38126. // queue optimize-deps re-run.
  38127. (_c = server._registerMissingImport) === null || _c === void 0 ? void 0 : _c.call(server, id, resolved, ssr);
  38128. }
  38129. return { id: resolved };
  38130. }
  38131. }
  38132. function tryOptimizedResolve(id, server, importer) {
  38133. const cacheDir = server.config.cacheDir;
  38134. const depData = server._optimizeDepsMetadata;
  38135. if (!cacheDir || !depData)
  38136. return;
  38137. const getOptimizedUrl = (optimizedData) => {
  38138. return (optimizedData.file +
  38139. `?v=${depData.browserHash}${optimizedData.needsInterop ? `&es-interop` : ``}`);
  38140. };
  38141. // check if id has been optimized
  38142. const isOptimized = depData.optimized[id];
  38143. if (isOptimized) {
  38144. return getOptimizedUrl(isOptimized);
  38145. }
  38146. if (!importer)
  38147. return;
  38148. // further check if id is imported by nested dependency
  38149. let resolvedSrc;
  38150. for (const [pkgPath, optimizedData] of Object.entries(depData.optimized)) {
  38151. // check for scenarios, e.g.
  38152. // pkgPath => "my-lib > foo"
  38153. // id => "foo"
  38154. // this narrows the need to do a full resolve
  38155. if (!pkgPath.endsWith(id))
  38156. continue;
  38157. // lazily initialize resolvedSrc
  38158. if (resolvedSrc == null) {
  38159. try {
  38160. // this may throw errors if unable to resolve, e.g. aliased id
  38161. resolvedSrc = normalizePath$4(resolveFrom$3(id, path__default.dirname(importer)));
  38162. }
  38163. catch {
  38164. // this is best-effort only so swallow errors
  38165. break;
  38166. }
  38167. }
  38168. // match by src to correctly identify if id belongs to nested dependency
  38169. if (optimizedData.src === resolvedSrc) {
  38170. return getOptimizedUrl(optimizedData);
  38171. }
  38172. }
  38173. }
  38174. const packageCache = new Map();
  38175. function resolvePackageData(id, basedir) {
  38176. const cacheKey = id + basedir;
  38177. if (packageCache.has(cacheKey)) {
  38178. return packageCache.get(cacheKey);
  38179. }
  38180. try {
  38181. const pkgPath = resolveFrom$3(`${id}/package.json`, basedir);
  38182. return loadPackageData(pkgPath, cacheKey);
  38183. }
  38184. catch (e) {
  38185. isDebug$5 && debug$b(`${source.red(`[failed loading package.json]`)} ${id}`);
  38186. }
  38187. }
  38188. function loadPackageData(pkgPath, cacheKey = pkgPath) {
  38189. const data = JSON.parse(fs__default.readFileSync(pkgPath, 'utf-8'));
  38190. const pkgDir = path__default.dirname(pkgPath);
  38191. const { sideEffects } = data;
  38192. let hasSideEffects;
  38193. if (typeof sideEffects === 'boolean') {
  38194. hasSideEffects = () => sideEffects;
  38195. }
  38196. else if (Array.isArray(sideEffects)) {
  38197. hasSideEffects = createFilter$1(sideEffects, null, { resolve: pkgDir });
  38198. }
  38199. else {
  38200. hasSideEffects = () => true;
  38201. }
  38202. const pkg = {
  38203. dir: pkgDir,
  38204. data,
  38205. hasSideEffects,
  38206. webResolvedImports: {},
  38207. nodeResolvedImports: {},
  38208. setResolvedCache(key, entry, targetWeb) {
  38209. if (targetWeb) {
  38210. pkg.webResolvedImports[key] = entry;
  38211. }
  38212. else {
  38213. pkg.nodeResolvedImports[key] = entry;
  38214. }
  38215. },
  38216. getResolvedCache(key, targetWeb) {
  38217. if (targetWeb) {
  38218. return pkg.webResolvedImports[key];
  38219. }
  38220. else {
  38221. return pkg.nodeResolvedImports[key];
  38222. }
  38223. }
  38224. };
  38225. packageCache.set(cacheKey, pkg);
  38226. return pkg;
  38227. }
  38228. function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options, targetWeb) {
  38229. var _a, _b;
  38230. const cached = getResolvedCache('.', targetWeb);
  38231. if (cached) {
  38232. return cached;
  38233. }
  38234. try {
  38235. let entryPoint;
  38236. // resolve exports field with highest priority
  38237. // using https://github.com/lukeed/resolve.exports
  38238. if (data.exports) {
  38239. entryPoint = resolveExports(data, '.', options, targetWeb);
  38240. }
  38241. // if exports resolved to .mjs, still resolve other fields.
  38242. // This is because .mjs files can technically import .cjs files which would
  38243. // make them invalid for pure ESM environments - so if other module/browser
  38244. // fields are present, prioritize those instead.
  38245. if (targetWeb && (!entryPoint || entryPoint.endsWith('.mjs'))) {
  38246. // check browser field
  38247. // https://github.com/defunctzombie/package-browser-field-spec
  38248. const browserEntry = typeof data.browser === 'string'
  38249. ? data.browser
  38250. : isObject$3(data.browser) && data.browser['.'];
  38251. if (browserEntry) {
  38252. // check if the package also has a "module" field.
  38253. if (typeof data.module === 'string' && data.module !== browserEntry) {
  38254. // if both are present, we may have a problem: some package points both
  38255. // to ESM, with "module" targeting Node.js, while some packages points
  38256. // "module" to browser ESM and "browser" to UMD.
  38257. // the heuristics here is to actually read the browser entry when
  38258. // possible and check for hints of UMD. If it is UMD, prefer "module"
  38259. // instead; Otherwise, assume it's ESM and use it.
  38260. const resolvedBrowserEntry = tryFsResolve(path__default.join(dir, browserEntry), options);
  38261. if (resolvedBrowserEntry) {
  38262. const content = fs__default.readFileSync(resolvedBrowserEntry, 'utf-8');
  38263. if ((/typeof exports\s*==/.test(content) &&
  38264. /typeof module\s*==/.test(content)) ||
  38265. /module\.exports\s*=/.test(content)) {
  38266. // likely UMD or CJS(!!! e.g. firebase 7.x), prefer module
  38267. entryPoint = data.module;
  38268. }
  38269. }
  38270. }
  38271. else {
  38272. entryPoint = browserEntry;
  38273. }
  38274. }
  38275. }
  38276. if (!entryPoint || entryPoint.endsWith('.mjs')) {
  38277. for (const field of options.mainFields || DEFAULT_MAIN_FIELDS) {
  38278. if (typeof data[field] === 'string') {
  38279. entryPoint = data[field];
  38280. break;
  38281. }
  38282. }
  38283. }
  38284. entryPoint = entryPoint || data.main || 'index.js';
  38285. // make sure we don't get scripts when looking for sass
  38286. if (((_a = options.mainFields) === null || _a === void 0 ? void 0 : _a[0]) === 'sass' &&
  38287. !((_b = options.extensions) === null || _b === void 0 ? void 0 : _b.includes(path__default.extname(entryPoint)))) {
  38288. entryPoint = '';
  38289. options.skipPackageJson = true;
  38290. }
  38291. // resolve object browser field in package.json
  38292. const { browser: browserField } = data;
  38293. if (targetWeb && isObject$3(browserField)) {
  38294. entryPoint = mapWithBrowserField(entryPoint, browserField) || entryPoint;
  38295. }
  38296. entryPoint = path__default.join(dir, entryPoint);
  38297. const resolvedEntryPoint = tryFsResolve(entryPoint, options);
  38298. if (resolvedEntryPoint) {
  38299. isDebug$5 &&
  38300. debug$b(`[package entry] ${source.cyan(id)} -> ${source.dim(resolvedEntryPoint)}`);
  38301. setResolvedCache('.', resolvedEntryPoint, targetWeb);
  38302. return resolvedEntryPoint;
  38303. }
  38304. else {
  38305. packageEntryFailure(id);
  38306. }
  38307. }
  38308. catch (e) {
  38309. packageEntryFailure(id, e.message);
  38310. }
  38311. }
  38312. function packageEntryFailure(id, details) {
  38313. throw new Error(`Failed to resolve entry for package "${id}". ` +
  38314. `The package may have incorrect main/module/exports specified in its package.json` +
  38315. (details ? ': ' + details : '.'));
  38316. }
  38317. function resolveExports(pkg, key, options, targetWeb) {
  38318. const conditions = [options.isProduction ? 'production' : 'development'];
  38319. if (!options.isRequire) {
  38320. conditions.push('module');
  38321. }
  38322. if (options.conditions) {
  38323. conditions.push(...options.conditions);
  38324. }
  38325. return resolve$1(pkg, key, {
  38326. browser: targetWeb,
  38327. require: options.isRequire,
  38328. conditions
  38329. });
  38330. }
  38331. function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolvedCache, dir, data }, options, targetWeb) {
  38332. id = '.' + id.slice(data.name.length);
  38333. const cache = getResolvedCache(id, targetWeb);
  38334. if (cache) {
  38335. return cache;
  38336. }
  38337. let relativeId = id;
  38338. const { exports: exportsField, browser: browserField } = data;
  38339. // map relative based on exports data
  38340. if (exportsField) {
  38341. if (isObject$3(exportsField) && !Array.isArray(exportsField)) {
  38342. relativeId = resolveExports(data, relativeId, options, targetWeb);
  38343. }
  38344. else {
  38345. // not exposed
  38346. relativeId = undefined;
  38347. }
  38348. if (!relativeId) {
  38349. throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ` +
  38350. `${path__default.join(dir, 'package.json')}.`);
  38351. }
  38352. }
  38353. else if (targetWeb && isObject$3(browserField)) {
  38354. const mapped = mapWithBrowserField(relativeId, browserField);
  38355. if (mapped) {
  38356. relativeId = mapped;
  38357. }
  38358. else if (mapped === false) {
  38359. return (webResolvedImports[id] = browserExternalId);
  38360. }
  38361. }
  38362. if (relativeId) {
  38363. const resolved = tryFsResolve(path__default.join(dir, relativeId), options, !exportsField, // try index only if no exports field
  38364. targetWeb);
  38365. if (resolved) {
  38366. isDebug$5 &&
  38367. debug$b(`[node/deep-import] ${source.cyan(id)} -> ${source.dim(resolved)}`);
  38368. setResolvedCache(id, resolved, targetWeb);
  38369. return resolved;
  38370. }
  38371. }
  38372. }
  38373. function tryResolveBrowserMapping(id, importer, options, isFilePath) {
  38374. let res;
  38375. const pkg = importer && idToPkgMap.get(importer);
  38376. if (pkg && isObject$3(pkg.data.browser)) {
  38377. const mapId = isFilePath ? './' + slash$3(path__default.relative(pkg.dir, id)) : id;
  38378. const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
  38379. if (browserMappedPath) {
  38380. const fsPath = path__default.join(pkg.dir, browserMappedPath);
  38381. if ((res = tryFsResolve(fsPath, options))) {
  38382. isDebug$5 &&
  38383. debug$b(`[browser mapped] ${source.cyan(id)} -> ${source.dim(res)}`);
  38384. idToPkgMap.set(res, pkg);
  38385. return {
  38386. id: res,
  38387. moduleSideEffects: pkg.hasSideEffects(res)
  38388. };
  38389. }
  38390. }
  38391. else if (browserMappedPath === false) {
  38392. return browserExternalId;
  38393. }
  38394. }
  38395. }
  38396. /**
  38397. * given a relative path in pkg dir,
  38398. * return a relative path in pkg dir,
  38399. * mapped with the "map" object
  38400. *
  38401. * - Returning `undefined` means there is no browser mapping for this id
  38402. * - Returning `false` means this id is explicitly externalized for browser
  38403. */
  38404. function mapWithBrowserField(relativePathInPkgDir, map) {
  38405. const normalizedPath = path__default.posix.normalize(relativePathInPkgDir);
  38406. for (const key in map) {
  38407. const normalizedKey = path__default.posix.normalize(key);
  38408. if (normalizedPath === normalizedKey ||
  38409. equalWithoutSuffix(normalizedPath, normalizedKey, '.js') ||
  38410. equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')) {
  38411. return map[key];
  38412. }
  38413. }
  38414. }
  38415. function equalWithoutSuffix(path, key, suffix) {
  38416. return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
  38417. }
  38418. /**
  38419. * Heuristics for determining whether a dependency should be externalized for
  38420. * server-side rendering.
  38421. *
  38422. * TODO right now externals are imported using require(), we probably need to
  38423. * rework this when more libraries ship native ESM distributions for Node.
  38424. */
  38425. function resolveSSRExternal(config, knownImports, ssrExternals = new Set(), seen = new Set()) {
  38426. var _a, _b, _c, _d;
  38427. if (((_a = config.ssr) === null || _a === void 0 ? void 0 : _a.noExternal) === true) {
  38428. return [];
  38429. }
  38430. const { root } = config;
  38431. const pkgContent = lookupFile(root, ['package.json']);
  38432. if (!pkgContent) {
  38433. return [];
  38434. }
  38435. const pkg = JSON.parse(pkgContent);
  38436. const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined);
  38437. const deps = unique([
  38438. ...importedDeps,
  38439. ...Object.keys(pkg.devDependencies || {}),
  38440. ...Object.keys(pkg.dependencies || {})
  38441. ]);
  38442. const resolveOptions = {
  38443. root,
  38444. isProduction: false,
  38445. isBuild: true
  38446. };
  38447. const depsToTrace = new Set();
  38448. for (const id of deps) {
  38449. if (seen.has(id)) {
  38450. continue;
  38451. }
  38452. seen.add(id);
  38453. let entry;
  38454. let requireEntry;
  38455. try {
  38456. entry = (_b = tryNodeResolve(id, undefined, resolveOptions, true, undefined, true)) === null || _b === void 0 ? void 0 : _b.id;
  38457. requireEntry = require.resolve(id, { paths: [root] });
  38458. }
  38459. catch (e) {
  38460. // resolve failed, assume include
  38461. continue;
  38462. }
  38463. if (!entry) {
  38464. // no esm entry but has require entry (is this even possible?)
  38465. ssrExternals.add(id);
  38466. continue;
  38467. }
  38468. if (!entry.includes('node_modules')) {
  38469. // entry is not a node dep, possibly linked - don't externalize
  38470. // instead, trace its dependencies.
  38471. depsToTrace.add(id);
  38472. continue;
  38473. }
  38474. if (entry !== requireEntry) {
  38475. // has separate esm/require entry, assume require entry is cjs
  38476. ssrExternals.add(id);
  38477. }
  38478. else {
  38479. // node resolve and esm resolve resolves to the same file.
  38480. if (!/\.m?js$/.test(entry)) {
  38481. // entry is not js, cannot externalize
  38482. continue;
  38483. }
  38484. // check if the entry is cjs
  38485. const content = fs__default.readFileSync(entry, 'utf-8');
  38486. if (/\bmodule\.exports\b|\bexports[.\[]|\brequire\s*\(/.test(content)) {
  38487. ssrExternals.add(id);
  38488. }
  38489. }
  38490. }
  38491. for (const id of depsToTrace) {
  38492. const depRoot = path__default.dirname(resolveFrom$3(`${id}/package.json`, root));
  38493. resolveSSRExternal({
  38494. ...config,
  38495. root: depRoot
  38496. }, knownImports, ssrExternals, seen);
  38497. }
  38498. if ((_c = config.ssr) === null || _c === void 0 ? void 0 : _c.external) {
  38499. config.ssr.external.forEach((id) => ssrExternals.add(id));
  38500. }
  38501. let externals = [...ssrExternals];
  38502. if ((_d = config.ssr) === null || _d === void 0 ? void 0 : _d.noExternal) {
  38503. const filter = createFilter$1(undefined, config.ssr.noExternal, {
  38504. resolve: false
  38505. });
  38506. externals = externals.filter((id) => filter(id));
  38507. }
  38508. return externals.filter((id) => id !== 'vite');
  38509. }
  38510. function shouldExternalizeForSSR(id, externals) {
  38511. const should = externals.some((e) => {
  38512. if (id === e) {
  38513. return true;
  38514. }
  38515. // deep imports, check ext before externalizing - only externalize
  38516. // extension-less imports and explicit .js imports
  38517. if (id.startsWith(e + '/') && (!path__default.extname(id) || id.endsWith('.js'))) {
  38518. return true;
  38519. }
  38520. });
  38521. return should;
  38522. }
  38523. function getNpmPackageName(importPath) {
  38524. const parts = importPath.split('/');
  38525. if (parts[0].startsWith('@')) {
  38526. if (!parts[1])
  38527. return null;
  38528. return `${parts[0]}/${parts[1]}`;
  38529. }
  38530. else {
  38531. return parts[0];
  38532. }
  38533. }
  38534. function ssrManifestPlugin(config) {
  38535. // module id => preload assets mapping
  38536. const ssrManifest = {};
  38537. const base = config.base;
  38538. return {
  38539. name: 'vite:manifest',
  38540. generateBundle(_options, bundle) {
  38541. for (const file in bundle) {
  38542. const chunk = bundle[file];
  38543. if (chunk.type === 'chunk') {
  38544. // links for certain entry chunks are already generated in static HTML
  38545. // in those cases we only need to record info for non-entry chunks
  38546. const cssFiles = chunk.isEntry
  38547. ? null
  38548. : chunkToEmittedCssFileMap.get(chunk);
  38549. const assetFiles = chunkToEmittedAssetsMap.get(chunk);
  38550. for (const id in chunk.modules) {
  38551. const normalizedId = normalizePath$3(path$w.relative(config.root, id));
  38552. const mappedChunks = ssrManifest[normalizedId] || (ssrManifest[normalizedId] = []);
  38553. if (!chunk.isEntry) {
  38554. mappedChunks.push(base + chunk.fileName);
  38555. }
  38556. if (cssFiles) {
  38557. cssFiles.forEach((file) => {
  38558. mappedChunks.push(base + file);
  38559. });
  38560. }
  38561. if (assetFiles) {
  38562. assetFiles.forEach((file) => {
  38563. mappedChunks.push(base + file);
  38564. });
  38565. }
  38566. }
  38567. }
  38568. }
  38569. this.emitFile({
  38570. fileName: 'ssr-manifest.json',
  38571. type: 'asset',
  38572. source: JSON.stringify(ssrManifest, null, 2)
  38573. });
  38574. }
  38575. };
  38576. }
  38577. // Reserved word lists for various dialects of the language
  38578. var reservedWords = {
  38579. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  38580. 5: "class enum extends super const export import",
  38581. 6: "enum",
  38582. strict: "implements interface let package private protected public static yield",
  38583. strictBind: "eval arguments"
  38584. };
  38585. // And the keywords
  38586. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  38587. var keywords = {
  38588. 5: ecma5AndLessKeywords,
  38589. "5module": ecma5AndLessKeywords + " export import",
  38590. 6: ecma5AndLessKeywords + " const class extends export import super"
  38591. };
  38592. var keywordRelationalOperator = /^in(stanceof)?$/;
  38593. // ## Character categories
  38594. // Big ugly regular expressions that match characters in the
  38595. // whitespace, identifier, and identifier-start categories. These
  38596. // are only applied when a character is found to actually have a
  38597. // code point above 128.
  38598. // Generated by `bin/generate-identifier-regex.js`.
  38599. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  38600. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  38601. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  38602. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  38603. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  38604. // These are a run-length and offset encoded representation of the
  38605. // >0xffff code points that are a valid part of identifiers. The
  38606. // offset starts at 0x10000, and each pair of numbers represents an
  38607. // offset to the next range, and then a size of the range. They were
  38608. // generated by bin/generate-identifier-regex.js
  38609. // eslint-disable-next-line comma-spacing
  38610. var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
  38611. // eslint-disable-next-line comma-spacing
  38612. var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];
  38613. // This has a complexity linear to the value of the code. The
  38614. // assumption is that looking up astral identifier characters is
  38615. // rare.
  38616. function isInAstralSet(code, set) {
  38617. var pos = 0x10000;
  38618. for (var i = 0; i < set.length; i += 2) {
  38619. pos += set[i];
  38620. if (pos > code) { return false }
  38621. pos += set[i + 1];
  38622. if (pos >= code) { return true }
  38623. }
  38624. }
  38625. // Test whether a given character code starts an identifier.
  38626. function isIdentifierStart(code, astral) {
  38627. if (code < 65) { return code === 36 }
  38628. if (code < 91) { return true }
  38629. if (code < 97) { return code === 95 }
  38630. if (code < 123) { return true }
  38631. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  38632. if (astral === false) { return false }
  38633. return isInAstralSet(code, astralIdentifierStartCodes)
  38634. }
  38635. // Test whether a given character is part of an identifier.
  38636. function isIdentifierChar(code, astral) {
  38637. if (code < 48) { return code === 36 }
  38638. if (code < 58) { return true }
  38639. if (code < 65) { return false }
  38640. if (code < 91) { return true }
  38641. if (code < 97) { return code === 95 }
  38642. if (code < 123) { return true }
  38643. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  38644. if (astral === false) { return false }
  38645. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  38646. }
  38647. // ## Token types
  38648. // The assignment of fine-grained, information-carrying type objects
  38649. // allows the tokenizer to store the information it has about a
  38650. // token in a way that is very cheap for the parser to look up.
  38651. // All token type variables start with an underscore, to make them
  38652. // easy to recognize.
  38653. // The `beforeExpr` property is used to disambiguate between regular
  38654. // expressions and divisions. It is set on all token types that can
  38655. // be followed by an expression (thus, a slash after them would be a
  38656. // regular expression).
  38657. //
  38658. // The `startsExpr` property is used to check if the token ends a
  38659. // `yield` expression. It is set on all token types that either can
  38660. // directly start an expression (like a quotation mark) or can
  38661. // continue an expression (like the body of a string).
  38662. //
  38663. // `isLoop` marks a keyword as starting a loop, which is important
  38664. // to know when parsing a label, in order to allow or disallow
  38665. // continue jumps to that label.
  38666. var TokenType = function TokenType(label, conf) {
  38667. if ( conf === void 0 ) conf = {};
  38668. this.label = label;
  38669. this.keyword = conf.keyword;
  38670. this.beforeExpr = !!conf.beforeExpr;
  38671. this.startsExpr = !!conf.startsExpr;
  38672. this.isLoop = !!conf.isLoop;
  38673. this.isAssign = !!conf.isAssign;
  38674. this.prefix = !!conf.prefix;
  38675. this.postfix = !!conf.postfix;
  38676. this.binop = conf.binop || null;
  38677. this.updateContext = null;
  38678. };
  38679. function binop(name, prec) {
  38680. return new TokenType(name, {beforeExpr: true, binop: prec})
  38681. }
  38682. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  38683. // Map keyword names to token types.
  38684. var keywords$1 = {};
  38685. // Succinct definitions of keyword token types
  38686. function kw(name, options) {
  38687. if ( options === void 0 ) options = {};
  38688. options.keyword = name;
  38689. return keywords$1[name] = new TokenType(name, options)
  38690. }
  38691. var types = {
  38692. num: new TokenType("num", startsExpr),
  38693. regexp: new TokenType("regexp", startsExpr),
  38694. string: new TokenType("string", startsExpr),
  38695. name: new TokenType("name", startsExpr),
  38696. privateId: new TokenType("privateId", startsExpr),
  38697. eof: new TokenType("eof"),
  38698. // Punctuation token types.
  38699. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  38700. bracketR: new TokenType("]"),
  38701. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  38702. braceR: new TokenType("}"),
  38703. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  38704. parenR: new TokenType(")"),
  38705. comma: new TokenType(",", beforeExpr),
  38706. semi: new TokenType(";", beforeExpr),
  38707. colon: new TokenType(":", beforeExpr),
  38708. dot: new TokenType("."),
  38709. question: new TokenType("?", beforeExpr),
  38710. questionDot: new TokenType("?."),
  38711. arrow: new TokenType("=>", beforeExpr),
  38712. template: new TokenType("template"),
  38713. invalidTemplate: new TokenType("invalidTemplate"),
  38714. ellipsis: new TokenType("...", beforeExpr),
  38715. backQuote: new TokenType("`", startsExpr),
  38716. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  38717. // Operators. These carry several kinds of properties to help the
  38718. // parser use them properly (the presence of these properties is
  38719. // what categorizes them as operators).
  38720. //
  38721. // `binop`, when present, specifies that this operator is a binary
  38722. // operator, and will refer to its precedence.
  38723. //
  38724. // `prefix` and `postfix` mark the operator as a prefix or postfix
  38725. // unary operator.
  38726. //
  38727. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  38728. // binary operators with a very low precedence, that should result
  38729. // in AssignmentExpression nodes.
  38730. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  38731. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  38732. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  38733. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  38734. logicalOR: binop("||", 1),
  38735. logicalAND: binop("&&", 2),
  38736. bitwiseOR: binop("|", 3),
  38737. bitwiseXOR: binop("^", 4),
  38738. bitwiseAND: binop("&", 5),
  38739. equality: binop("==/!=/===/!==", 6),
  38740. relational: binop("</>/<=/>=", 7),
  38741. bitShift: binop("<</>>/>>>", 8),
  38742. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  38743. modulo: binop("%", 10),
  38744. star: binop("*", 10),
  38745. slash: binop("/", 10),
  38746. starstar: new TokenType("**", {beforeExpr: true}),
  38747. coalesce: binop("??", 1),
  38748. // Keyword token types.
  38749. _break: kw("break"),
  38750. _case: kw("case", beforeExpr),
  38751. _catch: kw("catch"),
  38752. _continue: kw("continue"),
  38753. _debugger: kw("debugger"),
  38754. _default: kw("default", beforeExpr),
  38755. _do: kw("do", {isLoop: true, beforeExpr: true}),
  38756. _else: kw("else", beforeExpr),
  38757. _finally: kw("finally"),
  38758. _for: kw("for", {isLoop: true}),
  38759. _function: kw("function", startsExpr),
  38760. _if: kw("if"),
  38761. _return: kw("return", beforeExpr),
  38762. _switch: kw("switch"),
  38763. _throw: kw("throw", beforeExpr),
  38764. _try: kw("try"),
  38765. _var: kw("var"),
  38766. _const: kw("const"),
  38767. _while: kw("while", {isLoop: true}),
  38768. _with: kw("with"),
  38769. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  38770. _this: kw("this", startsExpr),
  38771. _super: kw("super", startsExpr),
  38772. _class: kw("class", startsExpr),
  38773. _extends: kw("extends", beforeExpr),
  38774. _export: kw("export"),
  38775. _import: kw("import", startsExpr),
  38776. _null: kw("null", startsExpr),
  38777. _true: kw("true", startsExpr),
  38778. _false: kw("false", startsExpr),
  38779. _in: kw("in", {beforeExpr: true, binop: 7}),
  38780. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  38781. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  38782. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  38783. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  38784. };
  38785. // Matches a whole line break (where CRLF is considered a single
  38786. // line break). Used to count lines.
  38787. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  38788. var lineBreakG = new RegExp(lineBreak.source, "g");
  38789. function isNewLine(code, ecma2019String) {
  38790. return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
  38791. }
  38792. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  38793. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  38794. var ref = Object.prototype;
  38795. var hasOwnProperty$1 = ref.hasOwnProperty;
  38796. var toString$1 = ref.toString;
  38797. // Checks if an object has a property.
  38798. function has$1(obj, propName) {
  38799. return hasOwnProperty$1.call(obj, propName)
  38800. }
  38801. var isArray = Array.isArray || (function (obj) { return (
  38802. toString$1.call(obj) === "[object Array]"
  38803. ); });
  38804. function wordsRegexp(words) {
  38805. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  38806. }
  38807. // These are used when `options.locations` is on, for the
  38808. // `startLoc` and `endLoc` properties.
  38809. var Position = function Position(line, col) {
  38810. this.line = line;
  38811. this.column = col;
  38812. };
  38813. Position.prototype.offset = function offset (n) {
  38814. return new Position(this.line, this.column + n)
  38815. };
  38816. var SourceLocation = function SourceLocation(p, start, end) {
  38817. this.start = start;
  38818. this.end = end;
  38819. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  38820. };
  38821. // The `getLineInfo` function is mostly useful when the
  38822. // `locations` option is off (for performance reasons) and you
  38823. // want to find the line/column position for a given character
  38824. // offset. `input` should be the code string that the offset refers
  38825. // into.
  38826. function getLineInfo(input, offset) {
  38827. for (var line = 1, cur = 0;;) {
  38828. lineBreakG.lastIndex = cur;
  38829. var match = lineBreakG.exec(input);
  38830. if (match && match.index < offset) {
  38831. ++line;
  38832. cur = match.index + match[0].length;
  38833. } else {
  38834. return new Position(line, offset - cur)
  38835. }
  38836. }
  38837. }
  38838. // A second argument must be given to configure the parser process.
  38839. // These options are recognized (only `ecmaVersion` is required):
  38840. var defaultOptions = {
  38841. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  38842. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  38843. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  38844. // latest version the library supports). This influences support
  38845. // for strict mode, the set of reserved words, and support for
  38846. // new syntax features.
  38847. ecmaVersion: null,
  38848. // `sourceType` indicates the mode the code should be parsed in.
  38849. // Can be either `"script"` or `"module"`. This influences global
  38850. // strict mode and parsing of `import` and `export` declarations.
  38851. sourceType: "script",
  38852. // `onInsertedSemicolon` can be a callback that will be called
  38853. // when a semicolon is automatically inserted. It will be passed
  38854. // the position of the comma as an offset, and if `locations` is
  38855. // enabled, it is given the location as a `{line, column}` object
  38856. // as second argument.
  38857. onInsertedSemicolon: null,
  38858. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  38859. // trailing commas.
  38860. onTrailingComma: null,
  38861. // By default, reserved words are only enforced if ecmaVersion >= 5.
  38862. // Set `allowReserved` to a boolean value to explicitly turn this on
  38863. // an off. When this option has the value "never", reserved words
  38864. // and keywords can also not be used as property names.
  38865. allowReserved: null,
  38866. // When enabled, a return at the top level is not considered an
  38867. // error.
  38868. allowReturnOutsideFunction: false,
  38869. // When enabled, import/export statements are not constrained to
  38870. // appearing at the top of the program, and an import.meta expression
  38871. // in a script isn't considered an error.
  38872. allowImportExportEverywhere: false,
  38873. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  38874. // When enabled, await identifiers are allowed to appear at the top-level scope,
  38875. // but they are still not allowed in non-async functions.
  38876. allowAwaitOutsideFunction: null,
  38877. // When enabled, super identifiers are not constrained to
  38878. // appearing in methods and do not raise an error when they appear elsewhere.
  38879. allowSuperOutsideMethod: null,
  38880. // When enabled, hashbang directive in the beginning of file
  38881. // is allowed and treated as a line comment.
  38882. allowHashBang: false,
  38883. // When `locations` is on, `loc` properties holding objects with
  38884. // `start` and `end` properties in `{line, column}` form (with
  38885. // line being 1-based and column 0-based) will be attached to the
  38886. // nodes.
  38887. locations: false,
  38888. // A function can be passed as `onToken` option, which will
  38889. // cause Acorn to call that function with object in the same
  38890. // format as tokens returned from `tokenizer().getToken()`. Note
  38891. // that you are not allowed to call the parser from the
  38892. // callback—that will corrupt its internal state.
  38893. onToken: null,
  38894. // A function can be passed as `onComment` option, which will
  38895. // cause Acorn to call that function with `(block, text, start,
  38896. // end)` parameters whenever a comment is skipped. `block` is a
  38897. // boolean indicating whether this is a block (`/* */`) comment,
  38898. // `text` is the content of the comment, and `start` and `end` are
  38899. // character offsets that denote the start and end of the comment.
  38900. // When the `locations` option is on, two more parameters are
  38901. // passed, the full `{line, column}` locations of the start and
  38902. // end of the comments. Note that you are not allowed to call the
  38903. // parser from the callback—that will corrupt its internal state.
  38904. onComment: null,
  38905. // Nodes have their start and end characters offsets recorded in
  38906. // `start` and `end` properties (directly on the node, rather than
  38907. // the `loc` object, which holds line/column data. To also add a
  38908. // [semi-standardized][range] `range` property holding a `[start,
  38909. // end]` array with the same numbers, set the `ranges` option to
  38910. // `true`.
  38911. //
  38912. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  38913. ranges: false,
  38914. // It is possible to parse multiple files into a single AST by
  38915. // passing the tree produced by parsing the first file as
  38916. // `program` option in subsequent parses. This will add the
  38917. // toplevel forms of the parsed file to the `Program` (top) node
  38918. // of an existing parse tree.
  38919. program: null,
  38920. // When `locations` is on, you can pass this to record the source
  38921. // file in every node's `loc` object.
  38922. sourceFile: null,
  38923. // This value, if given, is stored in every node, whether
  38924. // `locations` is on or off.
  38925. directSourceFile: null,
  38926. // When enabled, parenthesized expressions are represented by
  38927. // (non-standard) ParenthesizedExpression nodes
  38928. preserveParens: false
  38929. };
  38930. // Interpret and default an options object
  38931. var warnedAboutEcmaVersion = false;
  38932. function getOptions(opts) {
  38933. var options = {};
  38934. for (var opt in defaultOptions)
  38935. { options[opt] = opts && has$1(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  38936. if (options.ecmaVersion === "latest") {
  38937. options.ecmaVersion = 1e8;
  38938. } else if (options.ecmaVersion == null) {
  38939. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  38940. warnedAboutEcmaVersion = true;
  38941. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  38942. }
  38943. options.ecmaVersion = 11;
  38944. } else if (options.ecmaVersion >= 2015) {
  38945. options.ecmaVersion -= 2009;
  38946. }
  38947. if (options.allowReserved == null)
  38948. { options.allowReserved = options.ecmaVersion < 5; }
  38949. if (isArray(options.onToken)) {
  38950. var tokens = options.onToken;
  38951. options.onToken = function (token) { return tokens.push(token); };
  38952. }
  38953. if (isArray(options.onComment))
  38954. { options.onComment = pushComment(options, options.onComment); }
  38955. return options
  38956. }
  38957. function pushComment(options, array) {
  38958. return function(block, text, start, end, startLoc, endLoc) {
  38959. var comment = {
  38960. type: block ? "Block" : "Line",
  38961. value: text,
  38962. start: start,
  38963. end: end
  38964. };
  38965. if (options.locations)
  38966. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  38967. if (options.ranges)
  38968. { comment.range = [start, end]; }
  38969. array.push(comment);
  38970. }
  38971. }
  38972. // Each scope gets a bitset that may contain these flags
  38973. var
  38974. SCOPE_TOP = 1,
  38975. SCOPE_FUNCTION = 2,
  38976. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
  38977. SCOPE_ASYNC = 4,
  38978. SCOPE_GENERATOR = 8,
  38979. SCOPE_ARROW = 16,
  38980. SCOPE_SIMPLE_CATCH = 32,
  38981. SCOPE_SUPER = 64,
  38982. SCOPE_DIRECT_SUPER = 128;
  38983. function functionFlags(async, generator) {
  38984. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  38985. }
  38986. // Used in checkLVal* and declareName to determine the type of a binding
  38987. var
  38988. BIND_NONE = 0, // Not a binding
  38989. BIND_VAR = 1, // Var-style binding
  38990. BIND_LEXICAL = 2, // Let- or const-style binding
  38991. BIND_FUNCTION = 3, // Function declaration
  38992. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  38993. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  38994. var Parser = function Parser(options, input, startPos) {
  38995. this.options = options = getOptions(options);
  38996. this.sourceFile = options.sourceFile;
  38997. this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  38998. var reserved = "";
  38999. if (options.allowReserved !== true) {
  39000. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  39001. if (options.sourceType === "module") { reserved += " await"; }
  39002. }
  39003. this.reservedWords = wordsRegexp(reserved);
  39004. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  39005. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  39006. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  39007. this.input = String(input);
  39008. // Used to signal to callers of `readWord1` whether the word
  39009. // contained any escape sequences. This is needed because words with
  39010. // escape sequences must not be interpreted as keywords.
  39011. this.containsEsc = false;
  39012. // Set up token state
  39013. // The current position of the tokenizer in the input.
  39014. if (startPos) {
  39015. this.pos = startPos;
  39016. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  39017. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  39018. } else {
  39019. this.pos = this.lineStart = 0;
  39020. this.curLine = 1;
  39021. }
  39022. // Properties of the current token:
  39023. // Its type
  39024. this.type = types.eof;
  39025. // For tokens that include more information than their type, the value
  39026. this.value = null;
  39027. // Its start and end offset
  39028. this.start = this.end = this.pos;
  39029. // And, if locations are used, the {line, column} object
  39030. // corresponding to those offsets
  39031. this.startLoc = this.endLoc = this.curPosition();
  39032. // Position information for the previous token
  39033. this.lastTokEndLoc = this.lastTokStartLoc = null;
  39034. this.lastTokStart = this.lastTokEnd = this.pos;
  39035. // The context stack is used to superficially track syntactic
  39036. // context to predict whether a regular expression is allowed in a
  39037. // given position.
  39038. this.context = this.initialContext();
  39039. this.exprAllowed = true;
  39040. // Figure out if it's a module code.
  39041. this.inModule = options.sourceType === "module";
  39042. this.strict = this.inModule || this.strictDirective(this.pos);
  39043. // Used to signify the start of a potential arrow function
  39044. this.potentialArrowAt = -1;
  39045. this.potentialArrowInForAwait = false;
  39046. // Positions to delayed-check that yield/await does not exist in default parameters.
  39047. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  39048. // Labels in scope.
  39049. this.labels = [];
  39050. // Thus-far undefined exports.
  39051. this.undefinedExports = Object.create(null);
  39052. // If enabled, skip leading hashbang line.
  39053. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  39054. { this.skipLineComment(2); }
  39055. // Scope tracking for duplicate variable names (see scope.js)
  39056. this.scopeStack = [];
  39057. this.enterScope(SCOPE_TOP);
  39058. // For RegExp validation
  39059. this.regexpState = null;
  39060. // The stack of private names.
  39061. // Each element has two properties: 'declared' and 'used'.
  39062. // When it exited from the outermost class definition, all used private names must be declared.
  39063. this.privateNameStack = [];
  39064. };
  39065. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
  39066. Parser.prototype.parse = function parse () {
  39067. var node = this.options.program || this.startNode();
  39068. this.nextToken();
  39069. return this.parseTopLevel(node)
  39070. };
  39071. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  39072. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  39073. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  39074. prototypeAccessors.canAwait.get = function () {
  39075. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  39076. var scope = this.scopeStack[i];
  39077. if (scope.inClassFieldInit) { return false }
  39078. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  39079. }
  39080. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  39081. };
  39082. prototypeAccessors.allowSuper.get = function () {
  39083. var ref = this.currentThisScope();
  39084. var flags = ref.flags;
  39085. var inClassFieldInit = ref.inClassFieldInit;
  39086. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  39087. };
  39088. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  39089. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  39090. prototypeAccessors.inNonArrowFunction.get = function () {
  39091. var ref = this.currentThisScope();
  39092. var flags = ref.flags;
  39093. var inClassFieldInit = ref.inClassFieldInit;
  39094. return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit
  39095. };
  39096. Parser.extend = function extend () {
  39097. var plugins = [], len = arguments.length;
  39098. while ( len-- ) plugins[ len ] = arguments[ len ];
  39099. var cls = this;
  39100. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  39101. return cls
  39102. };
  39103. Parser.parse = function parse (input, options) {
  39104. return new this(options, input).parse()
  39105. };
  39106. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  39107. var parser = new this(options, input, pos);
  39108. parser.nextToken();
  39109. return parser.parseExpression()
  39110. };
  39111. Parser.tokenizer = function tokenizer (input, options) {
  39112. return new this(options, input)
  39113. };
  39114. Object.defineProperties( Parser.prototype, prototypeAccessors );
  39115. var pp = Parser.prototype;
  39116. // ## Parser utilities
  39117. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  39118. pp.strictDirective = function(start) {
  39119. for (;;) {
  39120. // Try to find string literal.
  39121. skipWhiteSpace.lastIndex = start;
  39122. start += skipWhiteSpace.exec(this.input)[0].length;
  39123. var match = literal.exec(this.input.slice(start));
  39124. if (!match) { return false }
  39125. if ((match[1] || match[2]) === "use strict") {
  39126. skipWhiteSpace.lastIndex = start + match[0].length;
  39127. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  39128. var next = this.input.charAt(end);
  39129. return next === ";" || next === "}" ||
  39130. (lineBreak.test(spaceAfter[0]) &&
  39131. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  39132. }
  39133. start += match[0].length;
  39134. // Skip semicolon, if any.
  39135. skipWhiteSpace.lastIndex = start;
  39136. start += skipWhiteSpace.exec(this.input)[0].length;
  39137. if (this.input[start] === ";")
  39138. { start++; }
  39139. }
  39140. };
  39141. // Predicate that tests whether the next token is of the given
  39142. // type, and if yes, consumes it as a side effect.
  39143. pp.eat = function(type) {
  39144. if (this.type === type) {
  39145. this.next();
  39146. return true
  39147. } else {
  39148. return false
  39149. }
  39150. };
  39151. // Tests whether parsed token is a contextual keyword.
  39152. pp.isContextual = function(name) {
  39153. return this.type === types.name && this.value === name && !this.containsEsc
  39154. };
  39155. // Consumes contextual keyword if possible.
  39156. pp.eatContextual = function(name) {
  39157. if (!this.isContextual(name)) { return false }
  39158. this.next();
  39159. return true
  39160. };
  39161. // Asserts that following token is given contextual keyword.
  39162. pp.expectContextual = function(name) {
  39163. if (!this.eatContextual(name)) { this.unexpected(); }
  39164. };
  39165. // Test whether a semicolon can be inserted at the current position.
  39166. pp.canInsertSemicolon = function() {
  39167. return this.type === types.eof ||
  39168. this.type === types.braceR ||
  39169. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  39170. };
  39171. pp.insertSemicolon = function() {
  39172. if (this.canInsertSemicolon()) {
  39173. if (this.options.onInsertedSemicolon)
  39174. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  39175. return true
  39176. }
  39177. };
  39178. // Consume a semicolon, or, failing that, see if we are allowed to
  39179. // pretend that there is a semicolon at this position.
  39180. pp.semicolon = function() {
  39181. if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
  39182. };
  39183. pp.afterTrailingComma = function(tokType, notNext) {
  39184. if (this.type === tokType) {
  39185. if (this.options.onTrailingComma)
  39186. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  39187. if (!notNext)
  39188. { this.next(); }
  39189. return true
  39190. }
  39191. };
  39192. // Expect a token of a given type. If found, consume it, otherwise,
  39193. // raise an unexpected token error.
  39194. pp.expect = function(type) {
  39195. this.eat(type) || this.unexpected();
  39196. };
  39197. // Raise an unexpected token error.
  39198. pp.unexpected = function(pos) {
  39199. this.raise(pos != null ? pos : this.start, "Unexpected token");
  39200. };
  39201. function DestructuringErrors() {
  39202. this.shorthandAssign =
  39203. this.trailingComma =
  39204. this.parenthesizedAssign =
  39205. this.parenthesizedBind =
  39206. this.doubleProto =
  39207. -1;
  39208. }
  39209. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  39210. if (!refDestructuringErrors) { return }
  39211. if (refDestructuringErrors.trailingComma > -1)
  39212. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  39213. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  39214. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  39215. };
  39216. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  39217. if (!refDestructuringErrors) { return false }
  39218. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  39219. var doubleProto = refDestructuringErrors.doubleProto;
  39220. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  39221. if (shorthandAssign >= 0)
  39222. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  39223. if (doubleProto >= 0)
  39224. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  39225. };
  39226. pp.checkYieldAwaitInDefaultParams = function() {
  39227. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  39228. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  39229. if (this.awaitPos)
  39230. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  39231. };
  39232. pp.isSimpleAssignTarget = function(expr) {
  39233. if (expr.type === "ParenthesizedExpression")
  39234. { return this.isSimpleAssignTarget(expr.expression) }
  39235. return expr.type === "Identifier" || expr.type === "MemberExpression"
  39236. };
  39237. var pp$1 = Parser.prototype;
  39238. // ### Statement parsing
  39239. // Parse a program. Initializes the parser, reads any number of
  39240. // statements, and wraps them in a Program node. Optionally takes a
  39241. // `program` argument. If present, the statements will be appended
  39242. // to its body instead of creating a new node.
  39243. pp$1.parseTopLevel = function(node) {
  39244. var exports = Object.create(null);
  39245. if (!node.body) { node.body = []; }
  39246. while (this.type !== types.eof) {
  39247. var stmt = this.parseStatement(null, true, exports);
  39248. node.body.push(stmt);
  39249. }
  39250. if (this.inModule)
  39251. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  39252. {
  39253. var name = list[i];
  39254. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  39255. } }
  39256. this.adaptDirectivePrologue(node.body);
  39257. this.next();
  39258. node.sourceType = this.options.sourceType;
  39259. return this.finishNode(node, "Program")
  39260. };
  39261. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  39262. pp$1.isLet = function(context) {
  39263. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  39264. skipWhiteSpace.lastIndex = this.pos;
  39265. var skip = skipWhiteSpace.exec(this.input);
  39266. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  39267. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  39268. // Statement) is allowed here. If context is not empty then only a Statement
  39269. // is allowed. However, `let [` is an explicit negative lookahead for
  39270. // ExpressionStatement, so special-case it first.
  39271. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  39272. if (context) { return false }
  39273. if (nextCh === 123) { return true } // '{'
  39274. if (isIdentifierStart(nextCh, true)) {
  39275. var pos = next + 1;
  39276. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  39277. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  39278. var ident = this.input.slice(next, pos);
  39279. if (!keywordRelationalOperator.test(ident)) { return true }
  39280. }
  39281. return false
  39282. };
  39283. // check 'async [no LineTerminator here] function'
  39284. // - 'async /*foo*/ function' is OK.
  39285. // - 'async /*\n*/ function' is invalid.
  39286. pp$1.isAsyncFunction = function() {
  39287. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  39288. { return false }
  39289. skipWhiteSpace.lastIndex = this.pos;
  39290. var skip = skipWhiteSpace.exec(this.input);
  39291. var next = this.pos + skip[0].length, after;
  39292. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  39293. this.input.slice(next, next + 8) === "function" &&
  39294. (next + 8 === this.input.length ||
  39295. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  39296. };
  39297. // Parse a single statement.
  39298. //
  39299. // If expecting a statement and finding a slash operator, parse a
  39300. // regular expression literal. This is to handle cases like
  39301. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  39302. // does not help.
  39303. pp$1.parseStatement = function(context, topLevel, exports) {
  39304. var starttype = this.type, node = this.startNode(), kind;
  39305. if (this.isLet(context)) {
  39306. starttype = types._var;
  39307. kind = "let";
  39308. }
  39309. // Most types of statements are recognized by the keyword they
  39310. // start with. Many are trivial to parse, some require a bit of
  39311. // complexity.
  39312. switch (starttype) {
  39313. case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  39314. case types._debugger: return this.parseDebuggerStatement(node)
  39315. case types._do: return this.parseDoStatement(node)
  39316. case types._for: return this.parseForStatement(node)
  39317. case types._function:
  39318. // Function as sole body of either an if statement or a labeled statement
  39319. // works, but not when it is part of a labeled statement that is the sole
  39320. // body of an if statement.
  39321. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  39322. return this.parseFunctionStatement(node, false, !context)
  39323. case types._class:
  39324. if (context) { this.unexpected(); }
  39325. return this.parseClass(node, true)
  39326. case types._if: return this.parseIfStatement(node)
  39327. case types._return: return this.parseReturnStatement(node)
  39328. case types._switch: return this.parseSwitchStatement(node)
  39329. case types._throw: return this.parseThrowStatement(node)
  39330. case types._try: return this.parseTryStatement(node)
  39331. case types._const: case types._var:
  39332. kind = kind || this.value;
  39333. if (context && kind !== "var") { this.unexpected(); }
  39334. return this.parseVarStatement(node, kind)
  39335. case types._while: return this.parseWhileStatement(node)
  39336. case types._with: return this.parseWithStatement(node)
  39337. case types.braceL: return this.parseBlock(true, node)
  39338. case types.semi: return this.parseEmptyStatement(node)
  39339. case types._export:
  39340. case types._import:
  39341. if (this.options.ecmaVersion > 10 && starttype === types._import) {
  39342. skipWhiteSpace.lastIndex = this.pos;
  39343. var skip = skipWhiteSpace.exec(this.input);
  39344. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  39345. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  39346. { return this.parseExpressionStatement(node, this.parseExpression()) }
  39347. }
  39348. if (!this.options.allowImportExportEverywhere) {
  39349. if (!topLevel)
  39350. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  39351. if (!this.inModule)
  39352. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  39353. }
  39354. return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
  39355. // If the statement does not start with a statement keyword or a
  39356. // brace, it's an ExpressionStatement or LabeledStatement. We
  39357. // simply start parsing an expression, and afterwards, if the
  39358. // next token is a colon and the expression was a simple
  39359. // Identifier node, we switch to interpreting it as a label.
  39360. default:
  39361. if (this.isAsyncFunction()) {
  39362. if (context) { this.unexpected(); }
  39363. this.next();
  39364. return this.parseFunctionStatement(node, true, !context)
  39365. }
  39366. var maybeName = this.value, expr = this.parseExpression();
  39367. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
  39368. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  39369. else { return this.parseExpressionStatement(node, expr) }
  39370. }
  39371. };
  39372. pp$1.parseBreakContinueStatement = function(node, keyword) {
  39373. var isBreak = keyword === "break";
  39374. this.next();
  39375. if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
  39376. else if (this.type !== types.name) { this.unexpected(); }
  39377. else {
  39378. node.label = this.parseIdent();
  39379. this.semicolon();
  39380. }
  39381. // Verify that there is an actual destination to break or
  39382. // continue to.
  39383. var i = 0;
  39384. for (; i < this.labels.length; ++i) {
  39385. var lab = this.labels[i];
  39386. if (node.label == null || lab.name === node.label.name) {
  39387. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  39388. if (node.label && isBreak) { break }
  39389. }
  39390. }
  39391. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  39392. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  39393. };
  39394. pp$1.parseDebuggerStatement = function(node) {
  39395. this.next();
  39396. this.semicolon();
  39397. return this.finishNode(node, "DebuggerStatement")
  39398. };
  39399. pp$1.parseDoStatement = function(node) {
  39400. this.next();
  39401. this.labels.push(loopLabel);
  39402. node.body = this.parseStatement("do");
  39403. this.labels.pop();
  39404. this.expect(types._while);
  39405. node.test = this.parseParenExpression();
  39406. if (this.options.ecmaVersion >= 6)
  39407. { this.eat(types.semi); }
  39408. else
  39409. { this.semicolon(); }
  39410. return this.finishNode(node, "DoWhileStatement")
  39411. };
  39412. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  39413. // loop is non-trivial. Basically, we have to parse the init `var`
  39414. // statement or expression, disallowing the `in` operator (see
  39415. // the second parameter to `parseExpression`), and then check
  39416. // whether the next token is `in` or `of`. When there is no init
  39417. // part (semicolon immediately after the opening parenthesis), it
  39418. // is a regular `for` loop.
  39419. pp$1.parseForStatement = function(node) {
  39420. this.next();
  39421. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  39422. this.labels.push(loopLabel);
  39423. this.enterScope(0);
  39424. this.expect(types.parenL);
  39425. if (this.type === types.semi) {
  39426. if (awaitAt > -1) { this.unexpected(awaitAt); }
  39427. return this.parseFor(node, null)
  39428. }
  39429. var isLet = this.isLet();
  39430. if (this.type === types._var || this.type === types._const || isLet) {
  39431. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  39432. this.next();
  39433. this.parseVar(init$1, true, kind);
  39434. this.finishNode(init$1, "VariableDeclaration");
  39435. if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  39436. if (this.options.ecmaVersion >= 9) {
  39437. if (this.type === types._in) {
  39438. if (awaitAt > -1) { this.unexpected(awaitAt); }
  39439. } else { node.await = awaitAt > -1; }
  39440. }
  39441. return this.parseForIn(node, init$1)
  39442. }
  39443. if (awaitAt > -1) { this.unexpected(awaitAt); }
  39444. return this.parseFor(node, init$1)
  39445. }
  39446. var refDestructuringErrors = new DestructuringErrors;
  39447. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  39448. if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  39449. if (this.options.ecmaVersion >= 9) {
  39450. if (this.type === types._in) {
  39451. if (awaitAt > -1) { this.unexpected(awaitAt); }
  39452. } else { node.await = awaitAt > -1; }
  39453. }
  39454. this.toAssignable(init, false, refDestructuringErrors);
  39455. this.checkLValPattern(init);
  39456. return this.parseForIn(node, init)
  39457. } else {
  39458. this.checkExpressionErrors(refDestructuringErrors, true);
  39459. }
  39460. if (awaitAt > -1) { this.unexpected(awaitAt); }
  39461. return this.parseFor(node, init)
  39462. };
  39463. pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  39464. this.next();
  39465. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  39466. };
  39467. pp$1.parseIfStatement = function(node) {
  39468. this.next();
  39469. node.test = this.parseParenExpression();
  39470. // allow function declarations in branches, but only in non-strict mode
  39471. node.consequent = this.parseStatement("if");
  39472. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  39473. return this.finishNode(node, "IfStatement")
  39474. };
  39475. pp$1.parseReturnStatement = function(node) {
  39476. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  39477. { this.raise(this.start, "'return' outside of function"); }
  39478. this.next();
  39479. // In `return` (and `break`/`continue`), the keywords with
  39480. // optional arguments, we eagerly look for a semicolon or the
  39481. // possibility to insert one.
  39482. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
  39483. else { node.argument = this.parseExpression(); this.semicolon(); }
  39484. return this.finishNode(node, "ReturnStatement")
  39485. };
  39486. pp$1.parseSwitchStatement = function(node) {
  39487. this.next();
  39488. node.discriminant = this.parseParenExpression();
  39489. node.cases = [];
  39490. this.expect(types.braceL);
  39491. this.labels.push(switchLabel);
  39492. this.enterScope(0);
  39493. // Statements under must be grouped (by label) in SwitchCase
  39494. // nodes. `cur` is used to keep the node that we are currently
  39495. // adding statements to.
  39496. var cur;
  39497. for (var sawDefault = false; this.type !== types.braceR;) {
  39498. if (this.type === types._case || this.type === types._default) {
  39499. var isCase = this.type === types._case;
  39500. if (cur) { this.finishNode(cur, "SwitchCase"); }
  39501. node.cases.push(cur = this.startNode());
  39502. cur.consequent = [];
  39503. this.next();
  39504. if (isCase) {
  39505. cur.test = this.parseExpression();
  39506. } else {
  39507. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  39508. sawDefault = true;
  39509. cur.test = null;
  39510. }
  39511. this.expect(types.colon);
  39512. } else {
  39513. if (!cur) { this.unexpected(); }
  39514. cur.consequent.push(this.parseStatement(null));
  39515. }
  39516. }
  39517. this.exitScope();
  39518. if (cur) { this.finishNode(cur, "SwitchCase"); }
  39519. this.next(); // Closing brace
  39520. this.labels.pop();
  39521. return this.finishNode(node, "SwitchStatement")
  39522. };
  39523. pp$1.parseThrowStatement = function(node) {
  39524. this.next();
  39525. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  39526. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  39527. node.argument = this.parseExpression();
  39528. this.semicolon();
  39529. return this.finishNode(node, "ThrowStatement")
  39530. };
  39531. // Reused empty array added for node fields that are always empty.
  39532. var empty = [];
  39533. pp$1.parseTryStatement = function(node) {
  39534. this.next();
  39535. node.block = this.parseBlock();
  39536. node.handler = null;
  39537. if (this.type === types._catch) {
  39538. var clause = this.startNode();
  39539. this.next();
  39540. if (this.eat(types.parenL)) {
  39541. clause.param = this.parseBindingAtom();
  39542. var simple = clause.param.type === "Identifier";
  39543. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  39544. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  39545. this.expect(types.parenR);
  39546. } else {
  39547. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  39548. clause.param = null;
  39549. this.enterScope(0);
  39550. }
  39551. clause.body = this.parseBlock(false);
  39552. this.exitScope();
  39553. node.handler = this.finishNode(clause, "CatchClause");
  39554. }
  39555. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  39556. if (!node.handler && !node.finalizer)
  39557. { this.raise(node.start, "Missing catch or finally clause"); }
  39558. return this.finishNode(node, "TryStatement")
  39559. };
  39560. pp$1.parseVarStatement = function(node, kind) {
  39561. this.next();
  39562. this.parseVar(node, false, kind);
  39563. this.semicolon();
  39564. return this.finishNode(node, "VariableDeclaration")
  39565. };
  39566. pp$1.parseWhileStatement = function(node) {
  39567. this.next();
  39568. node.test = this.parseParenExpression();
  39569. this.labels.push(loopLabel);
  39570. node.body = this.parseStatement("while");
  39571. this.labels.pop();
  39572. return this.finishNode(node, "WhileStatement")
  39573. };
  39574. pp$1.parseWithStatement = function(node) {
  39575. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  39576. this.next();
  39577. node.object = this.parseParenExpression();
  39578. node.body = this.parseStatement("with");
  39579. return this.finishNode(node, "WithStatement")
  39580. };
  39581. pp$1.parseEmptyStatement = function(node) {
  39582. this.next();
  39583. return this.finishNode(node, "EmptyStatement")
  39584. };
  39585. pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  39586. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  39587. {
  39588. var label = list[i$1];
  39589. if (label.name === maybeName)
  39590. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  39591. } }
  39592. var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
  39593. for (var i = this.labels.length - 1; i >= 0; i--) {
  39594. var label$1 = this.labels[i];
  39595. if (label$1.statementStart === node.start) {
  39596. // Update information about previous labels on this node
  39597. label$1.statementStart = this.start;
  39598. label$1.kind = kind;
  39599. } else { break }
  39600. }
  39601. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  39602. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  39603. this.labels.pop();
  39604. node.label = expr;
  39605. return this.finishNode(node, "LabeledStatement")
  39606. };
  39607. pp$1.parseExpressionStatement = function(node, expr) {
  39608. node.expression = expr;
  39609. this.semicolon();
  39610. return this.finishNode(node, "ExpressionStatement")
  39611. };
  39612. // Parse a semicolon-enclosed block of statements, handling `"use
  39613. // strict"` declarations when `allowStrict` is true (used for
  39614. // function bodies).
  39615. pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  39616. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  39617. if ( node === void 0 ) node = this.startNode();
  39618. node.body = [];
  39619. this.expect(types.braceL);
  39620. if (createNewLexicalScope) { this.enterScope(0); }
  39621. while (this.type !== types.braceR) {
  39622. var stmt = this.parseStatement(null);
  39623. node.body.push(stmt);
  39624. }
  39625. if (exitStrict) { this.strict = false; }
  39626. this.next();
  39627. if (createNewLexicalScope) { this.exitScope(); }
  39628. return this.finishNode(node, "BlockStatement")
  39629. };
  39630. // Parse a regular `for` loop. The disambiguation code in
  39631. // `parseStatement` will already have parsed the init statement or
  39632. // expression.
  39633. pp$1.parseFor = function(node, init) {
  39634. node.init = init;
  39635. this.expect(types.semi);
  39636. node.test = this.type === types.semi ? null : this.parseExpression();
  39637. this.expect(types.semi);
  39638. node.update = this.type === types.parenR ? null : this.parseExpression();
  39639. this.expect(types.parenR);
  39640. node.body = this.parseStatement("for");
  39641. this.exitScope();
  39642. this.labels.pop();
  39643. return this.finishNode(node, "ForStatement")
  39644. };
  39645. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  39646. // same from parser's perspective.
  39647. pp$1.parseForIn = function(node, init) {
  39648. var isForIn = this.type === types._in;
  39649. this.next();
  39650. if (
  39651. init.type === "VariableDeclaration" &&
  39652. init.declarations[0].init != null &&
  39653. (
  39654. !isForIn ||
  39655. this.options.ecmaVersion < 8 ||
  39656. this.strict ||
  39657. init.kind !== "var" ||
  39658. init.declarations[0].id.type !== "Identifier"
  39659. )
  39660. ) {
  39661. this.raise(
  39662. init.start,
  39663. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  39664. );
  39665. }
  39666. node.left = init;
  39667. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  39668. this.expect(types.parenR);
  39669. node.body = this.parseStatement("for");
  39670. this.exitScope();
  39671. this.labels.pop();
  39672. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  39673. };
  39674. // Parse a list of variable declarations.
  39675. pp$1.parseVar = function(node, isFor, kind) {
  39676. node.declarations = [];
  39677. node.kind = kind;
  39678. for (;;) {
  39679. var decl = this.startNode();
  39680. this.parseVarId(decl, kind);
  39681. if (this.eat(types.eq)) {
  39682. decl.init = this.parseMaybeAssign(isFor);
  39683. } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  39684. this.unexpected();
  39685. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
  39686. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  39687. } else {
  39688. decl.init = null;
  39689. }
  39690. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  39691. if (!this.eat(types.comma)) { break }
  39692. }
  39693. return node
  39694. };
  39695. pp$1.parseVarId = function(decl, kind) {
  39696. decl.id = this.parseBindingAtom();
  39697. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  39698. };
  39699. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  39700. // Parse a function declaration or literal (depending on the
  39701. // `statement & FUNC_STATEMENT`).
  39702. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  39703. pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
  39704. this.initFunction(node);
  39705. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  39706. if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
  39707. { this.unexpected(); }
  39708. node.generator = this.eat(types.star);
  39709. }
  39710. if (this.options.ecmaVersion >= 8)
  39711. { node.async = !!isAsync; }
  39712. if (statement & FUNC_STATEMENT) {
  39713. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
  39714. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  39715. // If it is a regular function declaration in sloppy mode, then it is
  39716. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  39717. // mode depends on properties of the current scope (see
  39718. // treatFunctionsAsVar).
  39719. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  39720. }
  39721. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  39722. this.yieldPos = 0;
  39723. this.awaitPos = 0;
  39724. this.awaitIdentPos = 0;
  39725. this.enterScope(functionFlags(node.async, node.generator));
  39726. if (!(statement & FUNC_STATEMENT))
  39727. { node.id = this.type === types.name ? this.parseIdent() : null; }
  39728. this.parseFunctionParams(node);
  39729. this.parseFunctionBody(node, allowExpressionBody, false);
  39730. this.yieldPos = oldYieldPos;
  39731. this.awaitPos = oldAwaitPos;
  39732. this.awaitIdentPos = oldAwaitIdentPos;
  39733. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  39734. };
  39735. pp$1.parseFunctionParams = function(node) {
  39736. this.expect(types.parenL);
  39737. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  39738. this.checkYieldAwaitInDefaultParams();
  39739. };
  39740. // Parse a class declaration or literal (depending on the
  39741. // `isStatement` parameter).
  39742. pp$1.parseClass = function(node, isStatement) {
  39743. this.next();
  39744. // ecma-262 14.6 Class Definitions
  39745. // A class definition is always strict mode code.
  39746. var oldStrict = this.strict;
  39747. this.strict = true;
  39748. this.parseClassId(node, isStatement);
  39749. this.parseClassSuper(node);
  39750. var privateNameMap = this.enterClassBody();
  39751. var classBody = this.startNode();
  39752. var hadConstructor = false;
  39753. classBody.body = [];
  39754. this.expect(types.braceL);
  39755. while (this.type !== types.braceR) {
  39756. var element = this.parseClassElement(node.superClass !== null);
  39757. if (element) {
  39758. classBody.body.push(element);
  39759. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  39760. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  39761. hadConstructor = true;
  39762. } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  39763. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  39764. }
  39765. }
  39766. }
  39767. this.strict = oldStrict;
  39768. this.next();
  39769. node.body = this.finishNode(classBody, "ClassBody");
  39770. this.exitClassBody();
  39771. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  39772. };
  39773. pp$1.parseClassElement = function(constructorAllowsSuper) {
  39774. if (this.eat(types.semi)) { return null }
  39775. var ecmaVersion = this.options.ecmaVersion;
  39776. var node = this.startNode();
  39777. var keyName = "";
  39778. var isGenerator = false;
  39779. var isAsync = false;
  39780. var kind = "method";
  39781. // Parse modifiers
  39782. node.static = false;
  39783. if (this.eatContextual("static")) {
  39784. if (this.isClassElementNameStart() || this.type === types.star) {
  39785. node.static = true;
  39786. } else {
  39787. keyName = "static";
  39788. }
  39789. }
  39790. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  39791. if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) {
  39792. isAsync = true;
  39793. } else {
  39794. keyName = "async";
  39795. }
  39796. }
  39797. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) {
  39798. isGenerator = true;
  39799. }
  39800. if (!keyName && !isAsync && !isGenerator) {
  39801. var lastValue = this.value;
  39802. if (this.eatContextual("get") || this.eatContextual("set")) {
  39803. if (this.isClassElementNameStart()) {
  39804. kind = lastValue;
  39805. } else {
  39806. keyName = lastValue;
  39807. }
  39808. }
  39809. }
  39810. // Parse element name
  39811. if (keyName) {
  39812. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  39813. // The last token is any of those. Make it the element name.
  39814. node.computed = false;
  39815. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  39816. node.key.name = keyName;
  39817. this.finishNode(node.key, "Identifier");
  39818. } else {
  39819. this.parseClassElementName(node);
  39820. }
  39821. // Parse element value
  39822. if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) {
  39823. var isConstructor = !node.static && checkKeyName(node, "constructor");
  39824. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  39825. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  39826. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  39827. node.kind = isConstructor ? "constructor" : kind;
  39828. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  39829. } else {
  39830. this.parseClassField(node);
  39831. }
  39832. return node
  39833. };
  39834. pp$1.isClassElementNameStart = function() {
  39835. return (
  39836. this.type === types.name ||
  39837. this.type === types.privateId ||
  39838. this.type === types.num ||
  39839. this.type === types.string ||
  39840. this.type === types.bracketL ||
  39841. this.type.keyword
  39842. )
  39843. };
  39844. pp$1.parseClassElementName = function(element) {
  39845. if (this.type === types.privateId) {
  39846. if (this.value === "constructor") {
  39847. this.raise(this.start, "Classes can't have an element named '#constructor'");
  39848. }
  39849. element.computed = false;
  39850. element.key = this.parsePrivateIdent();
  39851. } else {
  39852. this.parsePropertyName(element);
  39853. }
  39854. };
  39855. pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  39856. // Check key and flags
  39857. var key = method.key;
  39858. if (method.kind === "constructor") {
  39859. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  39860. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  39861. } else if (method.static && checkKeyName(method, "prototype")) {
  39862. this.raise(key.start, "Classes may not have a static property named prototype");
  39863. }
  39864. // Parse value
  39865. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  39866. // Check value
  39867. if (method.kind === "get" && value.params.length !== 0)
  39868. { this.raiseRecoverable(value.start, "getter should have no params"); }
  39869. if (method.kind === "set" && value.params.length !== 1)
  39870. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  39871. if (method.kind === "set" && value.params[0].type === "RestElement")
  39872. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  39873. return this.finishNode(method, "MethodDefinition")
  39874. };
  39875. pp$1.parseClassField = function(field) {
  39876. if (checkKeyName(field, "constructor")) {
  39877. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  39878. } else if (field.static && checkKeyName(field, "prototype")) {
  39879. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  39880. }
  39881. if (this.eat(types.eq)) {
  39882. // To raise SyntaxError if 'arguments' exists in the initializer.
  39883. var scope = this.currentThisScope();
  39884. var inClassFieldInit = scope.inClassFieldInit;
  39885. scope.inClassFieldInit = true;
  39886. field.value = this.parseMaybeAssign();
  39887. scope.inClassFieldInit = inClassFieldInit;
  39888. } else {
  39889. field.value = null;
  39890. }
  39891. this.semicolon();
  39892. return this.finishNode(field, "PropertyDefinition")
  39893. };
  39894. pp$1.parseClassId = function(node, isStatement) {
  39895. if (this.type === types.name) {
  39896. node.id = this.parseIdent();
  39897. if (isStatement)
  39898. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  39899. } else {
  39900. if (isStatement === true)
  39901. { this.unexpected(); }
  39902. node.id = null;
  39903. }
  39904. };
  39905. pp$1.parseClassSuper = function(node) {
  39906. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  39907. };
  39908. pp$1.enterClassBody = function() {
  39909. var element = {declared: Object.create(null), used: []};
  39910. this.privateNameStack.push(element);
  39911. return element.declared
  39912. };
  39913. pp$1.exitClassBody = function() {
  39914. var ref = this.privateNameStack.pop();
  39915. var declared = ref.declared;
  39916. var used = ref.used;
  39917. var len = this.privateNameStack.length;
  39918. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  39919. for (var i = 0; i < used.length; ++i) {
  39920. var id = used[i];
  39921. if (!has$1(declared, id.name)) {
  39922. if (parent) {
  39923. parent.used.push(id);
  39924. } else {
  39925. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  39926. }
  39927. }
  39928. }
  39929. };
  39930. function isPrivateNameConflicted(privateNameMap, element) {
  39931. var name = element.key.name;
  39932. var curr = privateNameMap[name];
  39933. var next = "true";
  39934. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  39935. next = (element.static ? "s" : "i") + element.kind;
  39936. }
  39937. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  39938. if (
  39939. curr === "iget" && next === "iset" ||
  39940. curr === "iset" && next === "iget" ||
  39941. curr === "sget" && next === "sset" ||
  39942. curr === "sset" && next === "sget"
  39943. ) {
  39944. privateNameMap[name] = "true";
  39945. return false
  39946. } else if (!curr) {
  39947. privateNameMap[name] = next;
  39948. return false
  39949. } else {
  39950. return true
  39951. }
  39952. }
  39953. function checkKeyName(node, name) {
  39954. var computed = node.computed;
  39955. var key = node.key;
  39956. return !computed && (
  39957. key.type === "Identifier" && key.name === name ||
  39958. key.type === "Literal" && key.value === name
  39959. )
  39960. }
  39961. // Parses module export declaration.
  39962. pp$1.parseExport = function(node, exports) {
  39963. this.next();
  39964. // export * from '...'
  39965. if (this.eat(types.star)) {
  39966. if (this.options.ecmaVersion >= 11) {
  39967. if (this.eatContextual("as")) {
  39968. node.exported = this.parseIdent(true);
  39969. this.checkExport(exports, node.exported.name, this.lastTokStart);
  39970. } else {
  39971. node.exported = null;
  39972. }
  39973. }
  39974. this.expectContextual("from");
  39975. if (this.type !== types.string) { this.unexpected(); }
  39976. node.source = this.parseExprAtom();
  39977. this.semicolon();
  39978. return this.finishNode(node, "ExportAllDeclaration")
  39979. }
  39980. if (this.eat(types._default)) { // export default ...
  39981. this.checkExport(exports, "default", this.lastTokStart);
  39982. var isAsync;
  39983. if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
  39984. var fNode = this.startNode();
  39985. this.next();
  39986. if (isAsync) { this.next(); }
  39987. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  39988. } else if (this.type === types._class) {
  39989. var cNode = this.startNode();
  39990. node.declaration = this.parseClass(cNode, "nullableID");
  39991. } else {
  39992. node.declaration = this.parseMaybeAssign();
  39993. this.semicolon();
  39994. }
  39995. return this.finishNode(node, "ExportDefaultDeclaration")
  39996. }
  39997. // export var|const|let|function|class ...
  39998. if (this.shouldParseExportStatement()) {
  39999. node.declaration = this.parseStatement(null);
  40000. if (node.declaration.type === "VariableDeclaration")
  40001. { this.checkVariableExport(exports, node.declaration.declarations); }
  40002. else
  40003. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  40004. node.specifiers = [];
  40005. node.source = null;
  40006. } else { // export { x, y as z } [from '...']
  40007. node.declaration = null;
  40008. node.specifiers = this.parseExportSpecifiers(exports);
  40009. if (this.eatContextual("from")) {
  40010. if (this.type !== types.string) { this.unexpected(); }
  40011. node.source = this.parseExprAtom();
  40012. } else {
  40013. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  40014. // check for keywords used as local names
  40015. var spec = list[i];
  40016. this.checkUnreserved(spec.local);
  40017. // check if export is defined
  40018. this.checkLocalExport(spec.local);
  40019. }
  40020. node.source = null;
  40021. }
  40022. this.semicolon();
  40023. }
  40024. return this.finishNode(node, "ExportNamedDeclaration")
  40025. };
  40026. pp$1.checkExport = function(exports, name, pos) {
  40027. if (!exports) { return }
  40028. if (has$1(exports, name))
  40029. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  40030. exports[name] = true;
  40031. };
  40032. pp$1.checkPatternExport = function(exports, pat) {
  40033. var type = pat.type;
  40034. if (type === "Identifier")
  40035. { this.checkExport(exports, pat.name, pat.start); }
  40036. else if (type === "ObjectPattern")
  40037. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  40038. {
  40039. var prop = list[i];
  40040. this.checkPatternExport(exports, prop);
  40041. } }
  40042. else if (type === "ArrayPattern")
  40043. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  40044. var elt = list$1[i$1];
  40045. if (elt) { this.checkPatternExport(exports, elt); }
  40046. } }
  40047. else if (type === "Property")
  40048. { this.checkPatternExport(exports, pat.value); }
  40049. else if (type === "AssignmentPattern")
  40050. { this.checkPatternExport(exports, pat.left); }
  40051. else if (type === "RestElement")
  40052. { this.checkPatternExport(exports, pat.argument); }
  40053. else if (type === "ParenthesizedExpression")
  40054. { this.checkPatternExport(exports, pat.expression); }
  40055. };
  40056. pp$1.checkVariableExport = function(exports, decls) {
  40057. if (!exports) { return }
  40058. for (var i = 0, list = decls; i < list.length; i += 1)
  40059. {
  40060. var decl = list[i];
  40061. this.checkPatternExport(exports, decl.id);
  40062. }
  40063. };
  40064. pp$1.shouldParseExportStatement = function() {
  40065. return this.type.keyword === "var" ||
  40066. this.type.keyword === "const" ||
  40067. this.type.keyword === "class" ||
  40068. this.type.keyword === "function" ||
  40069. this.isLet() ||
  40070. this.isAsyncFunction()
  40071. };
  40072. // Parses a comma-separated list of module exports.
  40073. pp$1.parseExportSpecifiers = function(exports) {
  40074. var nodes = [], first = true;
  40075. // export { x, y as z } [from '...']
  40076. this.expect(types.braceL);
  40077. while (!this.eat(types.braceR)) {
  40078. if (!first) {
  40079. this.expect(types.comma);
  40080. if (this.afterTrailingComma(types.braceR)) { break }
  40081. } else { first = false; }
  40082. var node = this.startNode();
  40083. node.local = this.parseIdent(true);
  40084. node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
  40085. this.checkExport(exports, node.exported.name, node.exported.start);
  40086. nodes.push(this.finishNode(node, "ExportSpecifier"));
  40087. }
  40088. return nodes
  40089. };
  40090. // Parses import declaration.
  40091. pp$1.parseImport = function(node) {
  40092. this.next();
  40093. // import '...'
  40094. if (this.type === types.string) {
  40095. node.specifiers = empty;
  40096. node.source = this.parseExprAtom();
  40097. } else {
  40098. node.specifiers = this.parseImportSpecifiers();
  40099. this.expectContextual("from");
  40100. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  40101. }
  40102. this.semicolon();
  40103. return this.finishNode(node, "ImportDeclaration")
  40104. };
  40105. // Parses a comma-separated list of module imports.
  40106. pp$1.parseImportSpecifiers = function() {
  40107. var nodes = [], first = true;
  40108. if (this.type === types.name) {
  40109. // import defaultObj, { x, y as z } from '...'
  40110. var node = this.startNode();
  40111. node.local = this.parseIdent();
  40112. this.checkLValSimple(node.local, BIND_LEXICAL);
  40113. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  40114. if (!this.eat(types.comma)) { return nodes }
  40115. }
  40116. if (this.type === types.star) {
  40117. var node$1 = this.startNode();
  40118. this.next();
  40119. this.expectContextual("as");
  40120. node$1.local = this.parseIdent();
  40121. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  40122. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  40123. return nodes
  40124. }
  40125. this.expect(types.braceL);
  40126. while (!this.eat(types.braceR)) {
  40127. if (!first) {
  40128. this.expect(types.comma);
  40129. if (this.afterTrailingComma(types.braceR)) { break }
  40130. } else { first = false; }
  40131. var node$2 = this.startNode();
  40132. node$2.imported = this.parseIdent(true);
  40133. if (this.eatContextual("as")) {
  40134. node$2.local = this.parseIdent();
  40135. } else {
  40136. this.checkUnreserved(node$2.imported);
  40137. node$2.local = node$2.imported;
  40138. }
  40139. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  40140. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  40141. }
  40142. return nodes
  40143. };
  40144. // Set `ExpressionStatement#directive` property for directive prologues.
  40145. pp$1.adaptDirectivePrologue = function(statements) {
  40146. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  40147. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  40148. }
  40149. };
  40150. pp$1.isDirectiveCandidate = function(statement) {
  40151. return (
  40152. statement.type === "ExpressionStatement" &&
  40153. statement.expression.type === "Literal" &&
  40154. typeof statement.expression.value === "string" &&
  40155. // Reject parenthesized strings.
  40156. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  40157. )
  40158. };
  40159. var pp$2 = Parser.prototype;
  40160. // Convert existing expression atom to assignable pattern
  40161. // if possible.
  40162. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  40163. if (this.options.ecmaVersion >= 6 && node) {
  40164. switch (node.type) {
  40165. case "Identifier":
  40166. if (this.inAsync && node.name === "await")
  40167. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  40168. break
  40169. case "ObjectPattern":
  40170. case "ArrayPattern":
  40171. case "AssignmentPattern":
  40172. case "RestElement":
  40173. break
  40174. case "ObjectExpression":
  40175. node.type = "ObjectPattern";
  40176. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  40177. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  40178. var prop = list[i];
  40179. this.toAssignable(prop, isBinding);
  40180. // Early error:
  40181. // AssignmentRestProperty[Yield, Await] :
  40182. // `...` DestructuringAssignmentTarget[Yield, Await]
  40183. //
  40184. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  40185. if (
  40186. prop.type === "RestElement" &&
  40187. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  40188. ) {
  40189. this.raise(prop.argument.start, "Unexpected token");
  40190. }
  40191. }
  40192. break
  40193. case "Property":
  40194. // AssignmentProperty has type === "Property"
  40195. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  40196. this.toAssignable(node.value, isBinding);
  40197. break
  40198. case "ArrayExpression":
  40199. node.type = "ArrayPattern";
  40200. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  40201. this.toAssignableList(node.elements, isBinding);
  40202. break
  40203. case "SpreadElement":
  40204. node.type = "RestElement";
  40205. this.toAssignable(node.argument, isBinding);
  40206. if (node.argument.type === "AssignmentPattern")
  40207. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  40208. break
  40209. case "AssignmentExpression":
  40210. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  40211. node.type = "AssignmentPattern";
  40212. delete node.operator;
  40213. this.toAssignable(node.left, isBinding);
  40214. break
  40215. case "ParenthesizedExpression":
  40216. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  40217. break
  40218. case "ChainExpression":
  40219. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  40220. break
  40221. case "MemberExpression":
  40222. if (!isBinding) { break }
  40223. default:
  40224. this.raise(node.start, "Assigning to rvalue");
  40225. }
  40226. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  40227. return node
  40228. };
  40229. // Convert list of expression atoms to binding list.
  40230. pp$2.toAssignableList = function(exprList, isBinding) {
  40231. var end = exprList.length;
  40232. for (var i = 0; i < end; i++) {
  40233. var elt = exprList[i];
  40234. if (elt) { this.toAssignable(elt, isBinding); }
  40235. }
  40236. if (end) {
  40237. var last = exprList[end - 1];
  40238. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  40239. { this.unexpected(last.argument.start); }
  40240. }
  40241. return exprList
  40242. };
  40243. // Parses spread element.
  40244. pp$2.parseSpread = function(refDestructuringErrors) {
  40245. var node = this.startNode();
  40246. this.next();
  40247. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  40248. return this.finishNode(node, "SpreadElement")
  40249. };
  40250. pp$2.parseRestBinding = function() {
  40251. var node = this.startNode();
  40252. this.next();
  40253. // RestElement inside of a function parameter must be an identifier
  40254. if (this.options.ecmaVersion === 6 && this.type !== types.name)
  40255. { this.unexpected(); }
  40256. node.argument = this.parseBindingAtom();
  40257. return this.finishNode(node, "RestElement")
  40258. };
  40259. // Parses lvalue (assignable) atom.
  40260. pp$2.parseBindingAtom = function() {
  40261. if (this.options.ecmaVersion >= 6) {
  40262. switch (this.type) {
  40263. case types.bracketL:
  40264. var node = this.startNode();
  40265. this.next();
  40266. node.elements = this.parseBindingList(types.bracketR, true, true);
  40267. return this.finishNode(node, "ArrayPattern")
  40268. case types.braceL:
  40269. return this.parseObj(true)
  40270. }
  40271. }
  40272. return this.parseIdent()
  40273. };
  40274. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  40275. var elts = [], first = true;
  40276. while (!this.eat(close)) {
  40277. if (first) { first = false; }
  40278. else { this.expect(types.comma); }
  40279. if (allowEmpty && this.type === types.comma) {
  40280. elts.push(null);
  40281. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  40282. break
  40283. } else if (this.type === types.ellipsis) {
  40284. var rest = this.parseRestBinding();
  40285. this.parseBindingListItem(rest);
  40286. elts.push(rest);
  40287. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  40288. this.expect(close);
  40289. break
  40290. } else {
  40291. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  40292. this.parseBindingListItem(elem);
  40293. elts.push(elem);
  40294. }
  40295. }
  40296. return elts
  40297. };
  40298. pp$2.parseBindingListItem = function(param) {
  40299. return param
  40300. };
  40301. // Parses assignment pattern around given atom if possible.
  40302. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  40303. left = left || this.parseBindingAtom();
  40304. if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
  40305. var node = this.startNodeAt(startPos, startLoc);
  40306. node.left = left;
  40307. node.right = this.parseMaybeAssign();
  40308. return this.finishNode(node, "AssignmentPattern")
  40309. };
  40310. // The following three functions all verify that a node is an lvalue —
  40311. // something that can be bound, or assigned to. In order to do so, they perform
  40312. // a variety of checks:
  40313. //
  40314. // - Check that none of the bound/assigned-to identifiers are reserved words.
  40315. // - Record name declarations for bindings in the appropriate scope.
  40316. // - Check duplicate argument names, if checkClashes is set.
  40317. //
  40318. // If a complex binding pattern is encountered (e.g., object and array
  40319. // destructuring), the entire pattern is recursively checked.
  40320. //
  40321. // There are three versions of checkLVal*() appropriate for different
  40322. // circumstances:
  40323. //
  40324. // - checkLValSimple() shall be used if the syntactic construct supports
  40325. // nothing other than identifiers and member expressions. Parenthesized
  40326. // expressions are also correctly handled. This is generally appropriate for
  40327. // constructs for which the spec says
  40328. //
  40329. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  40330. // > simple.
  40331. //
  40332. // It is also appropriate for checking if an identifier is valid and not
  40333. // defined elsewhere, like import declarations or function/class identifiers.
  40334. //
  40335. // Examples where this is used include:
  40336. // a += …;
  40337. // import a from '…';
  40338. // where a is the node to be checked.
  40339. //
  40340. // - checkLValPattern() shall be used if the syntactic construct supports
  40341. // anything checkLValSimple() supports, as well as object and array
  40342. // destructuring patterns. This is generally appropriate for constructs for
  40343. // which the spec says
  40344. //
  40345. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  40346. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  40347. // > simple.
  40348. //
  40349. // Examples where this is used include:
  40350. // (a = …);
  40351. // const a = …;
  40352. // try { … } catch (a) { … }
  40353. // where a is the node to be checked.
  40354. //
  40355. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  40356. // anything checkLValPattern() supports, as well as default assignment
  40357. // patterns, rest elements, and other constructs that may appear within an
  40358. // object or array destructuring pattern.
  40359. //
  40360. // As a special case, function parameters also use checkLValInnerPattern(),
  40361. // as they also support defaults and rest constructs.
  40362. //
  40363. // These functions deliberately support both assignment and binding constructs,
  40364. // as the logic for both is exceedingly similar. If the node is the target of
  40365. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  40366. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  40367. // BIND_LEXICAL.
  40368. //
  40369. // If the function is called with a non-BIND_NONE bindingType, then
  40370. // additionally a checkClashes object may be specified to allow checking for
  40371. // duplicate argument names. checkClashes is ignored if the provided construct
  40372. // is an assignment (i.e., bindingType is BIND_NONE).
  40373. pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
  40374. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  40375. var isBind = bindingType !== BIND_NONE;
  40376. switch (expr.type) {
  40377. case "Identifier":
  40378. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  40379. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  40380. if (isBind) {
  40381. if (bindingType === BIND_LEXICAL && expr.name === "let")
  40382. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  40383. if (checkClashes) {
  40384. if (has$1(checkClashes, expr.name))
  40385. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  40386. checkClashes[expr.name] = true;
  40387. }
  40388. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  40389. }
  40390. break
  40391. case "ChainExpression":
  40392. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  40393. break
  40394. case "MemberExpression":
  40395. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  40396. break
  40397. case "ParenthesizedExpression":
  40398. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  40399. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  40400. default:
  40401. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  40402. }
  40403. };
  40404. pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
  40405. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  40406. switch (expr.type) {
  40407. case "ObjectPattern":
  40408. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  40409. var prop = list[i];
  40410. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  40411. }
  40412. break
  40413. case "ArrayPattern":
  40414. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  40415. var elem = list$1[i$1];
  40416. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  40417. }
  40418. break
  40419. default:
  40420. this.checkLValSimple(expr, bindingType, checkClashes);
  40421. }
  40422. };
  40423. pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  40424. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  40425. switch (expr.type) {
  40426. case "Property":
  40427. // AssignmentProperty has type === "Property"
  40428. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  40429. break
  40430. case "AssignmentPattern":
  40431. this.checkLValPattern(expr.left, bindingType, checkClashes);
  40432. break
  40433. case "RestElement":
  40434. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  40435. break
  40436. default:
  40437. this.checkLValPattern(expr, bindingType, checkClashes);
  40438. }
  40439. };
  40440. // A recursive descent parser operates by defining functions for all
  40441. var pp$3 = Parser.prototype;
  40442. // Check if property name clashes with already added.
  40443. // Object/class getters and setters are not allowed to clash —
  40444. // either with each other or with an init property — and in
  40445. // strict mode, init properties are also not allowed to be repeated.
  40446. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  40447. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  40448. { return }
  40449. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  40450. { return }
  40451. var key = prop.key;
  40452. var name;
  40453. switch (key.type) {
  40454. case "Identifier": name = key.name; break
  40455. case "Literal": name = String(key.value); break
  40456. default: return
  40457. }
  40458. var kind = prop.kind;
  40459. if (this.options.ecmaVersion >= 6) {
  40460. if (name === "__proto__" && kind === "init") {
  40461. if (propHash.proto) {
  40462. if (refDestructuringErrors) {
  40463. if (refDestructuringErrors.doubleProto < 0)
  40464. { refDestructuringErrors.doubleProto = key.start; }
  40465. // Backwards-compat kludge. Can be removed in version 6.0
  40466. } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  40467. }
  40468. propHash.proto = true;
  40469. }
  40470. return
  40471. }
  40472. name = "$" + name;
  40473. var other = propHash[name];
  40474. if (other) {
  40475. var redefinition;
  40476. if (kind === "init") {
  40477. redefinition = this.strict && other.init || other.get || other.set;
  40478. } else {
  40479. redefinition = other.init || other[kind];
  40480. }
  40481. if (redefinition)
  40482. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  40483. } else {
  40484. other = propHash[name] = {
  40485. init: false,
  40486. get: false,
  40487. set: false
  40488. };
  40489. }
  40490. other[kind] = true;
  40491. };
  40492. // ### Expression parsing
  40493. // These nest, from the most general expression type at the top to
  40494. // 'atomic', nondivisible expression types at the bottom. Most of
  40495. // the functions will simply let the function(s) below them parse,
  40496. // and, *if* the syntactic construct they handle is present, wrap
  40497. // the AST node that the inner parser gave them in another node.
  40498. // Parse a full expression. The optional arguments are used to
  40499. // forbid the `in` operator (in for loops initalization expressions)
  40500. // and provide reference for storing '=' operator inside shorthand
  40501. // property assignment in contexts where both object expression
  40502. // and object pattern might appear (so it's possible to raise
  40503. // delayed syntax error at correct position).
  40504. pp$3.parseExpression = function(forInit, refDestructuringErrors) {
  40505. var startPos = this.start, startLoc = this.startLoc;
  40506. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  40507. if (this.type === types.comma) {
  40508. var node = this.startNodeAt(startPos, startLoc);
  40509. node.expressions = [expr];
  40510. while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  40511. return this.finishNode(node, "SequenceExpression")
  40512. }
  40513. return expr
  40514. };
  40515. // Parse an assignment expression. This includes applications of
  40516. // operators like `+=`.
  40517. pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  40518. if (this.isContextual("yield")) {
  40519. if (this.inGenerator) { return this.parseYield(forInit) }
  40520. // The tokenizer will assume an expression is allowed after
  40521. // `yield`, but this isn't that kind of yield
  40522. else { this.exprAllowed = false; }
  40523. }
  40524. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  40525. if (refDestructuringErrors) {
  40526. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  40527. oldTrailingComma = refDestructuringErrors.trailingComma;
  40528. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  40529. } else {
  40530. refDestructuringErrors = new DestructuringErrors;
  40531. ownDestructuringErrors = true;
  40532. }
  40533. var startPos = this.start, startLoc = this.startLoc;
  40534. if (this.type === types.parenL || this.type === types.name) {
  40535. this.potentialArrowAt = this.start;
  40536. this.potentialArrowInForAwait = forInit === "await";
  40537. }
  40538. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  40539. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  40540. if (this.type.isAssign) {
  40541. var node = this.startNodeAt(startPos, startLoc);
  40542. node.operator = this.value;
  40543. if (this.type === types.eq)
  40544. { left = this.toAssignable(left, false, refDestructuringErrors); }
  40545. if (!ownDestructuringErrors) {
  40546. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  40547. }
  40548. if (refDestructuringErrors.shorthandAssign >= left.start)
  40549. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  40550. if (this.type === types.eq)
  40551. { this.checkLValPattern(left); }
  40552. else
  40553. { this.checkLValSimple(left); }
  40554. node.left = left;
  40555. this.next();
  40556. node.right = this.parseMaybeAssign(forInit);
  40557. return this.finishNode(node, "AssignmentExpression")
  40558. } else {
  40559. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  40560. }
  40561. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  40562. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  40563. return left
  40564. };
  40565. // Parse a ternary conditional (`?:`) operator.
  40566. pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  40567. var startPos = this.start, startLoc = this.startLoc;
  40568. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  40569. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  40570. if (this.eat(types.question)) {
  40571. var node = this.startNodeAt(startPos, startLoc);
  40572. node.test = expr;
  40573. node.consequent = this.parseMaybeAssign();
  40574. this.expect(types.colon);
  40575. node.alternate = this.parseMaybeAssign(forInit);
  40576. return this.finishNode(node, "ConditionalExpression")
  40577. }
  40578. return expr
  40579. };
  40580. // Start the precedence parser.
  40581. pp$3.parseExprOps = function(forInit, refDestructuringErrors) {
  40582. var startPos = this.start, startLoc = this.startLoc;
  40583. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  40584. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  40585. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  40586. };
  40587. // Parse binary operators with the operator precedence parsing
  40588. // algorithm. `left` is the left-hand side of the operator.
  40589. // `minPrec` provides context that allows the function to stop and
  40590. // defer further parser to one of its callers when it encounters an
  40591. // operator that has a lower precedence than the set it is parsing.
  40592. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  40593. var prec = this.type.binop;
  40594. if (prec != null && (!forInit || this.type !== types._in)) {
  40595. if (prec > minPrec) {
  40596. var logical = this.type === types.logicalOR || this.type === types.logicalAND;
  40597. var coalesce = this.type === types.coalesce;
  40598. if (coalesce) {
  40599. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  40600. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  40601. prec = types.logicalAND.binop;
  40602. }
  40603. var op = this.value;
  40604. this.next();
  40605. var startPos = this.start, startLoc = this.startLoc;
  40606. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);
  40607. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  40608. if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
  40609. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  40610. }
  40611. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  40612. }
  40613. }
  40614. return left
  40615. };
  40616. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  40617. var node = this.startNodeAt(startPos, startLoc);
  40618. node.left = left;
  40619. node.operator = op;
  40620. node.right = right;
  40621. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  40622. };
  40623. // Parse unary operators, both prefix and postfix.
  40624. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
  40625. var startPos = this.start, startLoc = this.startLoc, expr;
  40626. if (this.isContextual("await") && this.canAwait) {
  40627. expr = this.parseAwait();
  40628. sawUnary = true;
  40629. } else if (this.type.prefix) {
  40630. var node = this.startNode(), update = this.type === types.incDec;
  40631. node.operator = this.value;
  40632. node.prefix = true;
  40633. this.next();
  40634. node.argument = this.parseMaybeUnary(null, true, update);
  40635. this.checkExpressionErrors(refDestructuringErrors, true);
  40636. if (update) { this.checkLValSimple(node.argument); }
  40637. else if (this.strict && node.operator === "delete" &&
  40638. node.argument.type === "Identifier")
  40639. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  40640. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  40641. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  40642. else { sawUnary = true; }
  40643. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  40644. } else {
  40645. expr = this.parseExprSubscripts(refDestructuringErrors);
  40646. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  40647. while (this.type.postfix && !this.canInsertSemicolon()) {
  40648. var node$1 = this.startNodeAt(startPos, startLoc);
  40649. node$1.operator = this.value;
  40650. node$1.prefix = false;
  40651. node$1.argument = expr;
  40652. this.checkLValSimple(expr);
  40653. this.next();
  40654. expr = this.finishNode(node$1, "UpdateExpression");
  40655. }
  40656. }
  40657. if (!incDec && this.eat(types.starstar)) {
  40658. if (sawUnary)
  40659. { this.unexpected(this.lastTokStart); }
  40660. else
  40661. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  40662. } else {
  40663. return expr
  40664. }
  40665. };
  40666. function isPrivateFieldAccess(node) {
  40667. return (
  40668. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  40669. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  40670. )
  40671. }
  40672. // Parse call, dot, and `[]`-subscript expressions.
  40673. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  40674. var startPos = this.start, startLoc = this.startLoc;
  40675. var expr = this.parseExprAtom(refDestructuringErrors);
  40676. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  40677. { return expr }
  40678. var result = this.parseSubscripts(expr, startPos, startLoc);
  40679. if (refDestructuringErrors && result.type === "MemberExpression") {
  40680. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  40681. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  40682. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  40683. }
  40684. return result
  40685. };
  40686. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  40687. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  40688. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  40689. this.potentialArrowAt === base.start;
  40690. var optionalChained = false;
  40691. while (true) {
  40692. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
  40693. if (element.optional) { optionalChained = true; }
  40694. if (element === base || element.type === "ArrowFunctionExpression") {
  40695. if (optionalChained) {
  40696. var chainNode = this.startNodeAt(startPos, startLoc);
  40697. chainNode.expression = element;
  40698. element = this.finishNode(chainNode, "ChainExpression");
  40699. }
  40700. return element
  40701. }
  40702. base = element;
  40703. }
  40704. };
  40705. pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  40706. var optionalSupported = this.options.ecmaVersion >= 11;
  40707. var optional = optionalSupported && this.eat(types.questionDot);
  40708. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  40709. var computed = this.eat(types.bracketL);
  40710. if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
  40711. var node = this.startNodeAt(startPos, startLoc);
  40712. node.object = base;
  40713. if (computed) {
  40714. node.property = this.parseExpression();
  40715. this.expect(types.bracketR);
  40716. } else if (this.type === types.privateId && base.type !== "Super") {
  40717. node.property = this.parsePrivateIdent();
  40718. } else {
  40719. node.property = this.parseIdent(this.options.allowReserved !== "never");
  40720. }
  40721. node.computed = !!computed;
  40722. if (optionalSupported) {
  40723. node.optional = optional;
  40724. }
  40725. base = this.finishNode(node, "MemberExpression");
  40726. } else if (!noCalls && this.eat(types.parenL)) {
  40727. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  40728. this.yieldPos = 0;
  40729. this.awaitPos = 0;
  40730. this.awaitIdentPos = 0;
  40731. var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  40732. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  40733. this.checkPatternErrors(refDestructuringErrors, false);
  40734. this.checkYieldAwaitInDefaultParams();
  40735. if (this.awaitIdentPos > 0)
  40736. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  40737. this.yieldPos = oldYieldPos;
  40738. this.awaitPos = oldAwaitPos;
  40739. this.awaitIdentPos = oldAwaitIdentPos;
  40740. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  40741. }
  40742. this.checkExpressionErrors(refDestructuringErrors, true);
  40743. this.yieldPos = oldYieldPos || this.yieldPos;
  40744. this.awaitPos = oldAwaitPos || this.awaitPos;
  40745. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  40746. var node$1 = this.startNodeAt(startPos, startLoc);
  40747. node$1.callee = base;
  40748. node$1.arguments = exprList;
  40749. if (optionalSupported) {
  40750. node$1.optional = optional;
  40751. }
  40752. base = this.finishNode(node$1, "CallExpression");
  40753. } else if (this.type === types.backQuote) {
  40754. if (optional || optionalChained) {
  40755. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  40756. }
  40757. var node$2 = this.startNodeAt(startPos, startLoc);
  40758. node$2.tag = base;
  40759. node$2.quasi = this.parseTemplate({isTagged: true});
  40760. base = this.finishNode(node$2, "TaggedTemplateExpression");
  40761. }
  40762. return base
  40763. };
  40764. // Parse an atomic expression — either a single token that is an
  40765. // expression, an expression started by a keyword like `function` or
  40766. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  40767. // or `{}`.
  40768. pp$3.parseExprAtom = function(refDestructuringErrors) {
  40769. // If a division operator appears in an expression position, the
  40770. // tokenizer got confused, and we force it to read a regexp instead.
  40771. if (this.type === types.slash) { this.readRegexp(); }
  40772. var node, canBeArrow = this.potentialArrowAt === this.start;
  40773. switch (this.type) {
  40774. case types._super:
  40775. if (!this.allowSuper)
  40776. { this.raise(this.start, "'super' keyword outside a method"); }
  40777. node = this.startNode();
  40778. this.next();
  40779. if (this.type === types.parenL && !this.allowDirectSuper)
  40780. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  40781. // The `super` keyword can appear at below:
  40782. // SuperProperty:
  40783. // super [ Expression ]
  40784. // super . IdentifierName
  40785. // SuperCall:
  40786. // super ( Arguments )
  40787. if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
  40788. { this.unexpected(); }
  40789. return this.finishNode(node, "Super")
  40790. case types._this:
  40791. node = this.startNode();
  40792. this.next();
  40793. return this.finishNode(node, "ThisExpression")
  40794. case types.name:
  40795. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  40796. var id = this.parseIdent(false);
  40797. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
  40798. { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
  40799. if (canBeArrow && !this.canInsertSemicolon()) {
  40800. if (this.eat(types.arrow))
  40801. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  40802. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc &&
  40803. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  40804. id = this.parseIdent(false);
  40805. if (this.canInsertSemicolon() || !this.eat(types.arrow))
  40806. { this.unexpected(); }
  40807. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  40808. }
  40809. }
  40810. return id
  40811. case types.regexp:
  40812. var value = this.value;
  40813. node = this.parseLiteral(value.value);
  40814. node.regex = {pattern: value.pattern, flags: value.flags};
  40815. return node
  40816. case types.num: case types.string:
  40817. return this.parseLiteral(this.value)
  40818. case types._null: case types._true: case types._false:
  40819. node = this.startNode();
  40820. node.value = this.type === types._null ? null : this.type === types._true;
  40821. node.raw = this.type.keyword;
  40822. this.next();
  40823. return this.finishNode(node, "Literal")
  40824. case types.parenL:
  40825. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  40826. if (refDestructuringErrors) {
  40827. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  40828. { refDestructuringErrors.parenthesizedAssign = start; }
  40829. if (refDestructuringErrors.parenthesizedBind < 0)
  40830. { refDestructuringErrors.parenthesizedBind = start; }
  40831. }
  40832. return expr
  40833. case types.bracketL:
  40834. node = this.startNode();
  40835. this.next();
  40836. node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
  40837. return this.finishNode(node, "ArrayExpression")
  40838. case types.braceL:
  40839. return this.parseObj(false, refDestructuringErrors)
  40840. case types._function:
  40841. node = this.startNode();
  40842. this.next();
  40843. return this.parseFunction(node, 0)
  40844. case types._class:
  40845. return this.parseClass(this.startNode(), false)
  40846. case types._new:
  40847. return this.parseNew()
  40848. case types.backQuote:
  40849. return this.parseTemplate()
  40850. case types._import:
  40851. if (this.options.ecmaVersion >= 11) {
  40852. return this.parseExprImport()
  40853. } else {
  40854. return this.unexpected()
  40855. }
  40856. default:
  40857. this.unexpected();
  40858. }
  40859. };
  40860. pp$3.parseExprImport = function() {
  40861. var node = this.startNode();
  40862. // Consume `import` as an identifier for `import.meta`.
  40863. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  40864. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  40865. var meta = this.parseIdent(true);
  40866. switch (this.type) {
  40867. case types.parenL:
  40868. return this.parseDynamicImport(node)
  40869. case types.dot:
  40870. node.meta = meta;
  40871. return this.parseImportMeta(node)
  40872. default:
  40873. this.unexpected();
  40874. }
  40875. };
  40876. pp$3.parseDynamicImport = function(node) {
  40877. this.next(); // skip `(`
  40878. // Parse node.source.
  40879. node.source = this.parseMaybeAssign();
  40880. // Verify ending.
  40881. if (!this.eat(types.parenR)) {
  40882. var errorPos = this.start;
  40883. if (this.eat(types.comma) && this.eat(types.parenR)) {
  40884. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  40885. } else {
  40886. this.unexpected(errorPos);
  40887. }
  40888. }
  40889. return this.finishNode(node, "ImportExpression")
  40890. };
  40891. pp$3.parseImportMeta = function(node) {
  40892. this.next(); // skip `.`
  40893. var containsEsc = this.containsEsc;
  40894. node.property = this.parseIdent(true);
  40895. if (node.property.name !== "meta")
  40896. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  40897. if (containsEsc)
  40898. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  40899. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  40900. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  40901. return this.finishNode(node, "MetaProperty")
  40902. };
  40903. pp$3.parseLiteral = function(value) {
  40904. var node = this.startNode();
  40905. node.value = value;
  40906. node.raw = this.input.slice(this.start, this.end);
  40907. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  40908. this.next();
  40909. return this.finishNode(node, "Literal")
  40910. };
  40911. pp$3.parseParenExpression = function() {
  40912. this.expect(types.parenL);
  40913. var val = this.parseExpression();
  40914. this.expect(types.parenR);
  40915. return val
  40916. };
  40917. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  40918. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  40919. if (this.options.ecmaVersion >= 6) {
  40920. this.next();
  40921. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  40922. var exprList = [], first = true, lastIsComma = false;
  40923. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  40924. this.yieldPos = 0;
  40925. this.awaitPos = 0;
  40926. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  40927. while (this.type !== types.parenR) {
  40928. first ? first = false : this.expect(types.comma);
  40929. if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
  40930. lastIsComma = true;
  40931. break
  40932. } else if (this.type === types.ellipsis) {
  40933. spreadStart = this.start;
  40934. exprList.push(this.parseParenItem(this.parseRestBinding()));
  40935. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  40936. break
  40937. } else {
  40938. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  40939. }
  40940. }
  40941. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  40942. this.expect(types.parenR);
  40943. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  40944. this.checkPatternErrors(refDestructuringErrors, false);
  40945. this.checkYieldAwaitInDefaultParams();
  40946. this.yieldPos = oldYieldPos;
  40947. this.awaitPos = oldAwaitPos;
  40948. return this.parseParenArrowList(startPos, startLoc, exprList)
  40949. }
  40950. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  40951. if (spreadStart) { this.unexpected(spreadStart); }
  40952. this.checkExpressionErrors(refDestructuringErrors, true);
  40953. this.yieldPos = oldYieldPos || this.yieldPos;
  40954. this.awaitPos = oldAwaitPos || this.awaitPos;
  40955. if (exprList.length > 1) {
  40956. val = this.startNodeAt(innerStartPos, innerStartLoc);
  40957. val.expressions = exprList;
  40958. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  40959. } else {
  40960. val = exprList[0];
  40961. }
  40962. } else {
  40963. val = this.parseParenExpression();
  40964. }
  40965. if (this.options.preserveParens) {
  40966. var par = this.startNodeAt(startPos, startLoc);
  40967. par.expression = val;
  40968. return this.finishNode(par, "ParenthesizedExpression")
  40969. } else {
  40970. return val
  40971. }
  40972. };
  40973. pp$3.parseParenItem = function(item) {
  40974. return item
  40975. };
  40976. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  40977. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  40978. };
  40979. // New's precedence is slightly tricky. It must allow its argument to
  40980. // be a `[]` or dot subscript expression, but not a call — at least,
  40981. // not without wrapping it in parentheses. Thus, it uses the noCalls
  40982. // argument to parseSubscripts to prevent it from consuming the
  40983. // argument list.
  40984. var empty$1 = [];
  40985. pp$3.parseNew = function() {
  40986. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  40987. var node = this.startNode();
  40988. var meta = this.parseIdent(true);
  40989. if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
  40990. node.meta = meta;
  40991. var containsEsc = this.containsEsc;
  40992. node.property = this.parseIdent(true);
  40993. if (node.property.name !== "target")
  40994. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  40995. if (containsEsc)
  40996. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  40997. if (!this.inNonArrowFunction)
  40998. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
  40999. return this.finishNode(node, "MetaProperty")
  41000. }
  41001. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
  41002. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  41003. if (isImport && node.callee.type === "ImportExpression") {
  41004. this.raise(startPos, "Cannot use new with import()");
  41005. }
  41006. if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
  41007. else { node.arguments = empty$1; }
  41008. return this.finishNode(node, "NewExpression")
  41009. };
  41010. // Parse template expression.
  41011. pp$3.parseTemplateElement = function(ref) {
  41012. var isTagged = ref.isTagged;
  41013. var elem = this.startNode();
  41014. if (this.type === types.invalidTemplate) {
  41015. if (!isTagged) {
  41016. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  41017. }
  41018. elem.value = {
  41019. raw: this.value,
  41020. cooked: null
  41021. };
  41022. } else {
  41023. elem.value = {
  41024. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  41025. cooked: this.value
  41026. };
  41027. }
  41028. this.next();
  41029. elem.tail = this.type === types.backQuote;
  41030. return this.finishNode(elem, "TemplateElement")
  41031. };
  41032. pp$3.parseTemplate = function(ref) {
  41033. if ( ref === void 0 ) ref = {};
  41034. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  41035. var node = this.startNode();
  41036. this.next();
  41037. node.expressions = [];
  41038. var curElt = this.parseTemplateElement({isTagged: isTagged});
  41039. node.quasis = [curElt];
  41040. while (!curElt.tail) {
  41041. if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
  41042. this.expect(types.dollarBraceL);
  41043. node.expressions.push(this.parseExpression());
  41044. this.expect(types.braceR);
  41045. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  41046. }
  41047. this.next();
  41048. return this.finishNode(node, "TemplateLiteral")
  41049. };
  41050. pp$3.isAsyncProp = function(prop) {
  41051. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  41052. (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
  41053. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  41054. };
  41055. // Parse an object literal or binding pattern.
  41056. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  41057. var node = this.startNode(), first = true, propHash = {};
  41058. node.properties = [];
  41059. this.next();
  41060. while (!this.eat(types.braceR)) {
  41061. if (!first) {
  41062. this.expect(types.comma);
  41063. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
  41064. } else { first = false; }
  41065. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  41066. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  41067. node.properties.push(prop);
  41068. }
  41069. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  41070. };
  41071. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  41072. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  41073. if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
  41074. if (isPattern) {
  41075. prop.argument = this.parseIdent(false);
  41076. if (this.type === types.comma) {
  41077. this.raise(this.start, "Comma is not permitted after the rest element");
  41078. }
  41079. return this.finishNode(prop, "RestElement")
  41080. }
  41081. // To disallow parenthesized identifier via `this.toAssignable()`.
  41082. if (this.type === types.parenL && refDestructuringErrors) {
  41083. if (refDestructuringErrors.parenthesizedAssign < 0) {
  41084. refDestructuringErrors.parenthesizedAssign = this.start;
  41085. }
  41086. if (refDestructuringErrors.parenthesizedBind < 0) {
  41087. refDestructuringErrors.parenthesizedBind = this.start;
  41088. }
  41089. }
  41090. // Parse argument.
  41091. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  41092. // To disallow trailing comma via `this.toAssignable()`.
  41093. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  41094. refDestructuringErrors.trailingComma = this.start;
  41095. }
  41096. // Finish
  41097. return this.finishNode(prop, "SpreadElement")
  41098. }
  41099. if (this.options.ecmaVersion >= 6) {
  41100. prop.method = false;
  41101. prop.shorthand = false;
  41102. if (isPattern || refDestructuringErrors) {
  41103. startPos = this.start;
  41104. startLoc = this.startLoc;
  41105. }
  41106. if (!isPattern)
  41107. { isGenerator = this.eat(types.star); }
  41108. }
  41109. var containsEsc = this.containsEsc;
  41110. this.parsePropertyName(prop);
  41111. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  41112. isAsync = true;
  41113. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  41114. this.parsePropertyName(prop, refDestructuringErrors);
  41115. } else {
  41116. isAsync = false;
  41117. }
  41118. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  41119. return this.finishNode(prop, "Property")
  41120. };
  41121. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  41122. if ((isGenerator || isAsync) && this.type === types.colon)
  41123. { this.unexpected(); }
  41124. if (this.eat(types.colon)) {
  41125. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  41126. prop.kind = "init";
  41127. } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
  41128. if (isPattern) { this.unexpected(); }
  41129. prop.kind = "init";
  41130. prop.method = true;
  41131. prop.value = this.parseMethod(isGenerator, isAsync);
  41132. } else if (!isPattern && !containsEsc &&
  41133. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  41134. (prop.key.name === "get" || prop.key.name === "set") &&
  41135. (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
  41136. if (isGenerator || isAsync) { this.unexpected(); }
  41137. prop.kind = prop.key.name;
  41138. this.parsePropertyName(prop);
  41139. prop.value = this.parseMethod(false);
  41140. var paramCount = prop.kind === "get" ? 0 : 1;
  41141. if (prop.value.params.length !== paramCount) {
  41142. var start = prop.value.start;
  41143. if (prop.kind === "get")
  41144. { this.raiseRecoverable(start, "getter should have no params"); }
  41145. else
  41146. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  41147. } else {
  41148. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  41149. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  41150. }
  41151. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  41152. if (isGenerator || isAsync) { this.unexpected(); }
  41153. this.checkUnreserved(prop.key);
  41154. if (prop.key.name === "await" && !this.awaitIdentPos)
  41155. { this.awaitIdentPos = startPos; }
  41156. prop.kind = "init";
  41157. if (isPattern) {
  41158. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  41159. } else if (this.type === types.eq && refDestructuringErrors) {
  41160. if (refDestructuringErrors.shorthandAssign < 0)
  41161. { refDestructuringErrors.shorthandAssign = this.start; }
  41162. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  41163. } else {
  41164. prop.value = this.copyNode(prop.key);
  41165. }
  41166. prop.shorthand = true;
  41167. } else { this.unexpected(); }
  41168. };
  41169. pp$3.parsePropertyName = function(prop) {
  41170. if (this.options.ecmaVersion >= 6) {
  41171. if (this.eat(types.bracketL)) {
  41172. prop.computed = true;
  41173. prop.key = this.parseMaybeAssign();
  41174. this.expect(types.bracketR);
  41175. return prop.key
  41176. } else {
  41177. prop.computed = false;
  41178. }
  41179. }
  41180. return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  41181. };
  41182. // Initialize empty function node.
  41183. pp$3.initFunction = function(node) {
  41184. node.id = null;
  41185. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  41186. if (this.options.ecmaVersion >= 8) { node.async = false; }
  41187. };
  41188. // Parse object or class method.
  41189. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  41190. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  41191. this.initFunction(node);
  41192. if (this.options.ecmaVersion >= 6)
  41193. { node.generator = isGenerator; }
  41194. if (this.options.ecmaVersion >= 8)
  41195. { node.async = !!isAsync; }
  41196. this.yieldPos = 0;
  41197. this.awaitPos = 0;
  41198. this.awaitIdentPos = 0;
  41199. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  41200. this.expect(types.parenL);
  41201. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  41202. this.checkYieldAwaitInDefaultParams();
  41203. this.parseFunctionBody(node, false, true);
  41204. this.yieldPos = oldYieldPos;
  41205. this.awaitPos = oldAwaitPos;
  41206. this.awaitIdentPos = oldAwaitIdentPos;
  41207. return this.finishNode(node, "FunctionExpression")
  41208. };
  41209. // Parse arrow function expression with given parameters.
  41210. pp$3.parseArrowExpression = function(node, params, isAsync) {
  41211. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  41212. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  41213. this.initFunction(node);
  41214. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  41215. this.yieldPos = 0;
  41216. this.awaitPos = 0;
  41217. this.awaitIdentPos = 0;
  41218. node.params = this.toAssignableList(params, true);
  41219. this.parseFunctionBody(node, true, false);
  41220. this.yieldPos = oldYieldPos;
  41221. this.awaitPos = oldAwaitPos;
  41222. this.awaitIdentPos = oldAwaitIdentPos;
  41223. return this.finishNode(node, "ArrowFunctionExpression")
  41224. };
  41225. // Parse function body and check parameters.
  41226. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  41227. var isExpression = isArrowFunction && this.type !== types.braceL;
  41228. var oldStrict = this.strict, useStrict = false;
  41229. if (isExpression) {
  41230. node.body = this.parseMaybeAssign();
  41231. node.expression = true;
  41232. this.checkParams(node, false);
  41233. } else {
  41234. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  41235. if (!oldStrict || nonSimple) {
  41236. useStrict = this.strictDirective(this.end);
  41237. // If this is a strict mode function, verify that argument names
  41238. // are not repeated, and it does not try to bind the words `eval`
  41239. // or `arguments`.
  41240. if (useStrict && nonSimple)
  41241. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  41242. }
  41243. // Start a new scope with regard to labels and the `inFunction`
  41244. // flag (restore them to their old value afterwards).
  41245. var oldLabels = this.labels;
  41246. this.labels = [];
  41247. if (useStrict) { this.strict = true; }
  41248. // Add the params to varDeclaredNames to ensure that an error is thrown
  41249. // if a let/const declaration in the function clashes with one of the params.
  41250. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  41251. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  41252. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  41253. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  41254. node.expression = false;
  41255. this.adaptDirectivePrologue(node.body.body);
  41256. this.labels = oldLabels;
  41257. }
  41258. this.exitScope();
  41259. };
  41260. pp$3.isSimpleParamList = function(params) {
  41261. for (var i = 0, list = params; i < list.length; i += 1)
  41262. {
  41263. var param = list[i];
  41264. if (param.type !== "Identifier") { return false
  41265. } }
  41266. return true
  41267. };
  41268. // Checks function params for various disallowed patterns such as using "eval"
  41269. // or "arguments" and duplicate parameters.
  41270. pp$3.checkParams = function(node, allowDuplicates) {
  41271. var nameHash = Object.create(null);
  41272. for (var i = 0, list = node.params; i < list.length; i += 1)
  41273. {
  41274. var param = list[i];
  41275. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  41276. }
  41277. };
  41278. // Parses a comma-separated list of expressions, and returns them as
  41279. // an array. `close` is the token type that ends the list, and
  41280. // `allowEmpty` can be turned on to allow subsequent commas with
  41281. // nothing in between them to be parsed as `null` (which is needed
  41282. // for array literals).
  41283. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  41284. var elts = [], first = true;
  41285. while (!this.eat(close)) {
  41286. if (!first) {
  41287. this.expect(types.comma);
  41288. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  41289. } else { first = false; }
  41290. var elt = (void 0);
  41291. if (allowEmpty && this.type === types.comma)
  41292. { elt = null; }
  41293. else if (this.type === types.ellipsis) {
  41294. elt = this.parseSpread(refDestructuringErrors);
  41295. if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
  41296. { refDestructuringErrors.trailingComma = this.start; }
  41297. } else {
  41298. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  41299. }
  41300. elts.push(elt);
  41301. }
  41302. return elts
  41303. };
  41304. pp$3.checkUnreserved = function(ref) {
  41305. var start = ref.start;
  41306. var end = ref.end;
  41307. var name = ref.name;
  41308. if (this.inGenerator && name === "yield")
  41309. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  41310. if (this.inAsync && name === "await")
  41311. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  41312. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  41313. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  41314. if (this.keywords.test(name))
  41315. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  41316. if (this.options.ecmaVersion < 6 &&
  41317. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  41318. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  41319. if (re.test(name)) {
  41320. if (!this.inAsync && name === "await")
  41321. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  41322. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  41323. }
  41324. };
  41325. // Parse the next token as an identifier. If `liberal` is true (used
  41326. // when parsing properties), it will also convert keywords into
  41327. // identifiers.
  41328. pp$3.parseIdent = function(liberal, isBinding) {
  41329. var node = this.startNode();
  41330. if (this.type === types.name) {
  41331. node.name = this.value;
  41332. } else if (this.type.keyword) {
  41333. node.name = this.type.keyword;
  41334. // To fix https://github.com/acornjs/acorn/issues/575
  41335. // `class` and `function` keywords push new context into this.context.
  41336. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  41337. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  41338. if ((node.name === "class" || node.name === "function") &&
  41339. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  41340. this.context.pop();
  41341. }
  41342. } else {
  41343. this.unexpected();
  41344. }
  41345. this.next(!!liberal);
  41346. this.finishNode(node, "Identifier");
  41347. if (!liberal) {
  41348. this.checkUnreserved(node);
  41349. if (node.name === "await" && !this.awaitIdentPos)
  41350. { this.awaitIdentPos = node.start; }
  41351. }
  41352. return node
  41353. };
  41354. pp$3.parsePrivateIdent = function() {
  41355. var node = this.startNode();
  41356. if (this.type === types.privateId) {
  41357. node.name = this.value;
  41358. } else {
  41359. this.unexpected();
  41360. }
  41361. this.next();
  41362. this.finishNode(node, "PrivateIdentifier");
  41363. // For validating existence
  41364. if (this.privateNameStack.length === 0) {
  41365. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  41366. } else {
  41367. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  41368. }
  41369. return node
  41370. };
  41371. // Parses yield expression inside generator.
  41372. pp$3.parseYield = function(forInit) {
  41373. if (!this.yieldPos) { this.yieldPos = this.start; }
  41374. var node = this.startNode();
  41375. this.next();
  41376. if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
  41377. node.delegate = false;
  41378. node.argument = null;
  41379. } else {
  41380. node.delegate = this.eat(types.star);
  41381. node.argument = this.parseMaybeAssign(forInit);
  41382. }
  41383. return this.finishNode(node, "YieldExpression")
  41384. };
  41385. pp$3.parseAwait = function() {
  41386. if (!this.awaitPos) { this.awaitPos = this.start; }
  41387. var node = this.startNode();
  41388. this.next();
  41389. node.argument = this.parseMaybeUnary(null, true);
  41390. return this.finishNode(node, "AwaitExpression")
  41391. };
  41392. var pp$4 = Parser.prototype;
  41393. // This function is used to raise exceptions on parse errors. It
  41394. // takes an offset integer (into the current `input`) to indicate
  41395. // the location of the error, attaches the position to the end
  41396. // of the error message, and then raises a `SyntaxError` with that
  41397. // message.
  41398. pp$4.raise = function(pos, message) {
  41399. var loc = getLineInfo(this.input, pos);
  41400. message += " (" + loc.line + ":" + loc.column + ")";
  41401. var err = new SyntaxError(message);
  41402. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  41403. throw err
  41404. };
  41405. pp$4.raiseRecoverable = pp$4.raise;
  41406. pp$4.curPosition = function() {
  41407. if (this.options.locations) {
  41408. return new Position(this.curLine, this.pos - this.lineStart)
  41409. }
  41410. };
  41411. var pp$5 = Parser.prototype;
  41412. var Scope = function Scope(flags) {
  41413. this.flags = flags;
  41414. // A list of var-declared names in the current lexical scope
  41415. this.var = [];
  41416. // A list of lexically-declared names in the current lexical scope
  41417. this.lexical = [];
  41418. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  41419. this.functions = [];
  41420. // A switch to disallow the identifier reference 'arguments'
  41421. this.inClassFieldInit = false;
  41422. };
  41423. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  41424. pp$5.enterScope = function(flags) {
  41425. this.scopeStack.push(new Scope(flags));
  41426. };
  41427. pp$5.exitScope = function() {
  41428. this.scopeStack.pop();
  41429. };
  41430. // The spec says:
  41431. // > At the top level of a function, or script, function declarations are
  41432. // > treated like var declarations rather than like lexical declarations.
  41433. pp$5.treatFunctionsAsVarInScope = function(scope) {
  41434. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  41435. };
  41436. pp$5.declareName = function(name, bindingType, pos) {
  41437. var redeclared = false;
  41438. if (bindingType === BIND_LEXICAL) {
  41439. var scope = this.currentScope();
  41440. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  41441. scope.lexical.push(name);
  41442. if (this.inModule && (scope.flags & SCOPE_TOP))
  41443. { delete this.undefinedExports[name]; }
  41444. } else if (bindingType === BIND_SIMPLE_CATCH) {
  41445. var scope$1 = this.currentScope();
  41446. scope$1.lexical.push(name);
  41447. } else if (bindingType === BIND_FUNCTION) {
  41448. var scope$2 = this.currentScope();
  41449. if (this.treatFunctionsAsVar)
  41450. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  41451. else
  41452. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  41453. scope$2.functions.push(name);
  41454. } else {
  41455. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  41456. var scope$3 = this.scopeStack[i];
  41457. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  41458. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  41459. redeclared = true;
  41460. break
  41461. }
  41462. scope$3.var.push(name);
  41463. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  41464. { delete this.undefinedExports[name]; }
  41465. if (scope$3.flags & SCOPE_VAR) { break }
  41466. }
  41467. }
  41468. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  41469. };
  41470. pp$5.checkLocalExport = function(id) {
  41471. // scope.functions must be empty as Module code is always strict.
  41472. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  41473. this.scopeStack[0].var.indexOf(id.name) === -1) {
  41474. this.undefinedExports[id.name] = id;
  41475. }
  41476. };
  41477. pp$5.currentScope = function() {
  41478. return this.scopeStack[this.scopeStack.length - 1]
  41479. };
  41480. pp$5.currentVarScope = function() {
  41481. for (var i = this.scopeStack.length - 1;; i--) {
  41482. var scope = this.scopeStack[i];
  41483. if (scope.flags & SCOPE_VAR) { return scope }
  41484. }
  41485. };
  41486. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  41487. pp$5.currentThisScope = function() {
  41488. for (var i = this.scopeStack.length - 1;; i--) {
  41489. var scope = this.scopeStack[i];
  41490. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  41491. }
  41492. };
  41493. var Node = function Node(parser, pos, loc) {
  41494. this.type = "";
  41495. this.start = pos;
  41496. this.end = 0;
  41497. if (parser.options.locations)
  41498. { this.loc = new SourceLocation(parser, loc); }
  41499. if (parser.options.directSourceFile)
  41500. { this.sourceFile = parser.options.directSourceFile; }
  41501. if (parser.options.ranges)
  41502. { this.range = [pos, 0]; }
  41503. };
  41504. // Start an AST node, attaching a start offset.
  41505. var pp$6 = Parser.prototype;
  41506. pp$6.startNode = function() {
  41507. return new Node(this, this.start, this.startLoc)
  41508. };
  41509. pp$6.startNodeAt = function(pos, loc) {
  41510. return new Node(this, pos, loc)
  41511. };
  41512. // Finish an AST node, adding `type` and `end` properties.
  41513. function finishNodeAt(node, type, pos, loc) {
  41514. node.type = type;
  41515. node.end = pos;
  41516. if (this.options.locations)
  41517. { node.loc.end = loc; }
  41518. if (this.options.ranges)
  41519. { node.range[1] = pos; }
  41520. return node
  41521. }
  41522. pp$6.finishNode = function(node, type) {
  41523. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  41524. };
  41525. // Finish node at given position
  41526. pp$6.finishNodeAt = function(node, type, pos, loc) {
  41527. return finishNodeAt.call(this, node, type, pos, loc)
  41528. };
  41529. pp$6.copyNode = function(node) {
  41530. var newNode = new Node(this, node.start, this.startLoc);
  41531. for (var prop in node) { newNode[prop] = node[prop]; }
  41532. return newNode
  41533. };
  41534. // The algorithm used to determine whether a regexp can appear at a
  41535. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  41536. this.token = token;
  41537. this.isExpr = !!isExpr;
  41538. this.preserveSpace = !!preserveSpace;
  41539. this.override = override;
  41540. this.generator = !!generator;
  41541. };
  41542. var types$1 = {
  41543. b_stat: new TokContext("{", false),
  41544. b_expr: new TokContext("{", true),
  41545. b_tmpl: new TokContext("${", false),
  41546. p_stat: new TokContext("(", false),
  41547. p_expr: new TokContext("(", true),
  41548. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  41549. f_stat: new TokContext("function", false),
  41550. f_expr: new TokContext("function", true),
  41551. f_expr_gen: new TokContext("function", true, false, null, true),
  41552. f_gen: new TokContext("function", false, false, null, true)
  41553. };
  41554. var pp$7 = Parser.prototype;
  41555. pp$7.initialContext = function() {
  41556. return [types$1.b_stat]
  41557. };
  41558. pp$7.braceIsBlock = function(prevType) {
  41559. var parent = this.curContext();
  41560. if (parent === types$1.f_expr || parent === types$1.f_stat)
  41561. { return true }
  41562. if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
  41563. { return !parent.isExpr }
  41564. // The check for `tt.name && exprAllowed` detects whether we are
  41565. // after a `yield` or `of` construct. See the `updateContext` for
  41566. // `tt.name`.
  41567. if (prevType === types._return || prevType === types.name && this.exprAllowed)
  41568. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  41569. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
  41570. { return true }
  41571. if (prevType === types.braceL)
  41572. { return parent === types$1.b_stat }
  41573. if (prevType === types._var || prevType === types._const || prevType === types.name)
  41574. { return false }
  41575. return !this.exprAllowed
  41576. };
  41577. pp$7.inGeneratorContext = function() {
  41578. for (var i = this.context.length - 1; i >= 1; i--) {
  41579. var context = this.context[i];
  41580. if (context.token === "function")
  41581. { return context.generator }
  41582. }
  41583. return false
  41584. };
  41585. pp$7.updateContext = function(prevType) {
  41586. var update, type = this.type;
  41587. if (type.keyword && prevType === types.dot)
  41588. { this.exprAllowed = false; }
  41589. else if (update = type.updateContext)
  41590. { update.call(this, prevType); }
  41591. else
  41592. { this.exprAllowed = type.beforeExpr; }
  41593. };
  41594. // Token-specific context update code
  41595. types.parenR.updateContext = types.braceR.updateContext = function() {
  41596. if (this.context.length === 1) {
  41597. this.exprAllowed = true;
  41598. return
  41599. }
  41600. var out = this.context.pop();
  41601. if (out === types$1.b_stat && this.curContext().token === "function") {
  41602. out = this.context.pop();
  41603. }
  41604. this.exprAllowed = !out.isExpr;
  41605. };
  41606. types.braceL.updateContext = function(prevType) {
  41607. this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  41608. this.exprAllowed = true;
  41609. };
  41610. types.dollarBraceL.updateContext = function() {
  41611. this.context.push(types$1.b_tmpl);
  41612. this.exprAllowed = true;
  41613. };
  41614. types.parenL.updateContext = function(prevType) {
  41615. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  41616. this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  41617. this.exprAllowed = true;
  41618. };
  41619. types.incDec.updateContext = function() {
  41620. // tokExprAllowed stays unchanged
  41621. };
  41622. types._function.updateContext = types._class.updateContext = function(prevType) {
  41623. if (prevType.beforeExpr && prevType !== types._else &&
  41624. !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
  41625. !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  41626. !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
  41627. { this.context.push(types$1.f_expr); }
  41628. else
  41629. { this.context.push(types$1.f_stat); }
  41630. this.exprAllowed = false;
  41631. };
  41632. types.backQuote.updateContext = function() {
  41633. if (this.curContext() === types$1.q_tmpl)
  41634. { this.context.pop(); }
  41635. else
  41636. { this.context.push(types$1.q_tmpl); }
  41637. this.exprAllowed = false;
  41638. };
  41639. types.star.updateContext = function(prevType) {
  41640. if (prevType === types._function) {
  41641. var index = this.context.length - 1;
  41642. if (this.context[index] === types$1.f_expr)
  41643. { this.context[index] = types$1.f_expr_gen; }
  41644. else
  41645. { this.context[index] = types$1.f_gen; }
  41646. }
  41647. this.exprAllowed = true;
  41648. };
  41649. types.name.updateContext = function(prevType) {
  41650. var allowed = false;
  41651. if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
  41652. if (this.value === "of" && !this.exprAllowed ||
  41653. this.value === "yield" && this.inGeneratorContext())
  41654. { allowed = true; }
  41655. }
  41656. this.exprAllowed = allowed;
  41657. };
  41658. // This file contains Unicode properties extracted from the ECMAScript
  41659. // specification. The lists are extracted like so:
  41660. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  41661. // #table-binary-unicode-properties
  41662. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  41663. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  41664. var ecma11BinaryProperties = ecma10BinaryProperties;
  41665. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  41666. var unicodeBinaryProperties = {
  41667. 9: ecma9BinaryProperties,
  41668. 10: ecma10BinaryProperties,
  41669. 11: ecma11BinaryProperties,
  41670. 12: ecma12BinaryProperties
  41671. };
  41672. // #table-unicode-general-category-values
  41673. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  41674. // #table-unicode-script-values
  41675. var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  41676. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  41677. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  41678. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  41679. var unicodeScriptValues = {
  41680. 9: ecma9ScriptValues,
  41681. 10: ecma10ScriptValues,
  41682. 11: ecma11ScriptValues,
  41683. 12: ecma12ScriptValues
  41684. };
  41685. var data = {};
  41686. function buildUnicodeData(ecmaVersion) {
  41687. var d = data[ecmaVersion] = {
  41688. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  41689. nonBinary: {
  41690. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  41691. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  41692. }
  41693. };
  41694. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  41695. d.nonBinary.gc = d.nonBinary.General_Category;
  41696. d.nonBinary.sc = d.nonBinary.Script;
  41697. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  41698. }
  41699. buildUnicodeData(9);
  41700. buildUnicodeData(10);
  41701. buildUnicodeData(11);
  41702. buildUnicodeData(12);
  41703. var pp$8 = Parser.prototype;
  41704. var RegExpValidationState = function RegExpValidationState(parser) {
  41705. this.parser = parser;
  41706. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  41707. this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
  41708. this.source = "";
  41709. this.flags = "";
  41710. this.start = 0;
  41711. this.switchU = false;
  41712. this.switchN = false;
  41713. this.pos = 0;
  41714. this.lastIntValue = 0;
  41715. this.lastStringValue = "";
  41716. this.lastAssertionIsQuantifiable = false;
  41717. this.numCapturingParens = 0;
  41718. this.maxBackReference = 0;
  41719. this.groupNames = [];
  41720. this.backReferenceNames = [];
  41721. };
  41722. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  41723. var unicode = flags.indexOf("u") !== -1;
  41724. this.start = start | 0;
  41725. this.source = pattern + "";
  41726. this.flags = flags;
  41727. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  41728. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  41729. };
  41730. RegExpValidationState.prototype.raise = function raise (message) {
  41731. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  41732. };
  41733. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  41734. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  41735. RegExpValidationState.prototype.at = function at (i, forceU) {
  41736. if ( forceU === void 0 ) forceU = false;
  41737. var s = this.source;
  41738. var l = s.length;
  41739. if (i >= l) {
  41740. return -1
  41741. }
  41742. var c = s.charCodeAt(i);
  41743. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  41744. return c
  41745. }
  41746. var next = s.charCodeAt(i + 1);
  41747. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  41748. };
  41749. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  41750. if ( forceU === void 0 ) forceU = false;
  41751. var s = this.source;
  41752. var l = s.length;
  41753. if (i >= l) {
  41754. return l
  41755. }
  41756. var c = s.charCodeAt(i), next;
  41757. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  41758. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  41759. return i + 1
  41760. }
  41761. return i + 2
  41762. };
  41763. RegExpValidationState.prototype.current = function current (forceU) {
  41764. if ( forceU === void 0 ) forceU = false;
  41765. return this.at(this.pos, forceU)
  41766. };
  41767. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  41768. if ( forceU === void 0 ) forceU = false;
  41769. return this.at(this.nextIndex(this.pos, forceU), forceU)
  41770. };
  41771. RegExpValidationState.prototype.advance = function advance (forceU) {
  41772. if ( forceU === void 0 ) forceU = false;
  41773. this.pos = this.nextIndex(this.pos, forceU);
  41774. };
  41775. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  41776. if ( forceU === void 0 ) forceU = false;
  41777. if (this.current(forceU) === ch) {
  41778. this.advance(forceU);
  41779. return true
  41780. }
  41781. return false
  41782. };
  41783. function codePointToString(ch) {
  41784. if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
  41785. ch -= 0x10000;
  41786. return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
  41787. }
  41788. /**
  41789. * Validate the flags part of a given RegExpLiteral.
  41790. *
  41791. * @param {RegExpValidationState} state The state to validate RegExp.
  41792. * @returns {void}
  41793. */
  41794. pp$8.validateRegExpFlags = function(state) {
  41795. var validFlags = state.validFlags;
  41796. var flags = state.flags;
  41797. for (var i = 0; i < flags.length; i++) {
  41798. var flag = flags.charAt(i);
  41799. if (validFlags.indexOf(flag) === -1) {
  41800. this.raise(state.start, "Invalid regular expression flag");
  41801. }
  41802. if (flags.indexOf(flag, i + 1) > -1) {
  41803. this.raise(state.start, "Duplicate regular expression flag");
  41804. }
  41805. }
  41806. };
  41807. /**
  41808. * Validate the pattern part of a given RegExpLiteral.
  41809. *
  41810. * @param {RegExpValidationState} state The state to validate RegExp.
  41811. * @returns {void}
  41812. */
  41813. pp$8.validateRegExpPattern = function(state) {
  41814. this.regexp_pattern(state);
  41815. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  41816. // parsing contains a |GroupName|, reparse with the goal symbol
  41817. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  41818. // exception if _P_ did not conform to the grammar, if any elements of _P_
  41819. // were not matched by the parse, or if any Early Error conditions exist.
  41820. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  41821. state.switchN = true;
  41822. this.regexp_pattern(state);
  41823. }
  41824. };
  41825. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  41826. pp$8.regexp_pattern = function(state) {
  41827. state.pos = 0;
  41828. state.lastIntValue = 0;
  41829. state.lastStringValue = "";
  41830. state.lastAssertionIsQuantifiable = false;
  41831. state.numCapturingParens = 0;
  41832. state.maxBackReference = 0;
  41833. state.groupNames.length = 0;
  41834. state.backReferenceNames.length = 0;
  41835. this.regexp_disjunction(state);
  41836. if (state.pos !== state.source.length) {
  41837. // Make the same messages as V8.
  41838. if (state.eat(0x29 /* ) */)) {
  41839. state.raise("Unmatched ')'");
  41840. }
  41841. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  41842. state.raise("Lone quantifier brackets");
  41843. }
  41844. }
  41845. if (state.maxBackReference > state.numCapturingParens) {
  41846. state.raise("Invalid escape");
  41847. }
  41848. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  41849. var name = list[i];
  41850. if (state.groupNames.indexOf(name) === -1) {
  41851. state.raise("Invalid named capture referenced");
  41852. }
  41853. }
  41854. };
  41855. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  41856. pp$8.regexp_disjunction = function(state) {
  41857. this.regexp_alternative(state);
  41858. while (state.eat(0x7C /* | */)) {
  41859. this.regexp_alternative(state);
  41860. }
  41861. // Make the same message as V8.
  41862. if (this.regexp_eatQuantifier(state, true)) {
  41863. state.raise("Nothing to repeat");
  41864. }
  41865. if (state.eat(0x7B /* { */)) {
  41866. state.raise("Lone quantifier brackets");
  41867. }
  41868. };
  41869. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  41870. pp$8.regexp_alternative = function(state) {
  41871. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  41872. { }
  41873. };
  41874. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  41875. pp$8.regexp_eatTerm = function(state) {
  41876. if (this.regexp_eatAssertion(state)) {
  41877. // Handle `QuantifiableAssertion Quantifier` alternative.
  41878. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  41879. // is a QuantifiableAssertion.
  41880. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  41881. // Make the same message as V8.
  41882. if (state.switchU) {
  41883. state.raise("Invalid quantifier");
  41884. }
  41885. }
  41886. return true
  41887. }
  41888. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  41889. this.regexp_eatQuantifier(state);
  41890. return true
  41891. }
  41892. return false
  41893. };
  41894. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  41895. pp$8.regexp_eatAssertion = function(state) {
  41896. var start = state.pos;
  41897. state.lastAssertionIsQuantifiable = false;
  41898. // ^, $
  41899. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  41900. return true
  41901. }
  41902. // \b \B
  41903. if (state.eat(0x5C /* \ */)) {
  41904. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  41905. return true
  41906. }
  41907. state.pos = start;
  41908. }
  41909. // Lookahead / Lookbehind
  41910. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  41911. var lookbehind = false;
  41912. if (this.options.ecmaVersion >= 9) {
  41913. lookbehind = state.eat(0x3C /* < */);
  41914. }
  41915. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  41916. this.regexp_disjunction(state);
  41917. if (!state.eat(0x29 /* ) */)) {
  41918. state.raise("Unterminated group");
  41919. }
  41920. state.lastAssertionIsQuantifiable = !lookbehind;
  41921. return true
  41922. }
  41923. }
  41924. state.pos = start;
  41925. return false
  41926. };
  41927. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  41928. pp$8.regexp_eatQuantifier = function(state, noError) {
  41929. if ( noError === void 0 ) noError = false;
  41930. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  41931. state.eat(0x3F /* ? */);
  41932. return true
  41933. }
  41934. return false
  41935. };
  41936. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  41937. pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
  41938. return (
  41939. state.eat(0x2A /* * */) ||
  41940. state.eat(0x2B /* + */) ||
  41941. state.eat(0x3F /* ? */) ||
  41942. this.regexp_eatBracedQuantifier(state, noError)
  41943. )
  41944. };
  41945. pp$8.regexp_eatBracedQuantifier = function(state, noError) {
  41946. var start = state.pos;
  41947. if (state.eat(0x7B /* { */)) {
  41948. var min = 0, max = -1;
  41949. if (this.regexp_eatDecimalDigits(state)) {
  41950. min = state.lastIntValue;
  41951. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  41952. max = state.lastIntValue;
  41953. }
  41954. if (state.eat(0x7D /* } */)) {
  41955. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  41956. if (max !== -1 && max < min && !noError) {
  41957. state.raise("numbers out of order in {} quantifier");
  41958. }
  41959. return true
  41960. }
  41961. }
  41962. if (state.switchU && !noError) {
  41963. state.raise("Incomplete quantifier");
  41964. }
  41965. state.pos = start;
  41966. }
  41967. return false
  41968. };
  41969. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  41970. pp$8.regexp_eatAtom = function(state) {
  41971. return (
  41972. this.regexp_eatPatternCharacters(state) ||
  41973. state.eat(0x2E /* . */) ||
  41974. this.regexp_eatReverseSolidusAtomEscape(state) ||
  41975. this.regexp_eatCharacterClass(state) ||
  41976. this.regexp_eatUncapturingGroup(state) ||
  41977. this.regexp_eatCapturingGroup(state)
  41978. )
  41979. };
  41980. pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
  41981. var start = state.pos;
  41982. if (state.eat(0x5C /* \ */)) {
  41983. if (this.regexp_eatAtomEscape(state)) {
  41984. return true
  41985. }
  41986. state.pos = start;
  41987. }
  41988. return false
  41989. };
  41990. pp$8.regexp_eatUncapturingGroup = function(state) {
  41991. var start = state.pos;
  41992. if (state.eat(0x28 /* ( */)) {
  41993. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  41994. this.regexp_disjunction(state);
  41995. if (state.eat(0x29 /* ) */)) {
  41996. return true
  41997. }
  41998. state.raise("Unterminated group");
  41999. }
  42000. state.pos = start;
  42001. }
  42002. return false
  42003. };
  42004. pp$8.regexp_eatCapturingGroup = function(state) {
  42005. if (state.eat(0x28 /* ( */)) {
  42006. if (this.options.ecmaVersion >= 9) {
  42007. this.regexp_groupSpecifier(state);
  42008. } else if (state.current() === 0x3F /* ? */) {
  42009. state.raise("Invalid group");
  42010. }
  42011. this.regexp_disjunction(state);
  42012. if (state.eat(0x29 /* ) */)) {
  42013. state.numCapturingParens += 1;
  42014. return true
  42015. }
  42016. state.raise("Unterminated group");
  42017. }
  42018. return false
  42019. };
  42020. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  42021. pp$8.regexp_eatExtendedAtom = function(state) {
  42022. return (
  42023. state.eat(0x2E /* . */) ||
  42024. this.regexp_eatReverseSolidusAtomEscape(state) ||
  42025. this.regexp_eatCharacterClass(state) ||
  42026. this.regexp_eatUncapturingGroup(state) ||
  42027. this.regexp_eatCapturingGroup(state) ||
  42028. this.regexp_eatInvalidBracedQuantifier(state) ||
  42029. this.regexp_eatExtendedPatternCharacter(state)
  42030. )
  42031. };
  42032. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  42033. pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
  42034. if (this.regexp_eatBracedQuantifier(state, true)) {
  42035. state.raise("Nothing to repeat");
  42036. }
  42037. return false
  42038. };
  42039. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  42040. pp$8.regexp_eatSyntaxCharacter = function(state) {
  42041. var ch = state.current();
  42042. if (isSyntaxCharacter(ch)) {
  42043. state.lastIntValue = ch;
  42044. state.advance();
  42045. return true
  42046. }
  42047. return false
  42048. };
  42049. function isSyntaxCharacter(ch) {
  42050. return (
  42051. ch === 0x24 /* $ */ ||
  42052. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  42053. ch === 0x2E /* . */ ||
  42054. ch === 0x3F /* ? */ ||
  42055. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  42056. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  42057. )
  42058. }
  42059. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  42060. // But eat eager.
  42061. pp$8.regexp_eatPatternCharacters = function(state) {
  42062. var start = state.pos;
  42063. var ch = 0;
  42064. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  42065. state.advance();
  42066. }
  42067. return state.pos !== start
  42068. };
  42069. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  42070. pp$8.regexp_eatExtendedPatternCharacter = function(state) {
  42071. var ch = state.current();
  42072. if (
  42073. ch !== -1 &&
  42074. ch !== 0x24 /* $ */ &&
  42075. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  42076. ch !== 0x2E /* . */ &&
  42077. ch !== 0x3F /* ? */ &&
  42078. ch !== 0x5B /* [ */ &&
  42079. ch !== 0x5E /* ^ */ &&
  42080. ch !== 0x7C /* | */
  42081. ) {
  42082. state.advance();
  42083. return true
  42084. }
  42085. return false
  42086. };
  42087. // GroupSpecifier ::
  42088. // [empty]
  42089. // `?` GroupName
  42090. pp$8.regexp_groupSpecifier = function(state) {
  42091. if (state.eat(0x3F /* ? */)) {
  42092. if (this.regexp_eatGroupName(state)) {
  42093. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  42094. state.raise("Duplicate capture group name");
  42095. }
  42096. state.groupNames.push(state.lastStringValue);
  42097. return
  42098. }
  42099. state.raise("Invalid group");
  42100. }
  42101. };
  42102. // GroupName ::
  42103. // `<` RegExpIdentifierName `>`
  42104. // Note: this updates `state.lastStringValue` property with the eaten name.
  42105. pp$8.regexp_eatGroupName = function(state) {
  42106. state.lastStringValue = "";
  42107. if (state.eat(0x3C /* < */)) {
  42108. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  42109. return true
  42110. }
  42111. state.raise("Invalid capture group name");
  42112. }
  42113. return false
  42114. };
  42115. // RegExpIdentifierName ::
  42116. // RegExpIdentifierStart
  42117. // RegExpIdentifierName RegExpIdentifierPart
  42118. // Note: this updates `state.lastStringValue` property with the eaten name.
  42119. pp$8.regexp_eatRegExpIdentifierName = function(state) {
  42120. state.lastStringValue = "";
  42121. if (this.regexp_eatRegExpIdentifierStart(state)) {
  42122. state.lastStringValue += codePointToString(state.lastIntValue);
  42123. while (this.regexp_eatRegExpIdentifierPart(state)) {
  42124. state.lastStringValue += codePointToString(state.lastIntValue);
  42125. }
  42126. return true
  42127. }
  42128. return false
  42129. };
  42130. // RegExpIdentifierStart ::
  42131. // UnicodeIDStart
  42132. // `$`
  42133. // `_`
  42134. // `\` RegExpUnicodeEscapeSequence[+U]
  42135. pp$8.regexp_eatRegExpIdentifierStart = function(state) {
  42136. var start = state.pos;
  42137. var forceU = this.options.ecmaVersion >= 11;
  42138. var ch = state.current(forceU);
  42139. state.advance(forceU);
  42140. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  42141. ch = state.lastIntValue;
  42142. }
  42143. if (isRegExpIdentifierStart(ch)) {
  42144. state.lastIntValue = ch;
  42145. return true
  42146. }
  42147. state.pos = start;
  42148. return false
  42149. };
  42150. function isRegExpIdentifierStart(ch) {
  42151. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  42152. }
  42153. // RegExpIdentifierPart ::
  42154. // UnicodeIDContinue
  42155. // `$`
  42156. // `_`
  42157. // `\` RegExpUnicodeEscapeSequence[+U]
  42158. // <ZWNJ>
  42159. // <ZWJ>
  42160. pp$8.regexp_eatRegExpIdentifierPart = function(state) {
  42161. var start = state.pos;
  42162. var forceU = this.options.ecmaVersion >= 11;
  42163. var ch = state.current(forceU);
  42164. state.advance(forceU);
  42165. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  42166. ch = state.lastIntValue;
  42167. }
  42168. if (isRegExpIdentifierPart(ch)) {
  42169. state.lastIntValue = ch;
  42170. return true
  42171. }
  42172. state.pos = start;
  42173. return false
  42174. };
  42175. function isRegExpIdentifierPart(ch) {
  42176. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  42177. }
  42178. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  42179. pp$8.regexp_eatAtomEscape = function(state) {
  42180. if (
  42181. this.regexp_eatBackReference(state) ||
  42182. this.regexp_eatCharacterClassEscape(state) ||
  42183. this.regexp_eatCharacterEscape(state) ||
  42184. (state.switchN && this.regexp_eatKGroupName(state))
  42185. ) {
  42186. return true
  42187. }
  42188. if (state.switchU) {
  42189. // Make the same message as V8.
  42190. if (state.current() === 0x63 /* c */) {
  42191. state.raise("Invalid unicode escape");
  42192. }
  42193. state.raise("Invalid escape");
  42194. }
  42195. return false
  42196. };
  42197. pp$8.regexp_eatBackReference = function(state) {
  42198. var start = state.pos;
  42199. if (this.regexp_eatDecimalEscape(state)) {
  42200. var n = state.lastIntValue;
  42201. if (state.switchU) {
  42202. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  42203. if (n > state.maxBackReference) {
  42204. state.maxBackReference = n;
  42205. }
  42206. return true
  42207. }
  42208. if (n <= state.numCapturingParens) {
  42209. return true
  42210. }
  42211. state.pos = start;
  42212. }
  42213. return false
  42214. };
  42215. pp$8.regexp_eatKGroupName = function(state) {
  42216. if (state.eat(0x6B /* k */)) {
  42217. if (this.regexp_eatGroupName(state)) {
  42218. state.backReferenceNames.push(state.lastStringValue);
  42219. return true
  42220. }
  42221. state.raise("Invalid named reference");
  42222. }
  42223. return false
  42224. };
  42225. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  42226. pp$8.regexp_eatCharacterEscape = function(state) {
  42227. return (
  42228. this.regexp_eatControlEscape(state) ||
  42229. this.regexp_eatCControlLetter(state) ||
  42230. this.regexp_eatZero(state) ||
  42231. this.regexp_eatHexEscapeSequence(state) ||
  42232. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  42233. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  42234. this.regexp_eatIdentityEscape(state)
  42235. )
  42236. };
  42237. pp$8.regexp_eatCControlLetter = function(state) {
  42238. var start = state.pos;
  42239. if (state.eat(0x63 /* c */)) {
  42240. if (this.regexp_eatControlLetter(state)) {
  42241. return true
  42242. }
  42243. state.pos = start;
  42244. }
  42245. return false
  42246. };
  42247. pp$8.regexp_eatZero = function(state) {
  42248. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  42249. state.lastIntValue = 0;
  42250. state.advance();
  42251. return true
  42252. }
  42253. return false
  42254. };
  42255. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  42256. pp$8.regexp_eatControlEscape = function(state) {
  42257. var ch = state.current();
  42258. if (ch === 0x74 /* t */) {
  42259. state.lastIntValue = 0x09; /* \t */
  42260. state.advance();
  42261. return true
  42262. }
  42263. if (ch === 0x6E /* n */) {
  42264. state.lastIntValue = 0x0A; /* \n */
  42265. state.advance();
  42266. return true
  42267. }
  42268. if (ch === 0x76 /* v */) {
  42269. state.lastIntValue = 0x0B; /* \v */
  42270. state.advance();
  42271. return true
  42272. }
  42273. if (ch === 0x66 /* f */) {
  42274. state.lastIntValue = 0x0C; /* \f */
  42275. state.advance();
  42276. return true
  42277. }
  42278. if (ch === 0x72 /* r */) {
  42279. state.lastIntValue = 0x0D; /* \r */
  42280. state.advance();
  42281. return true
  42282. }
  42283. return false
  42284. };
  42285. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  42286. pp$8.regexp_eatControlLetter = function(state) {
  42287. var ch = state.current();
  42288. if (isControlLetter(ch)) {
  42289. state.lastIntValue = ch % 0x20;
  42290. state.advance();
  42291. return true
  42292. }
  42293. return false
  42294. };
  42295. function isControlLetter(ch) {
  42296. return (
  42297. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  42298. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  42299. )
  42300. }
  42301. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  42302. pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  42303. if ( forceU === void 0 ) forceU = false;
  42304. var start = state.pos;
  42305. var switchU = forceU || state.switchU;
  42306. if (state.eat(0x75 /* u */)) {
  42307. if (this.regexp_eatFixedHexDigits(state, 4)) {
  42308. var lead = state.lastIntValue;
  42309. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  42310. var leadSurrogateEnd = state.pos;
  42311. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  42312. var trail = state.lastIntValue;
  42313. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  42314. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  42315. return true
  42316. }
  42317. }
  42318. state.pos = leadSurrogateEnd;
  42319. state.lastIntValue = lead;
  42320. }
  42321. return true
  42322. }
  42323. if (
  42324. switchU &&
  42325. state.eat(0x7B /* { */) &&
  42326. this.regexp_eatHexDigits(state) &&
  42327. state.eat(0x7D /* } */) &&
  42328. isValidUnicode(state.lastIntValue)
  42329. ) {
  42330. return true
  42331. }
  42332. if (switchU) {
  42333. state.raise("Invalid unicode escape");
  42334. }
  42335. state.pos = start;
  42336. }
  42337. return false
  42338. };
  42339. function isValidUnicode(ch) {
  42340. return ch >= 0 && ch <= 0x10FFFF
  42341. }
  42342. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  42343. pp$8.regexp_eatIdentityEscape = function(state) {
  42344. if (state.switchU) {
  42345. if (this.regexp_eatSyntaxCharacter(state)) {
  42346. return true
  42347. }
  42348. if (state.eat(0x2F /* / */)) {
  42349. state.lastIntValue = 0x2F; /* / */
  42350. return true
  42351. }
  42352. return false
  42353. }
  42354. var ch = state.current();
  42355. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  42356. state.lastIntValue = ch;
  42357. state.advance();
  42358. return true
  42359. }
  42360. return false
  42361. };
  42362. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  42363. pp$8.regexp_eatDecimalEscape = function(state) {
  42364. state.lastIntValue = 0;
  42365. var ch = state.current();
  42366. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  42367. do {
  42368. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  42369. state.advance();
  42370. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  42371. return true
  42372. }
  42373. return false
  42374. };
  42375. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  42376. pp$8.regexp_eatCharacterClassEscape = function(state) {
  42377. var ch = state.current();
  42378. if (isCharacterClassEscape(ch)) {
  42379. state.lastIntValue = -1;
  42380. state.advance();
  42381. return true
  42382. }
  42383. if (
  42384. state.switchU &&
  42385. this.options.ecmaVersion >= 9 &&
  42386. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  42387. ) {
  42388. state.lastIntValue = -1;
  42389. state.advance();
  42390. if (
  42391. state.eat(0x7B /* { */) &&
  42392. this.regexp_eatUnicodePropertyValueExpression(state) &&
  42393. state.eat(0x7D /* } */)
  42394. ) {
  42395. return true
  42396. }
  42397. state.raise("Invalid property name");
  42398. }
  42399. return false
  42400. };
  42401. function isCharacterClassEscape(ch) {
  42402. return (
  42403. ch === 0x64 /* d */ ||
  42404. ch === 0x44 /* D */ ||
  42405. ch === 0x73 /* s */ ||
  42406. ch === 0x53 /* S */ ||
  42407. ch === 0x77 /* w */ ||
  42408. ch === 0x57 /* W */
  42409. )
  42410. }
  42411. // UnicodePropertyValueExpression ::
  42412. // UnicodePropertyName `=` UnicodePropertyValue
  42413. // LoneUnicodePropertyNameOrValue
  42414. pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
  42415. var start = state.pos;
  42416. // UnicodePropertyName `=` UnicodePropertyValue
  42417. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  42418. var name = state.lastStringValue;
  42419. if (this.regexp_eatUnicodePropertyValue(state)) {
  42420. var value = state.lastStringValue;
  42421. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  42422. return true
  42423. }
  42424. }
  42425. state.pos = start;
  42426. // LoneUnicodePropertyNameOrValue
  42427. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  42428. var nameOrValue = state.lastStringValue;
  42429. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  42430. return true
  42431. }
  42432. return false
  42433. };
  42434. pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  42435. if (!has$1(state.unicodeProperties.nonBinary, name))
  42436. { state.raise("Invalid property name"); }
  42437. if (!state.unicodeProperties.nonBinary[name].test(value))
  42438. { state.raise("Invalid property value"); }
  42439. };
  42440. pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  42441. if (!state.unicodeProperties.binary.test(nameOrValue))
  42442. { state.raise("Invalid property name"); }
  42443. };
  42444. // UnicodePropertyName ::
  42445. // UnicodePropertyNameCharacters
  42446. pp$8.regexp_eatUnicodePropertyName = function(state) {
  42447. var ch = 0;
  42448. state.lastStringValue = "";
  42449. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  42450. state.lastStringValue += codePointToString(ch);
  42451. state.advance();
  42452. }
  42453. return state.lastStringValue !== ""
  42454. };
  42455. function isUnicodePropertyNameCharacter(ch) {
  42456. return isControlLetter(ch) || ch === 0x5F /* _ */
  42457. }
  42458. // UnicodePropertyValue ::
  42459. // UnicodePropertyValueCharacters
  42460. pp$8.regexp_eatUnicodePropertyValue = function(state) {
  42461. var ch = 0;
  42462. state.lastStringValue = "";
  42463. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  42464. state.lastStringValue += codePointToString(ch);
  42465. state.advance();
  42466. }
  42467. return state.lastStringValue !== ""
  42468. };
  42469. function isUnicodePropertyValueCharacter(ch) {
  42470. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  42471. }
  42472. // LoneUnicodePropertyNameOrValue ::
  42473. // UnicodePropertyValueCharacters
  42474. pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  42475. return this.regexp_eatUnicodePropertyValue(state)
  42476. };
  42477. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  42478. pp$8.regexp_eatCharacterClass = function(state) {
  42479. if (state.eat(0x5B /* [ */)) {
  42480. state.eat(0x5E /* ^ */);
  42481. this.regexp_classRanges(state);
  42482. if (state.eat(0x5D /* ] */)) {
  42483. return true
  42484. }
  42485. // Unreachable since it threw "unterminated regular expression" error before.
  42486. state.raise("Unterminated character class");
  42487. }
  42488. return false
  42489. };
  42490. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  42491. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  42492. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  42493. pp$8.regexp_classRanges = function(state) {
  42494. while (this.regexp_eatClassAtom(state)) {
  42495. var left = state.lastIntValue;
  42496. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  42497. var right = state.lastIntValue;
  42498. if (state.switchU && (left === -1 || right === -1)) {
  42499. state.raise("Invalid character class");
  42500. }
  42501. if (left !== -1 && right !== -1 && left > right) {
  42502. state.raise("Range out of order in character class");
  42503. }
  42504. }
  42505. }
  42506. };
  42507. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  42508. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  42509. pp$8.regexp_eatClassAtom = function(state) {
  42510. var start = state.pos;
  42511. if (state.eat(0x5C /* \ */)) {
  42512. if (this.regexp_eatClassEscape(state)) {
  42513. return true
  42514. }
  42515. if (state.switchU) {
  42516. // Make the same message as V8.
  42517. var ch$1 = state.current();
  42518. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  42519. state.raise("Invalid class escape");
  42520. }
  42521. state.raise("Invalid escape");
  42522. }
  42523. state.pos = start;
  42524. }
  42525. var ch = state.current();
  42526. if (ch !== 0x5D /* ] */) {
  42527. state.lastIntValue = ch;
  42528. state.advance();
  42529. return true
  42530. }
  42531. return false
  42532. };
  42533. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  42534. pp$8.regexp_eatClassEscape = function(state) {
  42535. var start = state.pos;
  42536. if (state.eat(0x62 /* b */)) {
  42537. state.lastIntValue = 0x08; /* <BS> */
  42538. return true
  42539. }
  42540. if (state.switchU && state.eat(0x2D /* - */)) {
  42541. state.lastIntValue = 0x2D; /* - */
  42542. return true
  42543. }
  42544. if (!state.switchU && state.eat(0x63 /* c */)) {
  42545. if (this.regexp_eatClassControlLetter(state)) {
  42546. return true
  42547. }
  42548. state.pos = start;
  42549. }
  42550. return (
  42551. this.regexp_eatCharacterClassEscape(state) ||
  42552. this.regexp_eatCharacterEscape(state)
  42553. )
  42554. };
  42555. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  42556. pp$8.regexp_eatClassControlLetter = function(state) {
  42557. var ch = state.current();
  42558. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  42559. state.lastIntValue = ch % 0x20;
  42560. state.advance();
  42561. return true
  42562. }
  42563. return false
  42564. };
  42565. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  42566. pp$8.regexp_eatHexEscapeSequence = function(state) {
  42567. var start = state.pos;
  42568. if (state.eat(0x78 /* x */)) {
  42569. if (this.regexp_eatFixedHexDigits(state, 2)) {
  42570. return true
  42571. }
  42572. if (state.switchU) {
  42573. state.raise("Invalid escape");
  42574. }
  42575. state.pos = start;
  42576. }
  42577. return false
  42578. };
  42579. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  42580. pp$8.regexp_eatDecimalDigits = function(state) {
  42581. var start = state.pos;
  42582. var ch = 0;
  42583. state.lastIntValue = 0;
  42584. while (isDecimalDigit(ch = state.current())) {
  42585. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  42586. state.advance();
  42587. }
  42588. return state.pos !== start
  42589. };
  42590. function isDecimalDigit(ch) {
  42591. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  42592. }
  42593. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  42594. pp$8.regexp_eatHexDigits = function(state) {
  42595. var start = state.pos;
  42596. var ch = 0;
  42597. state.lastIntValue = 0;
  42598. while (isHexDigit(ch = state.current())) {
  42599. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  42600. state.advance();
  42601. }
  42602. return state.pos !== start
  42603. };
  42604. function isHexDigit(ch) {
  42605. return (
  42606. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  42607. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  42608. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  42609. )
  42610. }
  42611. function hexToInt(ch) {
  42612. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  42613. return 10 + (ch - 0x41 /* A */)
  42614. }
  42615. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  42616. return 10 + (ch - 0x61 /* a */)
  42617. }
  42618. return ch - 0x30 /* 0 */
  42619. }
  42620. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  42621. // Allows only 0-377(octal) i.e. 0-255(decimal).
  42622. pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
  42623. if (this.regexp_eatOctalDigit(state)) {
  42624. var n1 = state.lastIntValue;
  42625. if (this.regexp_eatOctalDigit(state)) {
  42626. var n2 = state.lastIntValue;
  42627. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  42628. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  42629. } else {
  42630. state.lastIntValue = n1 * 8 + n2;
  42631. }
  42632. } else {
  42633. state.lastIntValue = n1;
  42634. }
  42635. return true
  42636. }
  42637. return false
  42638. };
  42639. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  42640. pp$8.regexp_eatOctalDigit = function(state) {
  42641. var ch = state.current();
  42642. if (isOctalDigit(ch)) {
  42643. state.lastIntValue = ch - 0x30; /* 0 */
  42644. state.advance();
  42645. return true
  42646. }
  42647. state.lastIntValue = 0;
  42648. return false
  42649. };
  42650. function isOctalDigit(ch) {
  42651. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  42652. }
  42653. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  42654. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  42655. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  42656. pp$8.regexp_eatFixedHexDigits = function(state, length) {
  42657. var start = state.pos;
  42658. state.lastIntValue = 0;
  42659. for (var i = 0; i < length; ++i) {
  42660. var ch = state.current();
  42661. if (!isHexDigit(ch)) {
  42662. state.pos = start;
  42663. return false
  42664. }
  42665. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  42666. state.advance();
  42667. }
  42668. return true
  42669. };
  42670. // Object type used to represent tokens. Note that normally, tokens
  42671. // simply exist as properties on the parser object. This is only
  42672. // used for the onToken callback and the external tokenizer.
  42673. var Token = function Token(p) {
  42674. this.type = p.type;
  42675. this.value = p.value;
  42676. this.start = p.start;
  42677. this.end = p.end;
  42678. if (p.options.locations)
  42679. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  42680. if (p.options.ranges)
  42681. { this.range = [p.start, p.end]; }
  42682. };
  42683. // ## Tokenizer
  42684. var pp$9 = Parser.prototype;
  42685. // Move to the next token
  42686. pp$9.next = function(ignoreEscapeSequenceInKeyword) {
  42687. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  42688. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  42689. if (this.options.onToken)
  42690. { this.options.onToken(new Token(this)); }
  42691. this.lastTokEnd = this.end;
  42692. this.lastTokStart = this.start;
  42693. this.lastTokEndLoc = this.endLoc;
  42694. this.lastTokStartLoc = this.startLoc;
  42695. this.nextToken();
  42696. };
  42697. pp$9.getToken = function() {
  42698. this.next();
  42699. return new Token(this)
  42700. };
  42701. // If we're in an ES6 environment, make parsers iterable
  42702. if (typeof Symbol !== "undefined")
  42703. { pp$9[Symbol.iterator] = function() {
  42704. var this$1$1 = this;
  42705. return {
  42706. next: function () {
  42707. var token = this$1$1.getToken();
  42708. return {
  42709. done: token.type === types.eof,
  42710. value: token
  42711. }
  42712. }
  42713. }
  42714. }; }
  42715. // Toggle strict mode. Re-reads the next number or string to please
  42716. // pedantic tests (`"use strict"; 010;` should fail).
  42717. pp$9.curContext = function() {
  42718. return this.context[this.context.length - 1]
  42719. };
  42720. // Read a single token, updating the parser object's token-related
  42721. // properties.
  42722. pp$9.nextToken = function() {
  42723. var curContext = this.curContext();
  42724. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  42725. this.start = this.pos;
  42726. if (this.options.locations) { this.startLoc = this.curPosition(); }
  42727. if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
  42728. if (curContext.override) { return curContext.override(this) }
  42729. else { this.readToken(this.fullCharCodeAtPos()); }
  42730. };
  42731. pp$9.readToken = function(code) {
  42732. // Identifier or keyword. '\uXXXX' sequences are allowed in
  42733. // identifiers, so '\' also dispatches to that.
  42734. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  42735. { return this.readWord() }
  42736. return this.getTokenFromCode(code)
  42737. };
  42738. pp$9.fullCharCodeAtPos = function() {
  42739. var code = this.input.charCodeAt(this.pos);
  42740. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  42741. var next = this.input.charCodeAt(this.pos + 1);
  42742. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  42743. };
  42744. pp$9.skipBlockComment = function() {
  42745. var startLoc = this.options.onComment && this.curPosition();
  42746. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  42747. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  42748. this.pos = end + 2;
  42749. if (this.options.locations) {
  42750. lineBreakG.lastIndex = start;
  42751. var match;
  42752. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  42753. ++this.curLine;
  42754. this.lineStart = match.index + match[0].length;
  42755. }
  42756. }
  42757. if (this.options.onComment)
  42758. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  42759. startLoc, this.curPosition()); }
  42760. };
  42761. pp$9.skipLineComment = function(startSkip) {
  42762. var start = this.pos;
  42763. var startLoc = this.options.onComment && this.curPosition();
  42764. var ch = this.input.charCodeAt(this.pos += startSkip);
  42765. while (this.pos < this.input.length && !isNewLine(ch)) {
  42766. ch = this.input.charCodeAt(++this.pos);
  42767. }
  42768. if (this.options.onComment)
  42769. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  42770. startLoc, this.curPosition()); }
  42771. };
  42772. // Called at the start of the parse and after every token. Skips
  42773. // whitespace and comments, and.
  42774. pp$9.skipSpace = function() {
  42775. loop: while (this.pos < this.input.length) {
  42776. var ch = this.input.charCodeAt(this.pos);
  42777. switch (ch) {
  42778. case 32: case 160: // ' '
  42779. ++this.pos;
  42780. break
  42781. case 13:
  42782. if (this.input.charCodeAt(this.pos + 1) === 10) {
  42783. ++this.pos;
  42784. }
  42785. case 10: case 8232: case 8233:
  42786. ++this.pos;
  42787. if (this.options.locations) {
  42788. ++this.curLine;
  42789. this.lineStart = this.pos;
  42790. }
  42791. break
  42792. case 47: // '/'
  42793. switch (this.input.charCodeAt(this.pos + 1)) {
  42794. case 42: // '*'
  42795. this.skipBlockComment();
  42796. break
  42797. case 47:
  42798. this.skipLineComment(2);
  42799. break
  42800. default:
  42801. break loop
  42802. }
  42803. break
  42804. default:
  42805. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  42806. ++this.pos;
  42807. } else {
  42808. break loop
  42809. }
  42810. }
  42811. }
  42812. };
  42813. // Called at the end of every token. Sets `end`, `val`, and
  42814. // maintains `context` and `exprAllowed`, and skips the space after
  42815. // the token, so that the next one's `start` will point at the
  42816. // right position.
  42817. pp$9.finishToken = function(type, val) {
  42818. this.end = this.pos;
  42819. if (this.options.locations) { this.endLoc = this.curPosition(); }
  42820. var prevType = this.type;
  42821. this.type = type;
  42822. this.value = val;
  42823. this.updateContext(prevType);
  42824. };
  42825. // ### Token reading
  42826. // This is the function that is called to fetch the next token. It
  42827. // is somewhat obscure, because it works in character codes rather
  42828. // than characters, and because operator parsing has been inlined
  42829. // into it.
  42830. //
  42831. // All in the name of speed.
  42832. //
  42833. pp$9.readToken_dot = function() {
  42834. var next = this.input.charCodeAt(this.pos + 1);
  42835. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  42836. var next2 = this.input.charCodeAt(this.pos + 2);
  42837. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  42838. this.pos += 3;
  42839. return this.finishToken(types.ellipsis)
  42840. } else {
  42841. ++this.pos;
  42842. return this.finishToken(types.dot)
  42843. }
  42844. };
  42845. pp$9.readToken_slash = function() { // '/'
  42846. var next = this.input.charCodeAt(this.pos + 1);
  42847. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  42848. if (next === 61) { return this.finishOp(types.assign, 2) }
  42849. return this.finishOp(types.slash, 1)
  42850. };
  42851. pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
  42852. var next = this.input.charCodeAt(this.pos + 1);
  42853. var size = 1;
  42854. var tokentype = code === 42 ? types.star : types.modulo;
  42855. // exponentiation operator ** and **=
  42856. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  42857. ++size;
  42858. tokentype = types.starstar;
  42859. next = this.input.charCodeAt(this.pos + 2);
  42860. }
  42861. if (next === 61) { return this.finishOp(types.assign, size + 1) }
  42862. return this.finishOp(tokentype, size)
  42863. };
  42864. pp$9.readToken_pipe_amp = function(code) { // '|&'
  42865. var next = this.input.charCodeAt(this.pos + 1);
  42866. if (next === code) {
  42867. if (this.options.ecmaVersion >= 12) {
  42868. var next2 = this.input.charCodeAt(this.pos + 2);
  42869. if (next2 === 61) { return this.finishOp(types.assign, 3) }
  42870. }
  42871. return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
  42872. }
  42873. if (next === 61) { return this.finishOp(types.assign, 2) }
  42874. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
  42875. };
  42876. pp$9.readToken_caret = function() { // '^'
  42877. var next = this.input.charCodeAt(this.pos + 1);
  42878. if (next === 61) { return this.finishOp(types.assign, 2) }
  42879. return this.finishOp(types.bitwiseXOR, 1)
  42880. };
  42881. pp$9.readToken_plus_min = function(code) { // '+-'
  42882. var next = this.input.charCodeAt(this.pos + 1);
  42883. if (next === code) {
  42884. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  42885. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  42886. // A `-->` line comment
  42887. this.skipLineComment(3);
  42888. this.skipSpace();
  42889. return this.nextToken()
  42890. }
  42891. return this.finishOp(types.incDec, 2)
  42892. }
  42893. if (next === 61) { return this.finishOp(types.assign, 2) }
  42894. return this.finishOp(types.plusMin, 1)
  42895. };
  42896. pp$9.readToken_lt_gt = function(code) { // '<>'
  42897. var next = this.input.charCodeAt(this.pos + 1);
  42898. var size = 1;
  42899. if (next === code) {
  42900. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  42901. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
  42902. return this.finishOp(types.bitShift, size)
  42903. }
  42904. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  42905. this.input.charCodeAt(this.pos + 3) === 45) {
  42906. // `<!--`, an XML-style comment that should be interpreted as a line comment
  42907. this.skipLineComment(4);
  42908. this.skipSpace();
  42909. return this.nextToken()
  42910. }
  42911. if (next === 61) { size = 2; }
  42912. return this.finishOp(types.relational, size)
  42913. };
  42914. pp$9.readToken_eq_excl = function(code) { // '=!'
  42915. var next = this.input.charCodeAt(this.pos + 1);
  42916. if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  42917. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  42918. this.pos += 2;
  42919. return this.finishToken(types.arrow)
  42920. }
  42921. return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
  42922. };
  42923. pp$9.readToken_question = function() { // '?'
  42924. var ecmaVersion = this.options.ecmaVersion;
  42925. if (ecmaVersion >= 11) {
  42926. var next = this.input.charCodeAt(this.pos + 1);
  42927. if (next === 46) {
  42928. var next2 = this.input.charCodeAt(this.pos + 2);
  42929. if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
  42930. }
  42931. if (next === 63) {
  42932. if (ecmaVersion >= 12) {
  42933. var next2$1 = this.input.charCodeAt(this.pos + 2);
  42934. if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
  42935. }
  42936. return this.finishOp(types.coalesce, 2)
  42937. }
  42938. }
  42939. return this.finishOp(types.question, 1)
  42940. };
  42941. pp$9.readToken_numberSign = function() { // '#'
  42942. var ecmaVersion = this.options.ecmaVersion;
  42943. var code = 35; // '#'
  42944. if (ecmaVersion >= 13) {
  42945. ++this.pos;
  42946. code = this.fullCharCodeAtPos();
  42947. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  42948. return this.finishToken(types.privateId, this.readWord1())
  42949. }
  42950. }
  42951. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  42952. };
  42953. pp$9.getTokenFromCode = function(code) {
  42954. switch (code) {
  42955. // The interpretation of a dot depends on whether it is followed
  42956. // by a digit or another two dots.
  42957. case 46: // '.'
  42958. return this.readToken_dot()
  42959. // Punctuation tokens.
  42960. case 40: ++this.pos; return this.finishToken(types.parenL)
  42961. case 41: ++this.pos; return this.finishToken(types.parenR)
  42962. case 59: ++this.pos; return this.finishToken(types.semi)
  42963. case 44: ++this.pos; return this.finishToken(types.comma)
  42964. case 91: ++this.pos; return this.finishToken(types.bracketL)
  42965. case 93: ++this.pos; return this.finishToken(types.bracketR)
  42966. case 123: ++this.pos; return this.finishToken(types.braceL)
  42967. case 125: ++this.pos; return this.finishToken(types.braceR)
  42968. case 58: ++this.pos; return this.finishToken(types.colon)
  42969. case 96: // '`'
  42970. if (this.options.ecmaVersion < 6) { break }
  42971. ++this.pos;
  42972. return this.finishToken(types.backQuote)
  42973. case 48: // '0'
  42974. var next = this.input.charCodeAt(this.pos + 1);
  42975. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  42976. if (this.options.ecmaVersion >= 6) {
  42977. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  42978. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  42979. }
  42980. // Anything else beginning with a digit is an integer, octal
  42981. // number, or float.
  42982. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  42983. return this.readNumber(false)
  42984. // Quotes produce strings.
  42985. case 34: case 39: // '"', "'"
  42986. return this.readString(code)
  42987. // Operators are parsed inline in tiny state machines. '=' (61) is
  42988. // often referred to. `finishOp` simply skips the amount of
  42989. // characters it is given as second argument, and returns a token
  42990. // of the type given by its first argument.
  42991. case 47: // '/'
  42992. return this.readToken_slash()
  42993. case 37: case 42: // '%*'
  42994. return this.readToken_mult_modulo_exp(code)
  42995. case 124: case 38: // '|&'
  42996. return this.readToken_pipe_amp(code)
  42997. case 94: // '^'
  42998. return this.readToken_caret()
  42999. case 43: case 45: // '+-'
  43000. return this.readToken_plus_min(code)
  43001. case 60: case 62: // '<>'
  43002. return this.readToken_lt_gt(code)
  43003. case 61: case 33: // '=!'
  43004. return this.readToken_eq_excl(code)
  43005. case 63: // '?'
  43006. return this.readToken_question()
  43007. case 126: // '~'
  43008. return this.finishOp(types.prefix, 1)
  43009. case 35: // '#'
  43010. return this.readToken_numberSign()
  43011. }
  43012. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  43013. };
  43014. pp$9.finishOp = function(type, size) {
  43015. var str = this.input.slice(this.pos, this.pos + size);
  43016. this.pos += size;
  43017. return this.finishToken(type, str)
  43018. };
  43019. pp$9.readRegexp = function() {
  43020. var escaped, inClass, start = this.pos;
  43021. for (;;) {
  43022. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  43023. var ch = this.input.charAt(this.pos);
  43024. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  43025. if (!escaped) {
  43026. if (ch === "[") { inClass = true; }
  43027. else if (ch === "]" && inClass) { inClass = false; }
  43028. else if (ch === "/" && !inClass) { break }
  43029. escaped = ch === "\\";
  43030. } else { escaped = false; }
  43031. ++this.pos;
  43032. }
  43033. var pattern = this.input.slice(start, this.pos);
  43034. ++this.pos;
  43035. var flagsStart = this.pos;
  43036. var flags = this.readWord1();
  43037. if (this.containsEsc) { this.unexpected(flagsStart); }
  43038. // Validate pattern
  43039. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  43040. state.reset(start, pattern, flags);
  43041. this.validateRegExpFlags(state);
  43042. this.validateRegExpPattern(state);
  43043. // Create Literal#value property value.
  43044. var value = null;
  43045. try {
  43046. value = new RegExp(pattern, flags);
  43047. } catch (e) {
  43048. // ESTree requires null if it failed to instantiate RegExp object.
  43049. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  43050. }
  43051. return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
  43052. };
  43053. // Read an integer in the given radix. Return null if zero digits
  43054. // were read, the integer value otherwise. When `len` is given, this
  43055. // will return `null` unless the integer has exactly `len` digits.
  43056. pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  43057. // `len` is used for character escape sequences. In that case, disallow separators.
  43058. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  43059. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  43060. // and isn't fraction part nor exponent part. In that case, if the first digit
  43061. // is zero then disallow separators.
  43062. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  43063. var start = this.pos, total = 0, lastCode = 0;
  43064. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  43065. var code = this.input.charCodeAt(this.pos), val = (void 0);
  43066. if (allowSeparators && code === 95) {
  43067. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  43068. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  43069. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  43070. lastCode = code;
  43071. continue
  43072. }
  43073. if (code >= 97) { val = code - 97 + 10; } // a
  43074. else if (code >= 65) { val = code - 65 + 10; } // A
  43075. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  43076. else { val = Infinity; }
  43077. if (val >= radix) { break }
  43078. lastCode = code;
  43079. total = total * radix + val;
  43080. }
  43081. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  43082. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  43083. return total
  43084. };
  43085. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  43086. if (isLegacyOctalNumericLiteral) {
  43087. return parseInt(str, 8)
  43088. }
  43089. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  43090. return parseFloat(str.replace(/_/g, ""))
  43091. }
  43092. function stringToBigInt(str) {
  43093. if (typeof BigInt !== "function") {
  43094. return null
  43095. }
  43096. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  43097. return BigInt(str.replace(/_/g, ""))
  43098. }
  43099. pp$9.readRadixNumber = function(radix) {
  43100. var start = this.pos;
  43101. this.pos += 2; // 0x
  43102. var val = this.readInt(radix);
  43103. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  43104. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  43105. val = stringToBigInt(this.input.slice(start, this.pos));
  43106. ++this.pos;
  43107. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  43108. return this.finishToken(types.num, val)
  43109. };
  43110. // Read an integer, octal integer, or floating-point number.
  43111. pp$9.readNumber = function(startsWithDot) {
  43112. var start = this.pos;
  43113. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  43114. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  43115. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  43116. var next = this.input.charCodeAt(this.pos);
  43117. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  43118. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  43119. ++this.pos;
  43120. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  43121. return this.finishToken(types.num, val$1)
  43122. }
  43123. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  43124. if (next === 46 && !octal) { // '.'
  43125. ++this.pos;
  43126. this.readInt(10);
  43127. next = this.input.charCodeAt(this.pos);
  43128. }
  43129. if ((next === 69 || next === 101) && !octal) { // 'eE'
  43130. next = this.input.charCodeAt(++this.pos);
  43131. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  43132. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  43133. }
  43134. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  43135. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  43136. return this.finishToken(types.num, val)
  43137. };
  43138. // Read a string value, interpreting backslash-escapes.
  43139. pp$9.readCodePoint = function() {
  43140. var ch = this.input.charCodeAt(this.pos), code;
  43141. if (ch === 123) { // '{'
  43142. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  43143. var codePos = ++this.pos;
  43144. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  43145. ++this.pos;
  43146. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  43147. } else {
  43148. code = this.readHexChar(4);
  43149. }
  43150. return code
  43151. };
  43152. function codePointToString$1(code) {
  43153. // UTF-16 Decoding
  43154. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  43155. code -= 0x10000;
  43156. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  43157. }
  43158. pp$9.readString = function(quote) {
  43159. var out = "", chunkStart = ++this.pos;
  43160. for (;;) {
  43161. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  43162. var ch = this.input.charCodeAt(this.pos);
  43163. if (ch === quote) { break }
  43164. if (ch === 92) { // '\'
  43165. out += this.input.slice(chunkStart, this.pos);
  43166. out += this.readEscapedChar(false);
  43167. chunkStart = this.pos;
  43168. } else {
  43169. if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
  43170. ++this.pos;
  43171. }
  43172. }
  43173. out += this.input.slice(chunkStart, this.pos++);
  43174. return this.finishToken(types.string, out)
  43175. };
  43176. // Reads template string tokens.
  43177. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  43178. pp$9.tryReadTemplateToken = function() {
  43179. this.inTemplateElement = true;
  43180. try {
  43181. this.readTmplToken();
  43182. } catch (err) {
  43183. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  43184. this.readInvalidTemplateToken();
  43185. } else {
  43186. throw err
  43187. }
  43188. }
  43189. this.inTemplateElement = false;
  43190. };
  43191. pp$9.invalidStringToken = function(position, message) {
  43192. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  43193. throw INVALID_TEMPLATE_ESCAPE_ERROR
  43194. } else {
  43195. this.raise(position, message);
  43196. }
  43197. };
  43198. pp$9.readTmplToken = function() {
  43199. var out = "", chunkStart = this.pos;
  43200. for (;;) {
  43201. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  43202. var ch = this.input.charCodeAt(this.pos);
  43203. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  43204. if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
  43205. if (ch === 36) {
  43206. this.pos += 2;
  43207. return this.finishToken(types.dollarBraceL)
  43208. } else {
  43209. ++this.pos;
  43210. return this.finishToken(types.backQuote)
  43211. }
  43212. }
  43213. out += this.input.slice(chunkStart, this.pos);
  43214. return this.finishToken(types.template, out)
  43215. }
  43216. if (ch === 92) { // '\'
  43217. out += this.input.slice(chunkStart, this.pos);
  43218. out += this.readEscapedChar(true);
  43219. chunkStart = this.pos;
  43220. } else if (isNewLine(ch)) {
  43221. out += this.input.slice(chunkStart, this.pos);
  43222. ++this.pos;
  43223. switch (ch) {
  43224. case 13:
  43225. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  43226. case 10:
  43227. out += "\n";
  43228. break
  43229. default:
  43230. out += String.fromCharCode(ch);
  43231. break
  43232. }
  43233. if (this.options.locations) {
  43234. ++this.curLine;
  43235. this.lineStart = this.pos;
  43236. }
  43237. chunkStart = this.pos;
  43238. } else {
  43239. ++this.pos;
  43240. }
  43241. }
  43242. };
  43243. // Reads a template token to search for the end, without validating any escape sequences
  43244. pp$9.readInvalidTemplateToken = function() {
  43245. for (; this.pos < this.input.length; this.pos++) {
  43246. switch (this.input[this.pos]) {
  43247. case "\\":
  43248. ++this.pos;
  43249. break
  43250. case "$":
  43251. if (this.input[this.pos + 1] !== "{") {
  43252. break
  43253. }
  43254. // falls through
  43255. case "`":
  43256. return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
  43257. // no default
  43258. }
  43259. }
  43260. this.raise(this.start, "Unterminated template");
  43261. };
  43262. // Used to read escaped characters
  43263. pp$9.readEscapedChar = function(inTemplate) {
  43264. var ch = this.input.charCodeAt(++this.pos);
  43265. ++this.pos;
  43266. switch (ch) {
  43267. case 110: return "\n" // 'n' -> '\n'
  43268. case 114: return "\r" // 'r' -> '\r'
  43269. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  43270. case 117: return codePointToString$1(this.readCodePoint()) // 'u'
  43271. case 116: return "\t" // 't' -> '\t'
  43272. case 98: return "\b" // 'b' -> '\b'
  43273. case 118: return "\u000b" // 'v' -> '\u000b'
  43274. case 102: return "\f" // 'f' -> '\f'
  43275. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  43276. case 10: // ' \n'
  43277. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  43278. return ""
  43279. case 56:
  43280. case 57:
  43281. if (this.strict) {
  43282. this.invalidStringToken(
  43283. this.pos - 1,
  43284. "Invalid escape sequence"
  43285. );
  43286. }
  43287. if (inTemplate) {
  43288. var codePos = this.pos - 1;
  43289. this.invalidStringToken(
  43290. codePos,
  43291. "Invalid escape sequence in template string"
  43292. );
  43293. return null
  43294. }
  43295. default:
  43296. if (ch >= 48 && ch <= 55) {
  43297. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  43298. var octal = parseInt(octalStr, 8);
  43299. if (octal > 255) {
  43300. octalStr = octalStr.slice(0, -1);
  43301. octal = parseInt(octalStr, 8);
  43302. }
  43303. this.pos += octalStr.length - 1;
  43304. ch = this.input.charCodeAt(this.pos);
  43305. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  43306. this.invalidStringToken(
  43307. this.pos - 1 - octalStr.length,
  43308. inTemplate
  43309. ? "Octal literal in template string"
  43310. : "Octal literal in strict mode"
  43311. );
  43312. }
  43313. return String.fromCharCode(octal)
  43314. }
  43315. if (isNewLine(ch)) {
  43316. // Unicode new line characters after \ get removed from output in both
  43317. // template literals and strings
  43318. return ""
  43319. }
  43320. return String.fromCharCode(ch)
  43321. }
  43322. };
  43323. // Used to read character escape sequences ('\x', '\u', '\U').
  43324. pp$9.readHexChar = function(len) {
  43325. var codePos = this.pos;
  43326. var n = this.readInt(16, len);
  43327. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  43328. return n
  43329. };
  43330. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  43331. // to whether the word contained a '\u' escape.
  43332. //
  43333. // Incrementally adds only escaped chars, adding other chunks as-is
  43334. // as a micro-optimization.
  43335. pp$9.readWord1 = function() {
  43336. this.containsEsc = false;
  43337. var word = "", first = true, chunkStart = this.pos;
  43338. var astral = this.options.ecmaVersion >= 6;
  43339. while (this.pos < this.input.length) {
  43340. var ch = this.fullCharCodeAtPos();
  43341. if (isIdentifierChar(ch, astral)) {
  43342. this.pos += ch <= 0xffff ? 1 : 2;
  43343. } else if (ch === 92) { // "\"
  43344. this.containsEsc = true;
  43345. word += this.input.slice(chunkStart, this.pos);
  43346. var escStart = this.pos;
  43347. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  43348. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  43349. ++this.pos;
  43350. var esc = this.readCodePoint();
  43351. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  43352. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  43353. word += codePointToString$1(esc);
  43354. chunkStart = this.pos;
  43355. } else {
  43356. break
  43357. }
  43358. first = false;
  43359. }
  43360. return word + this.input.slice(chunkStart, this.pos)
  43361. };
  43362. // Read an identifier or keyword token. Will check for reserved
  43363. // words when necessary.
  43364. pp$9.readWord = function() {
  43365. var word = this.readWord1();
  43366. var type = types.name;
  43367. if (this.keywords.test(word)) {
  43368. type = keywords$1[word];
  43369. }
  43370. return this.finishToken(type, word)
  43371. };
  43372. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  43373. var version = "8.4.1";
  43374. Parser.acorn = {
  43375. Parser: Parser,
  43376. version: version,
  43377. defaultOptions: defaultOptions,
  43378. Position: Position,
  43379. SourceLocation: SourceLocation,
  43380. getLineInfo: getLineInfo,
  43381. Node: Node,
  43382. TokenType: TokenType,
  43383. tokTypes: types,
  43384. keywordTypes: keywords$1,
  43385. TokContext: TokContext,
  43386. tokContexts: types$1,
  43387. isIdentifierChar: isIdentifierChar,
  43388. isIdentifierStart: isIdentifierStart,
  43389. Token: Token,
  43390. isNewLine: isNewLine,
  43391. lineBreak: lineBreak,
  43392. lineBreakG: lineBreakG,
  43393. nonASCIIwhitespace: nonASCIIwhitespace
  43394. };
  43395. // The main exported interface (under `self.acorn` when in the
  43396. // browser) is a `parse` function that takes a code string and
  43397. // returns an abstract syntax tree as specified by [Mozilla parser
  43398. // API][api].
  43399. //
  43400. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  43401. function parse$b(input, options) {
  43402. return Parser.parse(input, options)
  43403. }
  43404. // This function tries to parse a single expression at a given
  43405. // offset in a string. Useful for parsing mixed-language formats
  43406. // that embed JavaScript expressions.
  43407. function parseExpressionAt(input, pos, options) {
  43408. return Parser.parseExpressionAt(input, pos, options)
  43409. }
  43410. // Acorn is organized as a tokenizer and a recursive-descent parser.
  43411. // The `tokenizer` export provides an interface to the tokenizer.
  43412. function tokenizer(input, options) {
  43413. return Parser.tokenizer(input, options)
  43414. }
  43415. var acorn = {
  43416. __proto__: null,
  43417. Node: Node,
  43418. Parser: Parser,
  43419. Position: Position,
  43420. SourceLocation: SourceLocation,
  43421. TokContext: TokContext,
  43422. Token: Token,
  43423. TokenType: TokenType,
  43424. defaultOptions: defaultOptions,
  43425. getLineInfo: getLineInfo,
  43426. isIdentifierChar: isIdentifierChar,
  43427. isIdentifierStart: isIdentifierStart,
  43428. isNewLine: isNewLine,
  43429. keywordTypes: keywords$1,
  43430. lineBreak: lineBreak,
  43431. lineBreakG: lineBreakG,
  43432. nonASCIIwhitespace: nonASCIIwhitespace,
  43433. parse: parse$b,
  43434. parseExpressionAt: parseExpressionAt,
  43435. tokContexts: types$1,
  43436. tokTypes: types,
  43437. tokenizer: tokenizer,
  43438. version: version
  43439. };
  43440. const getPrototype = Object.getPrototypeOf || (o => o.__proto__);
  43441. const getAcorn = Parser => {
  43442. if (Parser.acorn) return Parser.acorn
  43443. const acorn = acorn$1.exports;
  43444. if (acorn.version.indexOf("6.") != 0 && acorn.version.indexOf("6.0.") == 0 && acorn.version.indexOf("7.") != 0) {
  43445. throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn.version}`)
  43446. }
  43447. // Make sure `Parser` comes from the same acorn as we `require`d,
  43448. // otherwise the comparisons fail.
  43449. for (let cur = Parser; cur && cur !== acorn.Parser; cur = getPrototype(cur)) {
  43450. if (cur !== acorn.Parser) {
  43451. throw new Error("acorn-private-class-elements does not support mixing different acorn copies")
  43452. }
  43453. }
  43454. return acorn
  43455. };
  43456. var acornPrivateClassElements = function(Parser) {
  43457. // Only load this plugin once.
  43458. if (Parser.prototype.parsePrivateName) {
  43459. return Parser
  43460. }
  43461. const acorn = getAcorn(Parser);
  43462. Parser = class extends Parser {
  43463. _branch() {
  43464. this.__branch = this.__branch || new Parser({ecmaVersion: this.options.ecmaVersion}, this.input);
  43465. this.__branch.end = this.end;
  43466. this.__branch.pos = this.pos;
  43467. this.__branch.type = this.type;
  43468. this.__branch.value = this.value;
  43469. this.__branch.containsEsc = this.containsEsc;
  43470. return this.__branch
  43471. }
  43472. parsePrivateClassElementName(element) {
  43473. element.computed = false;
  43474. element.key = this.parsePrivateName();
  43475. if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
  43476. const accept = {get: "set", set: "get"}[element.kind];
  43477. const privateBoundNames = this._privateBoundNames;
  43478. if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
  43479. this.raise(element.start, "Duplicate private element");
  43480. }
  43481. privateBoundNames[element.key.name] = element.kind || true;
  43482. delete this._unresolvedPrivateNames[element.key.name];
  43483. return element.key
  43484. }
  43485. parsePrivateName() {
  43486. const node = this.startNode();
  43487. node.name = this.value;
  43488. this.next();
  43489. this.finishNode(node, "PrivateIdentifier");
  43490. if (this.options.allowReserved == "never") this.checkUnreserved(node);
  43491. return node
  43492. }
  43493. // Parse # token
  43494. getTokenFromCode(code) {
  43495. if (code === 35) {
  43496. ++this.pos;
  43497. const word = this.readWord1();
  43498. return this.finishToken(this.privateIdentifierToken, word)
  43499. }
  43500. return super.getTokenFromCode(code)
  43501. }
  43502. // Manage stacks and check for undeclared private names
  43503. parseClass(node, isStatement) {
  43504. const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
  43505. this._outerPrivateBoundNames = this._privateBoundNames;
  43506. this._privateBoundNames = Object.create(this._privateBoundNames || null);
  43507. const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  43508. this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
  43509. this._unresolvedPrivateNames = Object.create(null);
  43510. const _return = super.parseClass(node, isStatement);
  43511. const unresolvedPrivateNames = this._unresolvedPrivateNames;
  43512. this._privateBoundNames = this._outerPrivateBoundNames;
  43513. this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
  43514. this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  43515. this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
  43516. if (!this._unresolvedPrivateNames) {
  43517. const names = Object.keys(unresolvedPrivateNames);
  43518. if (names.length) {
  43519. names.sort((n1, n2) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
  43520. this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
  43521. }
  43522. } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
  43523. return _return
  43524. }
  43525. // Class heritage is evaluated with outer private environment
  43526. parseClassSuper(node) {
  43527. const privateBoundNames = this._privateBoundNames;
  43528. this._privateBoundNames = this._outerPrivateBoundNames;
  43529. const unresolvedPrivateNames = this._unresolvedPrivateNames;
  43530. this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  43531. const _return = super.parseClassSuper(node);
  43532. this._privateBoundNames = privateBoundNames;
  43533. this._unresolvedPrivateNames = unresolvedPrivateNames;
  43534. return _return
  43535. }
  43536. // Parse private element access
  43537. parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
  43538. const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
  43539. const branch = this._branch();
  43540. if (!(
  43541. (branch.eat(acorn.tokTypes.dot) || (optionalSupported && branch.eat(acorn.tokTypes.questionDot))) &&
  43542. branch.type == this.privateIdentifierToken
  43543. )) {
  43544. return super.parseSubscript.apply(this, arguments)
  43545. }
  43546. let optional = false;
  43547. if (!this.eat(acorn.tokTypes.dot)) {
  43548. this.expect(acorn.tokTypes.questionDot);
  43549. optional = true;
  43550. }
  43551. let node = this.startNodeAt(startPos, startLoc);
  43552. node.object = base;
  43553. node.computed = false;
  43554. if (optionalSupported) {
  43555. node.optional = optional;
  43556. }
  43557. if (this.type == this.privateIdentifierToken) {
  43558. if (base.type == "Super") {
  43559. this.raise(this.start, "Cannot access private element on super");
  43560. }
  43561. node.property = this.parsePrivateName();
  43562. if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
  43563. if (!this._unresolvedPrivateNames) {
  43564. this.raise(node.property.start, "Usage of undeclared private name");
  43565. }
  43566. this._unresolvedPrivateNames[node.property.name] = node.property.start;
  43567. }
  43568. } else {
  43569. node.property = this.parseIdent(true);
  43570. }
  43571. return this.finishNode(node, "MemberExpression")
  43572. }
  43573. // Prohibit delete of private class elements
  43574. parseMaybeUnary(refDestructuringErrors, sawUnary) {
  43575. const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
  43576. if (_return.operator == "delete") {
  43577. if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateIdentifier") {
  43578. this.raise(_return.start, "Private elements may not be deleted");
  43579. }
  43580. }
  43581. return _return
  43582. }
  43583. };
  43584. Parser.prototype.privateIdentifierToken = new acorn.TokenType("privateIdentifier");
  43585. return Parser
  43586. };
  43587. const privateClassElements$1 = acornPrivateClassElements;
  43588. var acornClassFields = function(Parser) {
  43589. const acorn = Parser.acorn || acorn$1.exports;
  43590. const tt = acorn.tokTypes;
  43591. Parser = privateClassElements$1(Parser);
  43592. return class extends Parser {
  43593. _maybeParseFieldValue(field) {
  43594. if (this.eat(tt.eq)) {
  43595. const oldInFieldValue = this._inFieldValue;
  43596. this._inFieldValue = true;
  43597. if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
  43598. field.value = this.parseAwait();
  43599. } else field.value = this.parseExpression();
  43600. this._inFieldValue = oldInFieldValue;
  43601. } else field.value = null;
  43602. }
  43603. // Parse fields
  43604. parseClassElement(_constructorAllowsSuper) {
  43605. if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateIdentifierToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
  43606. const branch = this._branch();
  43607. if (branch.type == tt.bracketL) {
  43608. let count = 0;
  43609. do {
  43610. if (branch.eat(tt.bracketL)) ++count;
  43611. else if (branch.eat(tt.bracketR)) --count;
  43612. else branch.next();
  43613. } while (count > 0)
  43614. } else branch.next(true);
  43615. let isField = branch.type == tt.eq || branch.type == tt.semi;
  43616. if (!isField && branch.canInsertSemicolon()) {
  43617. isField = branch.type != tt.parenL;
  43618. }
  43619. if (isField) {
  43620. const node = this.startNode();
  43621. if (this.type == this.privateIdentifierToken) {
  43622. this.parsePrivateClassElementName(node);
  43623. } else {
  43624. this.parsePropertyName(node);
  43625. }
  43626. if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
  43627. (node.key.type === "Literal" && node.key.value === "constructor")) {
  43628. this.raise(node.key.start, "Classes may not have a field called constructor");
  43629. }
  43630. this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
  43631. this._maybeParseFieldValue(node);
  43632. this.exitScope();
  43633. this.finishNode(node, "PropertyDefinition");
  43634. this.semicolon();
  43635. return node
  43636. }
  43637. }
  43638. return super.parseClassElement.apply(this, arguments)
  43639. }
  43640. // Prohibit arguments in class field initializers
  43641. parseIdent(liberal, isBinding) {
  43642. const ident = super.parseIdent(liberal, isBinding);
  43643. if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
  43644. return ident
  43645. }
  43646. }
  43647. };
  43648. function withoutAcornBigInt(acorn, Parser) {
  43649. return class extends Parser {
  43650. readInt(radix, len) {
  43651. // Hack: len is only != null for unicode escape sequences,
  43652. // where numeric separators are not allowed
  43653. if (len != null) return super.readInt(radix, len)
  43654. let start = this.pos, total = 0, acceptUnderscore = false;
  43655. for (;;) {
  43656. let code = this.input.charCodeAt(this.pos), val;
  43657. if (code >= 97) val = code - 97 + 10; // a
  43658. else if (code == 95) {
  43659. if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
  43660. ++this.pos;
  43661. acceptUnderscore = false;
  43662. continue
  43663. } else if (code >= 65) val = code - 65 + 10; // A
  43664. else if (code >= 48 && code <= 57) val = code - 48; // 0-9
  43665. else val = Infinity;
  43666. if (val >= radix) break
  43667. ++this.pos;
  43668. total = total * radix + val;
  43669. acceptUnderscore = true;
  43670. }
  43671. if (this.pos === start) return null
  43672. if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
  43673. return total
  43674. }
  43675. readNumber(startsWithDot) {
  43676. const token = super.readNumber(startsWithDot);
  43677. let octal = this.end - this.start >= 2 && this.input.charCodeAt(this.start) === 48;
  43678. const stripped = this.getNumberInput(this.start, this.end);
  43679. if (stripped.length < this.end - this.start) {
  43680. if (octal) this.raise(this.start, "Invalid number");
  43681. this.value = parseFloat(stripped);
  43682. }
  43683. return token
  43684. }
  43685. // This is used by acorn-bigint
  43686. getNumberInput(start, end) {
  43687. return this.input.slice(start, end).replace(/_/g, "")
  43688. }
  43689. }
  43690. }
  43691. function withAcornBigInt(acorn, Parser) {
  43692. return class extends Parser {
  43693. readInt(radix, len) {
  43694. // Hack: len is only != null for unicode escape sequences,
  43695. // where numeric separators are not allowed
  43696. if (len != null) return super.readInt(radix, len)
  43697. let start = this.pos, total = 0, acceptUnderscore = false;
  43698. for (;;) {
  43699. let code = this.input.charCodeAt(this.pos), val;
  43700. if (code >= 97) val = code - 97 + 10; // a
  43701. else if (code == 95) {
  43702. if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
  43703. ++this.pos;
  43704. acceptUnderscore = false;
  43705. continue
  43706. } else if (code >= 65) val = code - 65 + 10; // A
  43707. else if (code >= 48 && code <= 57) val = code - 48; // 0-9
  43708. else val = Infinity;
  43709. if (val >= radix) break
  43710. ++this.pos;
  43711. total = total * radix + val;
  43712. acceptUnderscore = true;
  43713. }
  43714. if (this.pos === start) return null
  43715. if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
  43716. return total
  43717. }
  43718. readNumber(startsWithDot) {
  43719. let start = this.pos;
  43720. if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
  43721. let octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  43722. let octalLike = false;
  43723. if (octal && this.strict) this.raise(start, "Invalid number");
  43724. let next = this.input.charCodeAt(this.pos);
  43725. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  43726. let str = this.getNumberInput(start, this.pos);
  43727. // eslint-disable-next-line node/no-unsupported-features/es-builtins
  43728. let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
  43729. ++this.pos;
  43730. if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
  43731. return this.finishToken(acorn.tokTypes.num, val)
  43732. }
  43733. if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
  43734. octal = false;
  43735. octalLike = true;
  43736. }
  43737. if (next === 46 && !octal) { // '.'
  43738. ++this.pos;
  43739. this.readInt(10);
  43740. next = this.input.charCodeAt(this.pos);
  43741. }
  43742. if ((next === 69 || next === 101) && !octal) { // 'eE'
  43743. next = this.input.charCodeAt(++this.pos);
  43744. if (next === 43 || next === 45) ++this.pos; // '+-'
  43745. if (this.readInt(10) === null) this.raise(start, "Invalid number");
  43746. }
  43747. if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
  43748. let str = this.getNumberInput(start, this.pos);
  43749. if ((octal || octalLike) && str.length < this.pos - start) {
  43750. this.raise(start, "Invalid number");
  43751. }
  43752. let val = octal ? parseInt(str, 8) : parseFloat(str);
  43753. return this.finishToken(acorn.tokTypes.num, val)
  43754. }
  43755. parseLiteral(value) {
  43756. const ret = super.parseLiteral(value);
  43757. if (ret.bigint) ret.bigint = ret.bigint.replace(/_/g, "");
  43758. return ret
  43759. }
  43760. readRadixNumber(radix) {
  43761. let start = this.pos;
  43762. this.pos += 2; // 0x
  43763. let val = this.readInt(radix);
  43764. if (val == null) { this.raise(this.start + 2, `Expected number in radix ${radix}`); }
  43765. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  43766. let str = this.getNumberInput(start, this.pos);
  43767. // eslint-disable-next-line node/no-unsupported-features/es-builtins
  43768. val = typeof BigInt !== "undefined" ? BigInt(str) : null;
  43769. ++this.pos;
  43770. } else if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  43771. return this.finishToken(acorn.tokTypes.num, val)
  43772. }
  43773. // This is used by acorn-bigint, which theoretically could be used with acorn@6.2 || acorn@7
  43774. getNumberInput(start, end) {
  43775. return this.input.slice(start, end).replace(/_/g, "")
  43776. }
  43777. }
  43778. }
  43779. // eslint-disable-next-line node/no-unsupported-features/es-syntax
  43780. function numericSeparator(Parser) {
  43781. const acorn = Parser.acorn || require("acorn");
  43782. const withAcornBigIntSupport = (acorn.version.startsWith("6.") && !(acorn.version.startsWith("6.0.") || acorn.version.startsWith("6.1."))) || acorn.version.startsWith("7.");
  43783. return withAcornBigIntSupport ? withAcornBigInt(acorn, Parser) : withoutAcornBigInt(acorn, Parser)
  43784. }
  43785. const privateClassElements = acornPrivateClassElements;
  43786. var acornStaticClassFeatures = function(Parser) {
  43787. const ExtendedParser = privateClassElements(Parser);
  43788. const acorn = Parser.acorn || acorn$1.exports;
  43789. const tt = acorn.tokTypes;
  43790. return class extends ExtendedParser {
  43791. _maybeParseFieldValue(field) {
  43792. if (this.eat(tt.eq)) {
  43793. const oldInFieldValue = this._inStaticFieldScope;
  43794. this._inStaticFieldScope = this.currentThisScope();
  43795. field.value = this.parseExpression();
  43796. this._inStaticFieldScope = oldInFieldValue;
  43797. } else field.value = null;
  43798. }
  43799. // Parse fields
  43800. parseClassElement(_constructorAllowsSuper) {
  43801. if (this.options.ecmaVersion < 8 || !this.isContextual("static")) {
  43802. return super.parseClassElement.apply(this, arguments)
  43803. }
  43804. const branch = this._branch();
  43805. branch.next();
  43806. if ([tt.name, tt.bracketL, tt.string, tt.num, this.privateIdentifierToken].indexOf(branch.type) == -1 && !branch.type.keyword) {
  43807. return super.parseClassElement.apply(this, arguments)
  43808. }
  43809. if (branch.type == tt.bracketL) {
  43810. let count = 0;
  43811. do {
  43812. if (branch.eat(tt.bracketL)) ++count;
  43813. else if (branch.eat(tt.bracketR)) --count;
  43814. else branch.next();
  43815. } while (count > 0)
  43816. } else branch.next();
  43817. if (branch.type != tt.eq && !branch.canInsertSemicolon() && branch.type != tt.semi) {
  43818. return super.parseClassElement.apply(this, arguments)
  43819. }
  43820. const node = this.startNode();
  43821. node.static = this.eatContextual("static");
  43822. if (this.type == this.privateIdentifierToken) {
  43823. this.parsePrivateClassElementName(node);
  43824. } else {
  43825. this.parsePropertyName(node);
  43826. }
  43827. if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
  43828. (node.key.type === "Literal" && !node.computed && node.key.value === "constructor")) {
  43829. this.raise(node.key.start, "Classes may not have a field called constructor");
  43830. }
  43831. if ((node.key.name || node.key.value) === "prototype" && !node.computed) {
  43832. this.raise(node.key.start, "Classes may not have a static property named prototype");
  43833. }
  43834. this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
  43835. this._maybeParseFieldValue(node);
  43836. this.exitScope();
  43837. this.finishNode(node, "PropertyDefinition");
  43838. this.semicolon();
  43839. return node
  43840. }
  43841. // Parse private static methods
  43842. parsePropertyName(prop) {
  43843. if (prop.static && this.type == this.privateIdentifierToken) {
  43844. this.parsePrivateClassElementName(prop);
  43845. } else {
  43846. super.parsePropertyName(prop);
  43847. }
  43848. }
  43849. // Prohibit arguments in class field initializers
  43850. parseIdent(liberal, isBinding) {
  43851. const ident = super.parseIdent(liberal, isBinding);
  43852. if (this._inStaticFieldScope && this.currentThisScope() === this._inStaticFieldScope && ident.name == "arguments") {
  43853. this.raise(ident.start, "A static class field initializer may not contain arguments");
  43854. }
  43855. return ident
  43856. }
  43857. }
  43858. };
  43859. var ansiRegex$1 = ({onlyFirst = false} = {}) => {
  43860. const pattern = [
  43861. '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
  43862. '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
  43863. ].join('|');
  43864. return new RegExp(pattern, onlyFirst ? undefined : 'g');
  43865. };
  43866. const ansiRegex = ansiRegex$1;
  43867. var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
  43868. function prepareError(err) {
  43869. // only copy the information we need and avoid serializing unnecessary
  43870. // properties, since some errors may attach full objects (e.g. PostCSS)
  43871. return {
  43872. message: stripAnsi(err.message),
  43873. stack: stripAnsi(cleanStack(err.stack || '')),
  43874. id: err.id,
  43875. frame: stripAnsi(err.frame || ''),
  43876. plugin: err.plugin,
  43877. pluginCode: err.pluginCode,
  43878. loc: err.loc
  43879. };
  43880. }
  43881. function buildErrorMessage(err, args = [], includeStack = true) {
  43882. if (err.plugin)
  43883. args.push(` Plugin: ${source.magenta(err.plugin)}`);
  43884. if (err.id)
  43885. args.push(` File: ${source.cyan(err.id)}`);
  43886. if (err.frame)
  43887. args.push(source.yellow(pad$1(err.frame)));
  43888. if (includeStack && err.stack)
  43889. args.push(pad$1(cleanStack(err.stack)));
  43890. return args.join('\n');
  43891. }
  43892. function cleanStack(stack) {
  43893. return stack
  43894. .split(/\n/g)
  43895. .filter((l) => /^\s*at/.test(l))
  43896. .join('\n');
  43897. }
  43898. function errorMiddleware(server, allowNext = false) {
  43899. // note the 4 args must be kept for connect to treat this as error middleware
  43900. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  43901. return function viteErrorMiddleware(err, _req, res, next) {
  43902. const msg = buildErrorMessage(err, [
  43903. source.red(`Internal server error: ${err.message}`)
  43904. ]);
  43905. server.config.logger.error(msg, {
  43906. clear: true,
  43907. timestamp: true,
  43908. error: err
  43909. });
  43910. server.ws.send({
  43911. type: 'error',
  43912. err: prepareError(err)
  43913. });
  43914. if (allowNext) {
  43915. next();
  43916. }
  43917. else {
  43918. if (err instanceof AccessRestrictedError) {
  43919. res.statusCode = 403;
  43920. res.write(renderErrorHTML(err.message));
  43921. res.end();
  43922. }
  43923. res.statusCode = 500;
  43924. res.end();
  43925. }
  43926. };
  43927. }
  43928. class AccessRestrictedError extends Error {
  43929. constructor(msg) {
  43930. super(msg);
  43931. }
  43932. }
  43933. function renderErrorHTML(msg) {
  43934. // to have syntax highlighting and autocompletion in IDE
  43935. const html = String.raw;
  43936. return html `
  43937. <body>
  43938. <h1>403 Restricted</h1>
  43939. <p>${msg.replace(/\n/g, '<br/>')}</p>
  43940. <style>
  43941. body {
  43942. padding: 1em 2em;
  43943. }
  43944. </style>
  43945. </body>
  43946. `;
  43947. }
  43948. /**
  43949. * This file is refactored into TypeScript based on
  43950. * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
  43951. */
  43952. let parser = Parser.extend(acornClassFields, acornStaticClassFeatures, numericSeparator);
  43953. async function createPluginContainer({ plugins, logger, root, build: { rollupOptions } }, watcher) {
  43954. const isDebug = process.env.DEBUG;
  43955. const seenResolves = {};
  43956. const debugResolve = createDebugger('vite:resolve');
  43957. const debugPluginResolve = createDebugger('vite:plugin-resolve', {
  43958. onlyWhenFocused: 'vite:plugin'
  43959. });
  43960. const debugPluginTransform = createDebugger('vite:plugin-transform', {
  43961. onlyWhenFocused: 'vite:plugin'
  43962. });
  43963. // ---------------------------------------------------------------------------
  43964. const MODULES = new Map();
  43965. const watchFiles = new Set();
  43966. // get rollup version
  43967. const rollupPkgPath = path$w.resolve(require.resolve('rollup'), '../../package.json');
  43968. const minimalContext = {
  43969. meta: {
  43970. rollupVersion: JSON.parse(fs__default.readFileSync(rollupPkgPath, 'utf-8'))
  43971. .version,
  43972. watchMode: true
  43973. }
  43974. };
  43975. function warnIncompatibleMethod(method, plugin) {
  43976. logger.warn(source.cyan(`[plugin:${plugin}] `) +
  43977. source.yellow(`context method ${source.bold(`${method}()`)} is not supported in serve mode. This plugin is likely not vite-compatible.`));
  43978. }
  43979. // we should create a new context for each async hook pipeline so that the
  43980. // active plugin in that pipeline can be tracked in a concurrency-safe manner.
  43981. // using a class to make creating new contexts more efficient
  43982. class Context {
  43983. constructor(initialPlugin) {
  43984. this.meta = minimalContext.meta;
  43985. this.ssr = false;
  43986. this._activeId = null;
  43987. this._activeCode = null;
  43988. this._addedImports = null;
  43989. this._activePlugin = initialPlugin || null;
  43990. }
  43991. parse(code, opts = {}) {
  43992. return parser.parse(code, {
  43993. sourceType: 'module',
  43994. ecmaVersion: 2020,
  43995. locations: true,
  43996. ...opts
  43997. });
  43998. }
  43999. async resolve(id, importer, options) {
  44000. let skips;
  44001. if ((options === null || options === void 0 ? void 0 : options.skipSelf) && this._activePlugin) {
  44002. skips = new Set(this._resolveSkips);
  44003. skips.add(this._activePlugin);
  44004. }
  44005. let out = await container.resolveId(id, importer, skips, this.ssr);
  44006. if (typeof out === 'string')
  44007. out = { id: out };
  44008. return out;
  44009. }
  44010. getModuleInfo(id) {
  44011. let mod = MODULES.get(id);
  44012. if (mod)
  44013. return mod.info;
  44014. mod = {
  44015. /** @type {import('rollup').ModuleInfo} */
  44016. // @ts-ignore-next
  44017. info: {}
  44018. };
  44019. MODULES.set(id, mod);
  44020. return mod.info;
  44021. }
  44022. getModuleIds() {
  44023. return MODULES.keys();
  44024. }
  44025. addWatchFile(id) {
  44026. watchFiles.add(id);
  44027. (this._addedImports || (this._addedImports = new Set())).add(id);
  44028. if (watcher)
  44029. ensureWatchedFile(watcher, id, root);
  44030. }
  44031. getWatchFiles() {
  44032. return [...watchFiles];
  44033. }
  44034. emitFile(assetOrFile) {
  44035. warnIncompatibleMethod(`emitFile`, this._activePlugin.name);
  44036. return '';
  44037. }
  44038. setAssetSource() {
  44039. warnIncompatibleMethod(`setAssetSource`, this._activePlugin.name);
  44040. }
  44041. getFileName() {
  44042. warnIncompatibleMethod(`getFileName`, this._activePlugin.name);
  44043. return '';
  44044. }
  44045. warn(e, position) {
  44046. const err = formatError(e, position, this);
  44047. const msg = buildErrorMessage(err, [source.yellow(`warning: ${err.message}`)], false);
  44048. logger.warn(msg, {
  44049. clear: true,
  44050. timestamp: true
  44051. });
  44052. }
  44053. error(e, position) {
  44054. // error thrown here is caught by the transform middleware and passed on
  44055. // the the error middleware.
  44056. throw formatError(e, position, this);
  44057. }
  44058. }
  44059. function formatError(e, position, ctx) {
  44060. const err = (typeof e === 'string' ? new Error(e) : e);
  44061. if (ctx._activePlugin)
  44062. err.plugin = ctx._activePlugin.name;
  44063. if (ctx._activeId && !err.id)
  44064. err.id = ctx._activeId;
  44065. if (ctx._activeCode) {
  44066. err.pluginCode = ctx._activeCode;
  44067. const pos = position != null
  44068. ? position
  44069. : err.pos != null
  44070. ? err.pos
  44071. : // some rollup plugins, e.g. json, sets position instead of pos
  44072. err.position;
  44073. if (pos != null) {
  44074. err.loc = err.loc || {
  44075. file: err.id,
  44076. ...numberToPos(ctx._activeCode, pos)
  44077. };
  44078. err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos);
  44079. }
  44080. else if (err.loc) {
  44081. // css preprocessors may report errors in an included file
  44082. if (!err.frame) {
  44083. let code = ctx._activeCode;
  44084. if (err.loc.file) {
  44085. err.id = normalizePath$4(err.loc.file);
  44086. try {
  44087. code = fs__default.readFileSync(err.loc.file, 'utf-8');
  44088. }
  44089. catch { }
  44090. }
  44091. err.frame = generateCodeFrame(code, err.loc);
  44092. }
  44093. }
  44094. else if (err.line && err.column) {
  44095. err.loc = {
  44096. file: err.id,
  44097. line: err.line,
  44098. column: err.column
  44099. };
  44100. err.frame = err.frame || generateCodeFrame(ctx._activeCode, err.loc);
  44101. }
  44102. }
  44103. return err;
  44104. }
  44105. class TransformContext extends Context {
  44106. constructor(filename, code, inMap) {
  44107. super();
  44108. this.originalSourcemap = null;
  44109. this.sourcemapChain = [];
  44110. this.combinedMap = null;
  44111. this.filename = filename;
  44112. this.originalCode = code;
  44113. if (inMap) {
  44114. this.sourcemapChain.push(inMap);
  44115. }
  44116. }
  44117. _getCombinedSourcemap(createIfNull = false) {
  44118. let combinedMap = this.combinedMap;
  44119. for (let m of this.sourcemapChain) {
  44120. if (typeof m === 'string')
  44121. m = JSON.parse(m);
  44122. if (!('version' in m)) {
  44123. // empty, nullified source map
  44124. combinedMap = this.combinedMap = null;
  44125. this.sourcemapChain.length = 0;
  44126. break;
  44127. }
  44128. if (!combinedMap) {
  44129. combinedMap = m;
  44130. }
  44131. else {
  44132. combinedMap = combineSourcemaps(this.filename, [
  44133. {
  44134. ...m,
  44135. sourcesContent: combinedMap.sourcesContent
  44136. },
  44137. combinedMap
  44138. ]);
  44139. }
  44140. }
  44141. if (!combinedMap) {
  44142. return createIfNull
  44143. ? new MagicString(this.originalCode).generateMap({
  44144. includeContent: true,
  44145. hires: true,
  44146. source: this.filename
  44147. })
  44148. : null;
  44149. }
  44150. if (combinedMap !== this.combinedMap) {
  44151. this.combinedMap = combinedMap;
  44152. this.sourcemapChain.length = 0;
  44153. }
  44154. return this.combinedMap;
  44155. }
  44156. getCombinedSourcemap() {
  44157. return this._getCombinedSourcemap(true);
  44158. }
  44159. }
  44160. let closed = false;
  44161. const container = {
  44162. options: await (async () => {
  44163. let options = rollupOptions;
  44164. for (const plugin of plugins) {
  44165. if (!plugin.options)
  44166. continue;
  44167. options =
  44168. (await plugin.options.call(minimalContext, options)) || options;
  44169. }
  44170. if (options.acornInjectPlugins) {
  44171. parser = Parser.extend(...[
  44172. acornClassFields,
  44173. acornStaticClassFeatures,
  44174. numericSeparator
  44175. ].concat(options.acornInjectPlugins));
  44176. }
  44177. return {
  44178. acorn,
  44179. acornInjectPlugins: [],
  44180. ...options
  44181. };
  44182. })(),
  44183. async buildStart() {
  44184. await Promise.all(plugins.map((plugin) => {
  44185. if (plugin.buildStart) {
  44186. return plugin.buildStart.call(new Context(plugin), container.options);
  44187. }
  44188. }));
  44189. },
  44190. async resolveId(rawId, importer = path$w.join(root, 'index.html'), skips, ssr) {
  44191. const ctx = new Context();
  44192. ctx.ssr = !!ssr;
  44193. ctx._resolveSkips = skips;
  44194. const resolveStart = isDebug ? Date.now() : 0;
  44195. let id = null;
  44196. const partial = {};
  44197. for (const plugin of plugins) {
  44198. if (!plugin.resolveId)
  44199. continue;
  44200. if (skips === null || skips === void 0 ? void 0 : skips.has(plugin))
  44201. continue;
  44202. ctx._activePlugin = plugin;
  44203. const pluginResolveStart = isDebug ? Date.now() : 0;
  44204. const result = await plugin.resolveId.call(ctx, rawId, importer, {}, ssr);
  44205. if (!result)
  44206. continue;
  44207. if (typeof result === 'string') {
  44208. id = result;
  44209. }
  44210. else {
  44211. id = result.id;
  44212. Object.assign(partial, result);
  44213. }
  44214. isDebug &&
  44215. debugPluginResolve(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, root));
  44216. // resolveId() is hookFirst - first non-null result is returned.
  44217. break;
  44218. }
  44219. if (isDebug && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
  44220. const key = rawId + id;
  44221. // avoid spamming
  44222. if (!seenResolves[key]) {
  44223. seenResolves[key] = true;
  44224. debugResolve(`${timeFrom(resolveStart)} ${source.cyan(rawId)} -> ${source.dim(id)}`);
  44225. }
  44226. }
  44227. if (id) {
  44228. partial.id = isExternalUrl(id) ? id : normalizePath$4(id);
  44229. return partial;
  44230. }
  44231. else {
  44232. return null;
  44233. }
  44234. },
  44235. async load(id, ssr) {
  44236. const ctx = new Context();
  44237. ctx.ssr = !!ssr;
  44238. for (const plugin of plugins) {
  44239. if (!plugin.load)
  44240. continue;
  44241. ctx._activePlugin = plugin;
  44242. const result = await plugin.load.call(ctx, id, ssr);
  44243. if (result != null) {
  44244. return result;
  44245. }
  44246. }
  44247. return null;
  44248. },
  44249. async transform(code, id, inMap, ssr) {
  44250. const ctx = new TransformContext(id, code, inMap);
  44251. ctx.ssr = !!ssr;
  44252. for (const plugin of plugins) {
  44253. if (!plugin.transform)
  44254. continue;
  44255. ctx._activePlugin = plugin;
  44256. ctx._activeId = id;
  44257. ctx._activeCode = code;
  44258. const start = isDebug ? Date.now() : 0;
  44259. let result;
  44260. try {
  44261. result = await plugin.transform.call(ctx, code, id, ssr);
  44262. }
  44263. catch (e) {
  44264. ctx.error(e);
  44265. }
  44266. if (!result)
  44267. continue;
  44268. isDebug &&
  44269. debugPluginTransform(timeFrom(start), plugin.name, prettifyUrl(id, root));
  44270. if (isObject$3(result)) {
  44271. code = result.code || '';
  44272. if (result.map)
  44273. ctx.sourcemapChain.push(result.map);
  44274. }
  44275. else {
  44276. code = result;
  44277. }
  44278. }
  44279. return {
  44280. code,
  44281. map: ctx._getCombinedSourcemap()
  44282. };
  44283. },
  44284. watchChange(id, event = 'update') {
  44285. const ctx = new Context();
  44286. if (watchFiles.has(id)) {
  44287. for (const plugin of plugins) {
  44288. if (!plugin.watchChange)
  44289. continue;
  44290. ctx._activePlugin = plugin;
  44291. plugin.watchChange.call(ctx, id, { event });
  44292. }
  44293. }
  44294. },
  44295. async close() {
  44296. if (closed)
  44297. return;
  44298. const ctx = new Context();
  44299. await Promise.all(plugins.map((p) => p.buildEnd && p.buildEnd.call(ctx)));
  44300. await Promise.all(plugins.map((p) => p.closeBundle && p.closeBundle.call(ctx)));
  44301. closed = true;
  44302. }
  44303. };
  44304. return container;
  44305. }
  44306. const debug$a = createDebugger('vite:deps');
  44307. const htmlTypesRE = /\.(html|vue|svelte)$/;
  44308. // A simple regex to detect import sources. This is only used on
  44309. // <script lang="ts"> blocks in vue (setup only) or svelte files, since
  44310. // seemingly unused imports are dropped by esbuild when transpiling TS which
  44311. // prevents it from crawling further.
  44312. // We can't use es-module-lexer because it can't handle TS, and don't want to
  44313. // use Acorn because it's slow. Luckily this doesn't have to be bullet proof
  44314. // since even missed imports can be caught at runtime, and false positives will
  44315. // simply be ignored.
  44316. const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from\s*)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
  44317. async function scanImports(config) {
  44318. var _a, _b, _c, _d;
  44319. const s = Date.now();
  44320. let entries = [];
  44321. const explicitEntryPatterns = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.entries;
  44322. const buildInput = (_b = config.build.rollupOptions) === null || _b === void 0 ? void 0 : _b.input;
  44323. if (explicitEntryPatterns) {
  44324. entries = await globEntries(explicitEntryPatterns, config);
  44325. }
  44326. else if (buildInput) {
  44327. const resolvePath = (p) => path__default.resolve(config.root, p);
  44328. if (typeof buildInput === 'string') {
  44329. entries = [resolvePath(buildInput)];
  44330. }
  44331. else if (Array.isArray(buildInput)) {
  44332. entries = buildInput.map(resolvePath);
  44333. }
  44334. else if (isObject$3(buildInput)) {
  44335. entries = Object.values(buildInput).map(resolvePath);
  44336. }
  44337. else {
  44338. throw new Error('invalid rollupOptions.input value.');
  44339. }
  44340. }
  44341. else {
  44342. entries = await globEntries('**/*.html', config);
  44343. }
  44344. // Non-supported entry file types and virtual files should not be scanned for
  44345. // dependencies.
  44346. entries = entries.filter((entry) => (JS_TYPES_RE.test(entry) || htmlTypesRE.test(entry)) &&
  44347. fs__default.existsSync(entry));
  44348. if (!entries.length) {
  44349. config.logger.warn('Could not determine entry point from rollupOptions or html files. Skipping dependency pre-bundling.');
  44350. return { deps: {}, missing: {} };
  44351. }
  44352. else {
  44353. debug$a(`Crawling dependencies using entries:\n ${entries.join('\n ')}`);
  44354. }
  44355. const deps = {};
  44356. const missing = {};
  44357. const container = await createPluginContainer(config);
  44358. const plugin = esbuildScanPlugin(config, container, deps, missing, entries);
  44359. const { plugins = [], ...esbuildOptions } = (_d = (_c = config.optimizeDeps) === null || _c === void 0 ? void 0 : _c.esbuildOptions) !== null && _d !== void 0 ? _d : {};
  44360. await Promise.all(entries.map((entry) => esbuild.build({
  44361. absWorkingDir: process.cwd(),
  44362. write: false,
  44363. entryPoints: [entry],
  44364. bundle: true,
  44365. format: 'esm',
  44366. logLevel: 'error',
  44367. plugins: [...plugins, plugin],
  44368. ...esbuildOptions
  44369. })));
  44370. debug$a(`Scan completed in ${Date.now() - s}ms:`, deps);
  44371. return {
  44372. deps,
  44373. missing
  44374. };
  44375. }
  44376. function globEntries(pattern, config) {
  44377. return out(pattern, {
  44378. cwd: config.root,
  44379. ignore: [
  44380. '**/node_modules/**',
  44381. `**/${config.build.outDir}/**`,
  44382. `**/__tests__/**`
  44383. ],
  44384. absolute: true
  44385. });
  44386. }
  44387. const scriptModuleRE = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)(.*?)<\/script>/gims;
  44388. const scriptRE = /(<script\b(?:\s[^>]*>|>))(.*?)<\/script>/gims;
  44389. const commentRE = /<!--(.|[\r\n])*?-->/;
  44390. const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
  44391. const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
  44392. const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
  44393. function esbuildScanPlugin(config, container, depImports, missing, entries) {
  44394. var _a, _b;
  44395. const seen = new Map();
  44396. const resolve = async (id, importer) => {
  44397. const key = id + (importer && path__default.dirname(importer));
  44398. if (seen.has(key)) {
  44399. return seen.get(key);
  44400. }
  44401. const resolved = await container.resolveId(id, importer && normalizePath$4(importer));
  44402. const res = resolved === null || resolved === void 0 ? void 0 : resolved.id;
  44403. seen.set(key, res);
  44404. return res;
  44405. };
  44406. const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include;
  44407. const exclude = [
  44408. ...(((_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude) || []),
  44409. '@vite/client',
  44410. '@vite/env'
  44411. ];
  44412. const externalUnlessEntry = ({ path }) => ({
  44413. path,
  44414. external: !entries.includes(path)
  44415. });
  44416. return {
  44417. name: 'vite:dep-scan',
  44418. setup(build) {
  44419. // external urls
  44420. build.onResolve({ filter: externalRE }, ({ path }) => ({
  44421. path,
  44422. external: true
  44423. }));
  44424. // data urls
  44425. build.onResolve({ filter: dataUrlRE }, ({ path }) => ({
  44426. path,
  44427. external: true
  44428. }));
  44429. // html types: extract script contents -----------------------------------
  44430. build.onResolve({ filter: htmlTypesRE }, async ({ path, importer }) => {
  44431. return {
  44432. path: await resolve(path, importer),
  44433. namespace: 'html'
  44434. };
  44435. });
  44436. // extract scripts inside HTML-like files and treat it as a js module
  44437. build.onLoad({ filter: htmlTypesRE, namespace: 'html' }, async ({ path }) => {
  44438. let raw = fs__default.readFileSync(path, 'utf-8');
  44439. // Avoid matching the content of the comment
  44440. raw = raw.replace(commentRE, '<!---->');
  44441. const isHtml = path.endsWith('.html');
  44442. const regex = isHtml ? scriptModuleRE : scriptRE;
  44443. regex.lastIndex = 0;
  44444. let js = '';
  44445. let loader = 'js';
  44446. let match;
  44447. while ((match = regex.exec(raw))) {
  44448. const [, openTag, content] = match;
  44449. const srcMatch = openTag.match(srcRE);
  44450. const typeMatch = openTag.match(typeRE);
  44451. const langMatch = openTag.match(langRE);
  44452. const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
  44453. const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
  44454. // skip type="application/ld+json" and other non-JS types
  44455. if (type &&
  44456. !(type.includes('javascript') ||
  44457. type.includes('ecmascript') ||
  44458. type === 'module')) {
  44459. continue;
  44460. }
  44461. if (lang === 'ts' || lang === 'tsx' || lang === 'jsx') {
  44462. loader = lang;
  44463. }
  44464. if (srcMatch) {
  44465. const src = srcMatch[1] || srcMatch[2] || srcMatch[3];
  44466. js += `import ${JSON.stringify(src)}\n`;
  44467. }
  44468. else if (content.trim()) {
  44469. js += content + '\n';
  44470. }
  44471. }
  44472. // empty singleline & multiline comments to avoid matching comments
  44473. const code = js
  44474. .replace(multilineCommentsRE, '/* */')
  44475. .replace(singlelineCommentsRE, '');
  44476. if (loader.startsWith('ts') &&
  44477. (path.endsWith('.svelte') ||
  44478. (path.endsWith('.vue') && /<script\s+setup/.test(raw)))) {
  44479. // when using TS + (Vue + <script setup>) or Svelte, imports may seem
  44480. // unused to esbuild and dropped in the build output, which prevents
  44481. // esbuild from crawling further.
  44482. // the solution is to add `import 'x'` for every source to force
  44483. // esbuild to keep crawling due to potential side effects.
  44484. let m;
  44485. while ((m = importsRE.exec(code)) != null) {
  44486. // This is necessary to avoid infinite loops with zero-width matches
  44487. if (m.index === importsRE.lastIndex) {
  44488. importsRE.lastIndex++;
  44489. }
  44490. js += `\nimport ${m[1]}`;
  44491. }
  44492. }
  44493. if (!code.includes(`export default`)) {
  44494. js += `\nexport default {}`;
  44495. }
  44496. if (code.includes('import.meta.glob')) {
  44497. return {
  44498. // transformGlob already transforms to js
  44499. loader: 'js',
  44500. contents: await transformGlob(js, path, config.root, loader)
  44501. };
  44502. }
  44503. return {
  44504. loader,
  44505. contents: js
  44506. };
  44507. });
  44508. // bare imports: record and externalize ----------------------------------
  44509. build.onResolve({
  44510. // avoid matching windows volume
  44511. filter: /^[\w@][^:]/
  44512. }, async ({ path: id, importer }) => {
  44513. if (exclude === null || exclude === void 0 ? void 0 : exclude.some((e) => e === id || id.startsWith(e + '/'))) {
  44514. return externalUnlessEntry({ path: id });
  44515. }
  44516. if (depImports[id]) {
  44517. return externalUnlessEntry({ path: id });
  44518. }
  44519. const resolved = await resolve(id, importer);
  44520. if (resolved) {
  44521. if (shouldExternalizeDep(resolved, id)) {
  44522. return externalUnlessEntry({ path: id });
  44523. }
  44524. if (resolved.includes('node_modules') || (include === null || include === void 0 ? void 0 : include.includes(id))) {
  44525. // dependency or forced included, externalize and stop crawling
  44526. if (OPTIMIZABLE_ENTRY_RE.test(resolved)) {
  44527. depImports[id] = resolved;
  44528. }
  44529. return externalUnlessEntry({ path: id });
  44530. }
  44531. else {
  44532. const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
  44533. // linked package, keep crawling
  44534. return {
  44535. path: path__default.resolve(resolved),
  44536. namespace
  44537. };
  44538. }
  44539. }
  44540. else {
  44541. missing[id] = normalizePath$4(importer);
  44542. }
  44543. });
  44544. // Externalized file types -----------------------------------------------
  44545. // these are done on raw ids using esbuild's native regex filter so it
  44546. // should be faster than doing it in the catch-all via js
  44547. // they are done after the bare import resolve because a package name
  44548. // may end with these extensions
  44549. // css & json
  44550. build.onResolve({
  44551. filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json)$/
  44552. }, externalUnlessEntry);
  44553. // known asset types
  44554. build.onResolve({
  44555. filter: new RegExp(`\\.(${KNOWN_ASSET_TYPES.join('|')})$`)
  44556. }, externalUnlessEntry);
  44557. // known vite query types: ?worker, ?raw
  44558. build.onResolve({ filter: SPECIAL_QUERY_RE }, ({ path }) => ({
  44559. path,
  44560. external: true
  44561. }));
  44562. // catch all -------------------------------------------------------------
  44563. build.onResolve({
  44564. filter: /.*/
  44565. }, async ({ path: id, importer }) => {
  44566. // use vite resolver to support urls and omitted extensions
  44567. const resolved = await resolve(id, importer);
  44568. if (resolved) {
  44569. if (shouldExternalizeDep(resolved, id)) {
  44570. return externalUnlessEntry({ path: id });
  44571. }
  44572. const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
  44573. return {
  44574. path: path__default.resolve(cleanUrl(resolved)),
  44575. namespace
  44576. };
  44577. }
  44578. else {
  44579. // resolve failed... probably unsupported type
  44580. return externalUnlessEntry({ path: id });
  44581. }
  44582. });
  44583. // for jsx/tsx, we need to access the content and check for
  44584. // presence of import.meta.glob, since it results in import relationships
  44585. // but isn't crawled by esbuild.
  44586. build.onLoad({ filter: JS_TYPES_RE }, ({ path: id }) => {
  44587. let ext = path__default.extname(id).slice(1);
  44588. if (ext === 'mjs')
  44589. ext = 'js';
  44590. let contents = fs__default.readFileSync(id, 'utf-8');
  44591. if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) {
  44592. contents = config.esbuild.jsxInject + `\n` + contents;
  44593. }
  44594. if (contents.includes('import.meta.glob')) {
  44595. return transformGlob(contents, id, config.root, ext).then((contents) => ({
  44596. loader: ext,
  44597. contents
  44598. }));
  44599. }
  44600. return {
  44601. loader: ext,
  44602. contents
  44603. };
  44604. });
  44605. }
  44606. };
  44607. }
  44608. async function transformGlob(source, importer, root, loader) {
  44609. // transform the content first since es-module-lexer can't handle non-js
  44610. if (loader !== 'js') {
  44611. source = (await esbuild.transform(source, { loader })).code;
  44612. }
  44613. await init;
  44614. const imports = parse$d(source)[0];
  44615. const s = new MagicString(source);
  44616. for (let index = 0; index < imports.length; index++) {
  44617. const { s: start, e: end, ss: expStart } = imports[index];
  44618. const url = source.slice(start, end);
  44619. if (url !== 'import.meta')
  44620. continue;
  44621. if (source.slice(end, end + 5) !== '.glob')
  44622. continue;
  44623. const { importsString, exp, endIndex } = await transformImportGlob(source, start, normalizePath$4(importer), index, root);
  44624. s.prepend(importsString);
  44625. s.overwrite(expStart, endIndex, exp);
  44626. }
  44627. return s.toString();
  44628. }
  44629. function shouldExternalizeDep(resolvedId, rawId) {
  44630. // not a valid file path
  44631. if (!path__default.isAbsolute(resolvedId)) {
  44632. return true;
  44633. }
  44634. // virtual id
  44635. if (resolvedId === rawId || resolvedId.includes('\0')) {
  44636. return true;
  44637. }
  44638. // resolved is not a scannable type
  44639. if (!JS_TYPES_RE.test(resolvedId) && !htmlTypesRE.test(resolvedId)) {
  44640. return true;
  44641. }
  44642. return false;
  44643. }
  44644. /**
  44645. * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
  44646. *
  44647. * Supports tempalte string with dynamic segments:
  44648. * ```
  44649. * new URL(`./dir/${name}.png`, import.meta.url)
  44650. * // transformed to
  44651. * import.meta.globEager('./dir/**.png')[`./dir/${name}.png`].default
  44652. * ```
  44653. */
  44654. function assetImportMetaUrlPlugin(config) {
  44655. return {
  44656. name: 'asset-import-meta-url',
  44657. async transform(code, id, ssr) {
  44658. if (code.includes('new URL') && code.includes(`import.meta.url`)) {
  44659. const importMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\)/g;
  44660. const noCommentsCode = code
  44661. .replace(multilineCommentsRE, (m) => ' '.repeat(m.length))
  44662. .replace(singlelineCommentsRE, (m) => ' '.repeat(m.length));
  44663. let s = null;
  44664. let match;
  44665. while ((match = importMetaUrlRE.exec(noCommentsCode))) {
  44666. const { 0: exp, 1: rawUrl, index } = match;
  44667. if (ssr) {
  44668. this.error(`\`new URL(url, import.meta.url)\` is not supported in SSR.`, index);
  44669. }
  44670. if (!s)
  44671. s = new MagicString(code);
  44672. // potential dynamic template string
  44673. if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) {
  44674. const ast = this.parse(rawUrl);
  44675. const templateLiteral = ast.body[0].expression;
  44676. if (templateLiteral.expressions.length) {
  44677. const pattern = buildGlobPattern(templateLiteral);
  44678. // Note: native import.meta.url is not supported in the baseline
  44679. // target so we use window.location here -
  44680. s.overwrite(index, index + exp.length, `new URL(import.meta.globEagerDefault(${JSON.stringify(pattern)})[${rawUrl}], window.location)`);
  44681. continue;
  44682. }
  44683. }
  44684. const url = rawUrl.slice(1, -1);
  44685. const file = path__default.resolve(path__default.dirname(id), url);
  44686. const builtUrl = await fileToUrl(file, config, this);
  44687. s.overwrite(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, window.location)`);
  44688. }
  44689. if (s) {
  44690. return {
  44691. code: s.toString(),
  44692. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
  44693. };
  44694. }
  44695. }
  44696. return null;
  44697. }
  44698. };
  44699. }
  44700. function buildGlobPattern(ast) {
  44701. let pattern = '';
  44702. let lastElementIndex = -1;
  44703. for (const exp of ast.expressions) {
  44704. for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
  44705. const el = ast.quasis[i];
  44706. if (el.end < exp.start) {
  44707. pattern += el.value.raw;
  44708. lastElementIndex = i;
  44709. }
  44710. }
  44711. pattern += '**';
  44712. }
  44713. for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
  44714. pattern += ast.quasis[i].value.raw;
  44715. }
  44716. return pattern;
  44717. }
  44718. function loadFallbackPlugin() {
  44719. return {
  44720. name: 'load-fallback',
  44721. async load(id) {
  44722. try {
  44723. return fs$v.promises.readFile(cleanUrl(id), 'utf-8');
  44724. }
  44725. catch (e) {
  44726. return fs$v.promises.readFile(id, 'utf-8');
  44727. }
  44728. }
  44729. };
  44730. }
  44731. function resolveBuildOptions(raw) {
  44732. const resolved = {
  44733. target: 'modules',
  44734. polyfillModulePreload: true,
  44735. outDir: 'dist',
  44736. assetsDir: 'assets',
  44737. assetsInlineLimit: 4096,
  44738. cssCodeSplit: !(raw === null || raw === void 0 ? void 0 : raw.lib),
  44739. sourcemap: false,
  44740. rollupOptions: {},
  44741. commonjsOptions: {
  44742. include: [/node_modules/],
  44743. extensions: ['.js', '.cjs'],
  44744. ...raw === null || raw === void 0 ? void 0 : raw.commonjsOptions
  44745. },
  44746. dynamicImportVarsOptions: {
  44747. warnOnError: true,
  44748. exclude: [/node_modules/],
  44749. ...raw === null || raw === void 0 ? void 0 : raw.dynamicImportVarsOptions
  44750. },
  44751. minify: (raw === null || raw === void 0 ? void 0 : raw.ssr) ? false : 'terser',
  44752. terserOptions: {},
  44753. write: true,
  44754. emptyOutDir: null,
  44755. manifest: false,
  44756. lib: false,
  44757. ssr: false,
  44758. ssrManifest: false,
  44759. brotliSize: true,
  44760. chunkSizeWarningLimit: 500,
  44761. watch: null,
  44762. ...raw
  44763. };
  44764. // handle special build targets
  44765. if (resolved.target === 'modules') {
  44766. // Support browserslist
  44767. // "defaults and supports es6-module and supports es6-module-dynamic-import",
  44768. resolved.target = [
  44769. 'es2019',
  44770. 'edge88',
  44771. 'firefox78',
  44772. 'chrome87',
  44773. 'safari13.1'
  44774. ];
  44775. }
  44776. else if (resolved.target === 'esnext' && resolved.minify === 'terser') {
  44777. // esnext + terser: limit to es2019 so it can be minified by terser
  44778. resolved.target = 'es2019';
  44779. }
  44780. // normalize false string into actual false
  44781. if (resolved.minify === 'false') {
  44782. resolved.minify = false;
  44783. }
  44784. return resolved;
  44785. }
  44786. function resolveBuildPlugins(config) {
  44787. const options = config.build;
  44788. return {
  44789. pre: [
  44790. buildHtmlPlugin(config),
  44791. commonjs(options.commonjsOptions),
  44792. dataURIPlugin(),
  44793. dynamicImportVariables(options.dynamicImportVarsOptions),
  44794. assetImportMetaUrlPlugin(config),
  44795. ...(options.rollupOptions.plugins
  44796. ? options.rollupOptions.plugins.filter((p) => !!p)
  44797. : [])
  44798. ],
  44799. post: [
  44800. buildImportAnalysisPlugin(config),
  44801. buildEsbuildPlugin(config),
  44802. ...(options.minify && options.minify !== 'esbuild'
  44803. ? [terserPlugin(options.terserOptions)]
  44804. : []),
  44805. ...(options.manifest ? [manifestPlugin(config)] : []),
  44806. ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),
  44807. buildReporterPlugin(config),
  44808. loadFallbackPlugin()
  44809. ]
  44810. };
  44811. }
  44812. /**
  44813. * Track parallel build calls and only stop the esbuild service when all
  44814. * builds are done. (#1098)
  44815. */
  44816. let parallelCallCounts = 0;
  44817. // we use a separate counter to track since the call may error before the
  44818. // bundle is even pushed.
  44819. const parallelBuilds = [];
  44820. /**
  44821. * Bundles the app for production.
  44822. * Returns a Promise containing the build result.
  44823. */
  44824. async function build(inlineConfig = {}) {
  44825. parallelCallCounts++;
  44826. try {
  44827. return await doBuild(inlineConfig);
  44828. }
  44829. finally {
  44830. parallelCallCounts--;
  44831. if (parallelCallCounts <= 0) {
  44832. await Promise.all(parallelBuilds.map((bundle) => bundle.close()));
  44833. parallelBuilds.length = 0;
  44834. }
  44835. }
  44836. }
  44837. async function doBuild(inlineConfig = {}) {
  44838. var _a, _b, _c, _d;
  44839. const config = await resolveConfig(inlineConfig, 'build', 'production');
  44840. const options = config.build;
  44841. const ssr = !!options.ssr;
  44842. const libOptions = options.lib;
  44843. config.logger.info(source.cyan(`vite v${require('vite/package.json').version} ${source.green(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)}`));
  44844. const resolve = (p) => path__default.resolve(config.root, p);
  44845. const input = libOptions
  44846. ? resolve(libOptions.entry)
  44847. : typeof options.ssr === 'string'
  44848. ? resolve(options.ssr)
  44849. : ((_a = options.rollupOptions) === null || _a === void 0 ? void 0 : _a.input) || resolve('index.html');
  44850. if (ssr && typeof input === 'string' && input.endsWith('.html')) {
  44851. throw new Error(`rollupOptions.input should not be an html file when building for SSR. ` +
  44852. `Please specify a dedicated SSR entry.`);
  44853. }
  44854. const outDir = resolve(options.outDir);
  44855. // inject ssr arg to plugin load/transform hooks
  44856. const plugins = (ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins);
  44857. // inject ssrExternal if present
  44858. const userExternal = (_b = options.rollupOptions) === null || _b === void 0 ? void 0 : _b.external;
  44859. let external = userExternal;
  44860. if (ssr) {
  44861. // see if we have cached deps data available
  44862. let knownImports;
  44863. if (config.cacheDir) {
  44864. const dataPath = path__default.join(config.cacheDir, '_metadata.json');
  44865. try {
  44866. const data = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8'));
  44867. knownImports = Object.keys(data.optimized);
  44868. }
  44869. catch (e) { }
  44870. }
  44871. if (!knownImports) {
  44872. // no dev deps optimization data, do a fresh scan
  44873. knownImports = Object.keys((await scanImports(config)).deps);
  44874. }
  44875. external = resolveExternal(resolveSSRExternal(config, knownImports), userExternal);
  44876. }
  44877. const rollup = require('rollup');
  44878. const rollupOptions = {
  44879. input,
  44880. preserveEntrySignatures: ssr
  44881. ? 'allow-extension'
  44882. : libOptions
  44883. ? 'strict'
  44884. : false,
  44885. ...options.rollupOptions,
  44886. plugins,
  44887. external,
  44888. onwarn(warning, warn) {
  44889. onRollupWarning(warning, warn, config);
  44890. }
  44891. };
  44892. const outputBuildError = (e) => {
  44893. let msg = source.red((e.plugin ? `[${e.plugin}] ` : '') + e.message);
  44894. if (e.id) {
  44895. msg += `\nfile: ${source.cyan(e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ''))}`;
  44896. }
  44897. if (e.frame) {
  44898. msg += `\n` + source.yellow(e.frame);
  44899. }
  44900. config.logger.error(msg, { error: e });
  44901. };
  44902. try {
  44903. const pkgName = libOptions && getPkgName(config.root);
  44904. const buildOutputOptions = (output = {}) => {
  44905. return {
  44906. dir: outDir,
  44907. format: ssr ? 'cjs' : 'es',
  44908. exports: ssr ? 'named' : 'auto',
  44909. sourcemap: options.sourcemap,
  44910. name: libOptions ? libOptions.name : undefined,
  44911. entryFileNames: ssr
  44912. ? `[name].js`
  44913. : libOptions
  44914. ? resolveLibFilename(libOptions, output.format || 'es', pkgName)
  44915. : path__default.posix.join(options.assetsDir, `[name].[hash].js`),
  44916. chunkFileNames: libOptions
  44917. ? `[name].js`
  44918. : path__default.posix.join(options.assetsDir, `[name].[hash].js`),
  44919. assetFileNames: libOptions
  44920. ? `[name].[ext]`
  44921. : path__default.posix.join(options.assetsDir, `[name].[hash].[ext]`),
  44922. // #764 add `Symbol.toStringTag` when build es module into cjs chunk
  44923. // #1048 add `Symbol.toStringTag` for module default export
  44924. namespaceToStringTag: true,
  44925. inlineDynamicImports: ssr && typeof input === 'string',
  44926. manualChunks: !ssr &&
  44927. !libOptions &&
  44928. (output === null || output === void 0 ? void 0 : output.format) !== 'umd' &&
  44929. (output === null || output === void 0 ? void 0 : output.format) !== 'iife'
  44930. ? createMoveToVendorChunkFn()
  44931. : undefined,
  44932. ...output
  44933. };
  44934. };
  44935. // resolve lib mode outputs
  44936. const outputs = resolveBuildOutputs((_c = options.rollupOptions) === null || _c === void 0 ? void 0 : _c.output, libOptions, config.logger);
  44937. // watch file changes with rollup
  44938. if (config.build.watch) {
  44939. config.logger.info(source.cyanBright(`\nwatching for file changes...`));
  44940. const output = [];
  44941. if (Array.isArray(outputs)) {
  44942. for (const resolvedOutput of outputs) {
  44943. output.push(buildOutputOptions(resolvedOutput));
  44944. }
  44945. }
  44946. else {
  44947. output.push(buildOutputOptions(outputs));
  44948. }
  44949. const watcherOptions = config.build.watch;
  44950. const watcher = rollup.watch({
  44951. ...rollupOptions,
  44952. output,
  44953. watch: {
  44954. ...watcherOptions,
  44955. chokidar: {
  44956. ignored: [
  44957. '**/node_modules/**',
  44958. '**/.git/**',
  44959. ...(((_d = watcherOptions === null || watcherOptions === void 0 ? void 0 : watcherOptions.chokidar) === null || _d === void 0 ? void 0 : _d.ignored) || [])
  44960. ],
  44961. ignoreInitial: true,
  44962. ignorePermissionErrors: true,
  44963. ...watcherOptions.chokidar
  44964. }
  44965. }
  44966. });
  44967. watcher.on('event', (event) => {
  44968. if (event.code === 'BUNDLE_START') {
  44969. config.logger.info(source.cyanBright(`\nbuild started...`));
  44970. if (options.write) {
  44971. prepareOutDir(outDir, options.emptyOutDir, config);
  44972. }
  44973. }
  44974. else if (event.code === 'BUNDLE_END') {
  44975. event.result.close();
  44976. config.logger.info(source.cyanBright(`built in ${event.duration}ms.`));
  44977. }
  44978. else if (event.code === 'ERROR') {
  44979. outputBuildError(event.error);
  44980. }
  44981. });
  44982. // stop watching
  44983. watcher.close();
  44984. return watcher;
  44985. }
  44986. // write or generate files with rollup
  44987. const bundle = await rollup.rollup(rollupOptions);
  44988. parallelBuilds.push(bundle);
  44989. const generate = (output = {}) => {
  44990. return bundle[options.write ? 'write' : 'generate'](buildOutputOptions(output));
  44991. };
  44992. if (options.write) {
  44993. prepareOutDir(outDir, options.emptyOutDir, config);
  44994. }
  44995. if (Array.isArray(outputs)) {
  44996. const res = [];
  44997. for (const output of outputs) {
  44998. res.push(await generate(output));
  44999. }
  45000. return res;
  45001. }
  45002. else {
  45003. return await generate(outputs);
  45004. }
  45005. }
  45006. catch (e) {
  45007. outputBuildError(e);
  45008. throw e;
  45009. }
  45010. }
  45011. function prepareOutDir(outDir, emptyOutDir, config) {
  45012. if (fs__default.existsSync(outDir)) {
  45013. if (emptyOutDir == null &&
  45014. !normalizePath$4(outDir).startsWith(config.root + '/')) {
  45015. // warn if outDir is outside of root
  45016. config.logger.warn(source.yellow(`\n${source.bold(`(!)`)} outDir ${source.white.dim(outDir)} is not inside project root and will not be emptied.\n` +
  45017. `Use --emptyOutDir to override.\n`));
  45018. }
  45019. else if (emptyOutDir !== false) {
  45020. emptyDir(outDir, ['.git']);
  45021. }
  45022. }
  45023. if (config.publicDir && fs__default.existsSync(config.publicDir)) {
  45024. copyDir(config.publicDir, outDir);
  45025. }
  45026. }
  45027. function getPkgName(root) {
  45028. const { name } = JSON.parse(lookupFile(root, ['package.json']) || `{}`);
  45029. if (!name)
  45030. throw new Error('no name found in package.json');
  45031. return name.startsWith('@') ? name.split('/')[1] : name;
  45032. }
  45033. function createMoveToVendorChunkFn(config) {
  45034. const cache = new Map();
  45035. return (id, { getModuleInfo }) => {
  45036. if (id.includes('node_modules') &&
  45037. !isCSSRequest(id) &&
  45038. staticImportedByEntry(id, getModuleInfo, cache)) {
  45039. return 'vendor';
  45040. }
  45041. };
  45042. }
  45043. function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
  45044. if (cache.has(id)) {
  45045. return cache.get(id);
  45046. }
  45047. if (importStack.includes(id)) {
  45048. // circular deps!
  45049. cache.set(id, false);
  45050. return false;
  45051. }
  45052. const mod = getModuleInfo(id);
  45053. if (!mod) {
  45054. cache.set(id, false);
  45055. return false;
  45056. }
  45057. if (mod.isEntry) {
  45058. cache.set(id, true);
  45059. return true;
  45060. }
  45061. const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id)));
  45062. cache.set(id, someImporterIs);
  45063. return someImporterIs;
  45064. }
  45065. function resolveLibFilename(libOptions, format, pkgName) {
  45066. return typeof libOptions.fileName === 'function'
  45067. ? libOptions.fileName(format)
  45068. : `${libOptions.fileName || pkgName}.${format}.js`;
  45069. }
  45070. function resolveBuildOutputs(outputs, libOptions, logger) {
  45071. if (libOptions) {
  45072. const formats = libOptions.formats || ['es', 'umd'];
  45073. if ((formats.includes('umd') || formats.includes('iife')) &&
  45074. !libOptions.name) {
  45075. throw new Error(`Option "build.lib.name" is required when output formats ` +
  45076. `include "umd" or "iife".`);
  45077. }
  45078. if (!outputs) {
  45079. return formats.map((format) => ({ format }));
  45080. }
  45081. else if (!Array.isArray(outputs)) {
  45082. return formats.map((format) => ({ ...outputs, format }));
  45083. }
  45084. else if (libOptions.formats) {
  45085. // user explicitly specifying own output array
  45086. logger.warn(source.yellow(`"build.lib.formats" will be ignored because ` +
  45087. `"build.rollupOptions.output" is already an array format`));
  45088. }
  45089. }
  45090. return outputs;
  45091. }
  45092. const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
  45093. const dynamicImportWarningIgnoreList = [
  45094. `Unsupported expression`,
  45095. `statically analyzed`
  45096. ];
  45097. function onRollupWarning(warning, warn, config) {
  45098. var _a;
  45099. if (warning.code === 'UNRESOLVED_IMPORT') {
  45100. const id = warning.source;
  45101. const importer = warning.importer;
  45102. // throw unless it's commonjs external...
  45103. if (!importer || !/\?commonjs-external$/.test(importer)) {
  45104. throw new Error(`[vite]: Rollup failed to resolve import "${id}" from "${importer}".\n` +
  45105. `This is most likely unintended because it can break your application at runtime.\n` +
  45106. `If you do want to externalize this module explicitly add it to\n` +
  45107. `\`build.rollupOptions.external\``);
  45108. }
  45109. }
  45110. if (warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
  45111. dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))) {
  45112. return;
  45113. }
  45114. if (!warningIgnoreList.includes(warning.code)) {
  45115. const userOnWarn = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.onwarn;
  45116. if (userOnWarn) {
  45117. userOnWarn(warning, warn);
  45118. }
  45119. else if (warning.code === 'PLUGIN_WARNING') {
  45120. config.logger.warn(`${source.bold.yellow(`[plugin:${warning.plugin}]`)} ${source.yellow(warning.message)}`);
  45121. }
  45122. else {
  45123. warn(warning);
  45124. }
  45125. }
  45126. }
  45127. function resolveExternal(ssrExternals, user) {
  45128. return ((id, parentId, isResolved) => {
  45129. if (shouldExternalizeForSSR(id, ssrExternals)) {
  45130. return true;
  45131. }
  45132. if (user) {
  45133. if (typeof user === 'function') {
  45134. return user(id, parentId, isResolved);
  45135. }
  45136. else if (Array.isArray(user)) {
  45137. return user.some((test) => isExternal(id, test));
  45138. }
  45139. else {
  45140. return isExternal(id, user);
  45141. }
  45142. }
  45143. });
  45144. }
  45145. function isExternal(id, test) {
  45146. if (typeof test === 'string') {
  45147. return id === test;
  45148. }
  45149. else {
  45150. return test.test(id);
  45151. }
  45152. }
  45153. function injectSsrFlagToHooks(p) {
  45154. const { resolveId, load, transform } = p;
  45155. return {
  45156. ...p,
  45157. resolveId: wrapSsrHook(resolveId),
  45158. load: wrapSsrHook(load),
  45159. transform: wrapSsrHook(transform)
  45160. };
  45161. }
  45162. function wrapSsrHook(fn) {
  45163. if (!fn)
  45164. return;
  45165. return function (...args) {
  45166. return fn.call(this, ...args, true);
  45167. };
  45168. }
  45169. var build$1 = {
  45170. __proto__: null,
  45171. resolveBuildOptions: resolveBuildOptions,
  45172. resolveBuildPlugins: resolveBuildPlugins,
  45173. build: build,
  45174. resolveLibFilename: resolveLibFilename,
  45175. onRollupWarning: onRollupWarning
  45176. };
  45177. var src$1 = {exports: {}};
  45178. var browser$1 = {exports: {}};
  45179. var debug$9 = {exports: {}};
  45180. /**
  45181. * Helpers.
  45182. */
  45183. var s = 1000;
  45184. var m = s * 60;
  45185. var h = m * 60;
  45186. var d = h * 24;
  45187. var y = d * 365.25;
  45188. /**
  45189. * Parse or format the given `val`.
  45190. *
  45191. * Options:
  45192. *
  45193. * - `long` verbose formatting [false]
  45194. *
  45195. * @param {String|Number} val
  45196. * @param {Object} [options]
  45197. * @throws {Error} throw an error if val is not a non-empty string or a number
  45198. * @return {String|Number}
  45199. * @api public
  45200. */
  45201. var ms = function(val, options) {
  45202. options = options || {};
  45203. var type = typeof val;
  45204. if (type === 'string' && val.length > 0) {
  45205. return parse$a(val);
  45206. } else if (type === 'number' && isNaN(val) === false) {
  45207. return options.long ? fmtLong(val) : fmtShort(val);
  45208. }
  45209. throw new Error(
  45210. 'val is not a non-empty string or a valid number. val=' +
  45211. JSON.stringify(val)
  45212. );
  45213. };
  45214. /**
  45215. * Parse the given `str` and return milliseconds.
  45216. *
  45217. * @param {String} str
  45218. * @return {Number}
  45219. * @api private
  45220. */
  45221. function parse$a(str) {
  45222. str = String(str);
  45223. if (str.length > 100) {
  45224. return;
  45225. }
  45226. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
  45227. str
  45228. );
  45229. if (!match) {
  45230. return;
  45231. }
  45232. var n = parseFloat(match[1]);
  45233. var type = (match[2] || 'ms').toLowerCase();
  45234. switch (type) {
  45235. case 'years':
  45236. case 'year':
  45237. case 'yrs':
  45238. case 'yr':
  45239. case 'y':
  45240. return n * y;
  45241. case 'days':
  45242. case 'day':
  45243. case 'd':
  45244. return n * d;
  45245. case 'hours':
  45246. case 'hour':
  45247. case 'hrs':
  45248. case 'hr':
  45249. case 'h':
  45250. return n * h;
  45251. case 'minutes':
  45252. case 'minute':
  45253. case 'mins':
  45254. case 'min':
  45255. case 'm':
  45256. return n * m;
  45257. case 'seconds':
  45258. case 'second':
  45259. case 'secs':
  45260. case 'sec':
  45261. case 's':
  45262. return n * s;
  45263. case 'milliseconds':
  45264. case 'millisecond':
  45265. case 'msecs':
  45266. case 'msec':
  45267. case 'ms':
  45268. return n;
  45269. default:
  45270. return undefined;
  45271. }
  45272. }
  45273. /**
  45274. * Short format for `ms`.
  45275. *
  45276. * @param {Number} ms
  45277. * @return {String}
  45278. * @api private
  45279. */
  45280. function fmtShort(ms) {
  45281. if (ms >= d) {
  45282. return Math.round(ms / d) + 'd';
  45283. }
  45284. if (ms >= h) {
  45285. return Math.round(ms / h) + 'h';
  45286. }
  45287. if (ms >= m) {
  45288. return Math.round(ms / m) + 'm';
  45289. }
  45290. if (ms >= s) {
  45291. return Math.round(ms / s) + 's';
  45292. }
  45293. return ms + 'ms';
  45294. }
  45295. /**
  45296. * Long format for `ms`.
  45297. *
  45298. * @param {Number} ms
  45299. * @return {String}
  45300. * @api private
  45301. */
  45302. function fmtLong(ms) {
  45303. return plural(ms, d, 'day') ||
  45304. plural(ms, h, 'hour') ||
  45305. plural(ms, m, 'minute') ||
  45306. plural(ms, s, 'second') ||
  45307. ms + ' ms';
  45308. }
  45309. /**
  45310. * Pluralization helper.
  45311. */
  45312. function plural(ms, n, name) {
  45313. if (ms < n) {
  45314. return;
  45315. }
  45316. if (ms < n * 1.5) {
  45317. return Math.floor(ms / n) + ' ' + name;
  45318. }
  45319. return Math.ceil(ms / n) + ' ' + name + 's';
  45320. }
  45321. (function (module, exports) {
  45322. /**
  45323. * This is the common logic for both the Node.js and web browser
  45324. * implementations of `debug()`.
  45325. *
  45326. * Expose `debug()` as the module.
  45327. */
  45328. exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
  45329. exports.coerce = coerce;
  45330. exports.disable = disable;
  45331. exports.enable = enable;
  45332. exports.enabled = enabled;
  45333. exports.humanize = ms;
  45334. /**
  45335. * The currently active debug mode names, and names to skip.
  45336. */
  45337. exports.names = [];
  45338. exports.skips = [];
  45339. /**
  45340. * Map of special "%n" handling functions, for the debug "format" argument.
  45341. *
  45342. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  45343. */
  45344. exports.formatters = {};
  45345. /**
  45346. * Previous log timestamp.
  45347. */
  45348. var prevTime;
  45349. /**
  45350. * Select a color.
  45351. * @param {String} namespace
  45352. * @return {Number}
  45353. * @api private
  45354. */
  45355. function selectColor(namespace) {
  45356. var hash = 0, i;
  45357. for (i in namespace) {
  45358. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  45359. hash |= 0; // Convert to 32bit integer
  45360. }
  45361. return exports.colors[Math.abs(hash) % exports.colors.length];
  45362. }
  45363. /**
  45364. * Create a debugger with the given `namespace`.
  45365. *
  45366. * @param {String} namespace
  45367. * @return {Function}
  45368. * @api public
  45369. */
  45370. function createDebug(namespace) {
  45371. function debug() {
  45372. // disabled?
  45373. if (!debug.enabled) return;
  45374. var self = debug;
  45375. // set `diff` timestamp
  45376. var curr = +new Date();
  45377. var ms = curr - (prevTime || curr);
  45378. self.diff = ms;
  45379. self.prev = prevTime;
  45380. self.curr = curr;
  45381. prevTime = curr;
  45382. // turn the `arguments` into a proper Array
  45383. var args = new Array(arguments.length);
  45384. for (var i = 0; i < args.length; i++) {
  45385. args[i] = arguments[i];
  45386. }
  45387. args[0] = exports.coerce(args[0]);
  45388. if ('string' !== typeof args[0]) {
  45389. // anything else let's inspect with %O
  45390. args.unshift('%O');
  45391. }
  45392. // apply any `formatters` transformations
  45393. var index = 0;
  45394. args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
  45395. // if we encounter an escaped % then don't increase the array index
  45396. if (match === '%%') return match;
  45397. index++;
  45398. var formatter = exports.formatters[format];
  45399. if ('function' === typeof formatter) {
  45400. var val = args[index];
  45401. match = formatter.call(self, val);
  45402. // now we need to remove `args[index]` since it's inlined in the `format`
  45403. args.splice(index, 1);
  45404. index--;
  45405. }
  45406. return match;
  45407. });
  45408. // apply env-specific formatting (colors, etc.)
  45409. exports.formatArgs.call(self, args);
  45410. var logFn = debug.log || exports.log || console.log.bind(console);
  45411. logFn.apply(self, args);
  45412. }
  45413. debug.namespace = namespace;
  45414. debug.enabled = exports.enabled(namespace);
  45415. debug.useColors = exports.useColors();
  45416. debug.color = selectColor(namespace);
  45417. // env-specific initialization logic for debug instances
  45418. if ('function' === typeof exports.init) {
  45419. exports.init(debug);
  45420. }
  45421. return debug;
  45422. }
  45423. /**
  45424. * Enables a debug mode by namespaces. This can include modes
  45425. * separated by a colon and wildcards.
  45426. *
  45427. * @param {String} namespaces
  45428. * @api public
  45429. */
  45430. function enable(namespaces) {
  45431. exports.save(namespaces);
  45432. exports.names = [];
  45433. exports.skips = [];
  45434. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  45435. var len = split.length;
  45436. for (var i = 0; i < len; i++) {
  45437. if (!split[i]) continue; // ignore empty strings
  45438. namespaces = split[i].replace(/\*/g, '.*?');
  45439. if (namespaces[0] === '-') {
  45440. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  45441. } else {
  45442. exports.names.push(new RegExp('^' + namespaces + '$'));
  45443. }
  45444. }
  45445. }
  45446. /**
  45447. * Disable debug output.
  45448. *
  45449. * @api public
  45450. */
  45451. function disable() {
  45452. exports.enable('');
  45453. }
  45454. /**
  45455. * Returns true if the given mode name is enabled, false otherwise.
  45456. *
  45457. * @param {String} name
  45458. * @return {Boolean}
  45459. * @api public
  45460. */
  45461. function enabled(name) {
  45462. var i, len;
  45463. for (i = 0, len = exports.skips.length; i < len; i++) {
  45464. if (exports.skips[i].test(name)) {
  45465. return false;
  45466. }
  45467. }
  45468. for (i = 0, len = exports.names.length; i < len; i++) {
  45469. if (exports.names[i].test(name)) {
  45470. return true;
  45471. }
  45472. }
  45473. return false;
  45474. }
  45475. /**
  45476. * Coerce `val`.
  45477. *
  45478. * @param {Mixed} val
  45479. * @return {Mixed}
  45480. * @api private
  45481. */
  45482. function coerce(val) {
  45483. if (val instanceof Error) return val.stack || val.message;
  45484. return val;
  45485. }
  45486. }(debug$9, debug$9.exports));
  45487. /**
  45488. * This is the web browser implementation of `debug()`.
  45489. *
  45490. * Expose `debug()` as the module.
  45491. */
  45492. (function (module, exports) {
  45493. exports = module.exports = debug$9.exports;
  45494. exports.log = log;
  45495. exports.formatArgs = formatArgs;
  45496. exports.save = save;
  45497. exports.load = load;
  45498. exports.useColors = useColors;
  45499. exports.storage = 'undefined' != typeof chrome
  45500. && 'undefined' != typeof chrome.storage
  45501. ? chrome.storage.local
  45502. : localstorage();
  45503. /**
  45504. * Colors.
  45505. */
  45506. exports.colors = [
  45507. 'lightseagreen',
  45508. 'forestgreen',
  45509. 'goldenrod',
  45510. 'dodgerblue',
  45511. 'darkorchid',
  45512. 'crimson'
  45513. ];
  45514. /**
  45515. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  45516. * and the Firebug extension (any Firefox version) are known
  45517. * to support "%c" CSS customizations.
  45518. *
  45519. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  45520. */
  45521. function useColors() {
  45522. // NB: In an Electron preload script, document will be defined but not fully
  45523. // initialized. Since we know we're in Chrome, we'll just detect this case
  45524. // explicitly
  45525. if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
  45526. return true;
  45527. }
  45528. // is webkit? http://stackoverflow.com/a/16459606/376773
  45529. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  45530. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  45531. // is firebug? http://stackoverflow.com/a/398120/376773
  45532. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  45533. // is firefox >= v31?
  45534. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  45535. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  45536. // double check webkit in userAgent just in case we are in a worker
  45537. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  45538. }
  45539. /**
  45540. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  45541. */
  45542. exports.formatters.j = function(v) {
  45543. try {
  45544. return JSON.stringify(v);
  45545. } catch (err) {
  45546. return '[UnexpectedJSONParseError]: ' + err.message;
  45547. }
  45548. };
  45549. /**
  45550. * Colorize log arguments if enabled.
  45551. *
  45552. * @api public
  45553. */
  45554. function formatArgs(args) {
  45555. var useColors = this.useColors;
  45556. args[0] = (useColors ? '%c' : '')
  45557. + this.namespace
  45558. + (useColors ? ' %c' : ' ')
  45559. + args[0]
  45560. + (useColors ? '%c ' : ' ')
  45561. + '+' + exports.humanize(this.diff);
  45562. if (!useColors) return;
  45563. var c = 'color: ' + this.color;
  45564. args.splice(1, 0, c, 'color: inherit');
  45565. // the final "%c" is somewhat tricky, because there could be other
  45566. // arguments passed either before or after the %c, so we need to
  45567. // figure out the correct index to insert the CSS into
  45568. var index = 0;
  45569. var lastC = 0;
  45570. args[0].replace(/%[a-zA-Z%]/g, function(match) {
  45571. if ('%%' === match) return;
  45572. index++;
  45573. if ('%c' === match) {
  45574. // we only are interested in the *last* %c
  45575. // (the user may have provided their own)
  45576. lastC = index;
  45577. }
  45578. });
  45579. args.splice(lastC, 0, c);
  45580. }
  45581. /**
  45582. * Invokes `console.log()` when available.
  45583. * No-op when `console.log` is not a "function".
  45584. *
  45585. * @api public
  45586. */
  45587. function log() {
  45588. // this hackery is required for IE8/9, where
  45589. // the `console.log` function doesn't have 'apply'
  45590. return 'object' === typeof console
  45591. && console.log
  45592. && Function.prototype.apply.call(console.log, console, arguments);
  45593. }
  45594. /**
  45595. * Save `namespaces`.
  45596. *
  45597. * @param {String} namespaces
  45598. * @api private
  45599. */
  45600. function save(namespaces) {
  45601. try {
  45602. if (null == namespaces) {
  45603. exports.storage.removeItem('debug');
  45604. } else {
  45605. exports.storage.debug = namespaces;
  45606. }
  45607. } catch(e) {}
  45608. }
  45609. /**
  45610. * Load `namespaces`.
  45611. *
  45612. * @return {String} returns the previously persisted debug modes
  45613. * @api private
  45614. */
  45615. function load() {
  45616. var r;
  45617. try {
  45618. r = exports.storage.debug;
  45619. } catch(e) {}
  45620. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  45621. if (!r && typeof process !== 'undefined' && 'env' in process) {
  45622. r = process.env.DEBUG;
  45623. }
  45624. return r;
  45625. }
  45626. /**
  45627. * Enable namespaces listed in `localStorage.debug` initially.
  45628. */
  45629. exports.enable(load());
  45630. /**
  45631. * Localstorage attempts to return the localstorage.
  45632. *
  45633. * This is necessary because safari throws
  45634. * when a user disables cookies/localstorage
  45635. * and you attempt to access it.
  45636. *
  45637. * @return {LocalStorage}
  45638. * @api private
  45639. */
  45640. function localstorage() {
  45641. try {
  45642. return window.localStorage;
  45643. } catch (e) {}
  45644. }
  45645. }(browser$1, browser$1.exports));
  45646. var node$1 = {exports: {}};
  45647. /**
  45648. * Module dependencies.
  45649. */
  45650. (function (module, exports) {
  45651. var tty = require$$0__default;
  45652. var util = require$$0__default$3;
  45653. /**
  45654. * This is the Node.js implementation of `debug()`.
  45655. *
  45656. * Expose `debug()` as the module.
  45657. */
  45658. exports = module.exports = debug$9.exports;
  45659. exports.init = init;
  45660. exports.log = log;
  45661. exports.formatArgs = formatArgs;
  45662. exports.save = save;
  45663. exports.load = load;
  45664. exports.useColors = useColors;
  45665. /**
  45666. * Colors.
  45667. */
  45668. exports.colors = [6, 2, 3, 4, 5, 1];
  45669. /**
  45670. * Build up the default `inspectOpts` object from the environment variables.
  45671. *
  45672. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  45673. */
  45674. exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  45675. return /^debug_/i.test(key);
  45676. }).reduce(function (obj, key) {
  45677. // camel-case
  45678. var prop = key
  45679. .substring(6)
  45680. .toLowerCase()
  45681. .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
  45682. // coerce string value into JS value
  45683. var val = process.env[key];
  45684. if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  45685. else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  45686. else if (val === 'null') val = null;
  45687. else val = Number(val);
  45688. obj[prop] = val;
  45689. return obj;
  45690. }, {});
  45691. /**
  45692. * The file descriptor to write the `debug()` calls to.
  45693. * Set the `DEBUG_FD` env variable to override with another value. i.e.:
  45694. *
  45695. * $ DEBUG_FD=3 node script.js 3>debug.log
  45696. */
  45697. var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
  45698. if (1 !== fd && 2 !== fd) {
  45699. util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
  45700. }
  45701. var stream = 1 === fd ? process.stdout :
  45702. 2 === fd ? process.stderr :
  45703. createWritableStdioStream(fd);
  45704. /**
  45705. * Is stdout a TTY? Colored output is enabled when `true`.
  45706. */
  45707. function useColors() {
  45708. return 'colors' in exports.inspectOpts
  45709. ? Boolean(exports.inspectOpts.colors)
  45710. : tty.isatty(fd);
  45711. }
  45712. /**
  45713. * Map %o to `util.inspect()`, all on a single line.
  45714. */
  45715. exports.formatters.o = function(v) {
  45716. this.inspectOpts.colors = this.useColors;
  45717. return util.inspect(v, this.inspectOpts)
  45718. .split('\n').map(function(str) {
  45719. return str.trim()
  45720. }).join(' ');
  45721. };
  45722. /**
  45723. * Map %o to `util.inspect()`, allowing multiple lines if needed.
  45724. */
  45725. exports.formatters.O = function(v) {
  45726. this.inspectOpts.colors = this.useColors;
  45727. return util.inspect(v, this.inspectOpts);
  45728. };
  45729. /**
  45730. * Adds ANSI color escape codes if enabled.
  45731. *
  45732. * @api public
  45733. */
  45734. function formatArgs(args) {
  45735. var name = this.namespace;
  45736. var useColors = this.useColors;
  45737. if (useColors) {
  45738. var c = this.color;
  45739. var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
  45740. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  45741. args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  45742. } else {
  45743. args[0] = new Date().toUTCString()
  45744. + ' ' + name + ' ' + args[0];
  45745. }
  45746. }
  45747. /**
  45748. * Invokes `util.format()` with the specified arguments and writes to `stream`.
  45749. */
  45750. function log() {
  45751. return stream.write(util.format.apply(util, arguments) + '\n');
  45752. }
  45753. /**
  45754. * Save `namespaces`.
  45755. *
  45756. * @param {String} namespaces
  45757. * @api private
  45758. */
  45759. function save(namespaces) {
  45760. if (null == namespaces) {
  45761. // If you set a process.env field to null or undefined, it gets cast to the
  45762. // string 'null' or 'undefined'. Just delete instead.
  45763. delete process.env.DEBUG;
  45764. } else {
  45765. process.env.DEBUG = namespaces;
  45766. }
  45767. }
  45768. /**
  45769. * Load `namespaces`.
  45770. *
  45771. * @return {String} returns the previously persisted debug modes
  45772. * @api private
  45773. */
  45774. function load() {
  45775. return process.env.DEBUG;
  45776. }
  45777. /**
  45778. * Copied from `node/src/node.js`.
  45779. *
  45780. * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
  45781. * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
  45782. */
  45783. function createWritableStdioStream (fd) {
  45784. var stream;
  45785. var tty_wrap = process.binding('tty_wrap');
  45786. // Note stream._type is used for test-module-load-list.js
  45787. switch (tty_wrap.guessHandleType(fd)) {
  45788. case 'TTY':
  45789. stream = new tty.WriteStream(fd);
  45790. stream._type = 'tty';
  45791. // Hack to have stream not keep the event loop alive.
  45792. // See https://github.com/joyent/node/issues/1726
  45793. if (stream._handle && stream._handle.unref) {
  45794. stream._handle.unref();
  45795. }
  45796. break;
  45797. case 'FILE':
  45798. var fs = fs__default;
  45799. stream = new fs.SyncWriteStream(fd, { autoClose: false });
  45800. stream._type = 'fs';
  45801. break;
  45802. case 'PIPE':
  45803. case 'TCP':
  45804. var net = require$$4__default$1;
  45805. stream = new net.Socket({
  45806. fd: fd,
  45807. readable: false,
  45808. writable: true
  45809. });
  45810. // FIXME Should probably have an option in net.Socket to create a
  45811. // stream from an existing fd which is writable only. But for now
  45812. // we'll just add this hack and set the `readable` member to false.
  45813. // Test: ./node test/fixtures/echo.js < /etc/passwd
  45814. stream.readable = false;
  45815. stream.read = null;
  45816. stream._type = 'pipe';
  45817. // FIXME Hack to have stream not keep the event loop alive.
  45818. // See https://github.com/joyent/node/issues/1726
  45819. if (stream._handle && stream._handle.unref) {
  45820. stream._handle.unref();
  45821. }
  45822. break;
  45823. default:
  45824. // Probably an error on in uv_guess_handle()
  45825. throw new Error('Implement me. Unknown stream file type!');
  45826. }
  45827. // For supporting legacy API we put the FD here.
  45828. stream.fd = fd;
  45829. stream._isStdio = true;
  45830. return stream;
  45831. }
  45832. /**
  45833. * Init logic for `debug` instances.
  45834. *
  45835. * Create a new `inspectOpts` object in case `useColors` is set
  45836. * differently for a particular `debug` instance.
  45837. */
  45838. function init (debug) {
  45839. debug.inspectOpts = {};
  45840. var keys = Object.keys(exports.inspectOpts);
  45841. for (var i = 0; i < keys.length; i++) {
  45842. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  45843. }
  45844. }
  45845. /**
  45846. * Enable namespaces listed in `process.env.DEBUG` initially.
  45847. */
  45848. exports.enable(load());
  45849. }(node$1, node$1.exports));
  45850. /**
  45851. * Detect Electron renderer process, which is node, but we should
  45852. * treat as a browser.
  45853. */
  45854. if (typeof process !== 'undefined' && process.type === 'renderer') {
  45855. src$1.exports = browser$1.exports;
  45856. } else {
  45857. src$1.exports = node$1.exports;
  45858. }
  45859. var src = {exports: {}};
  45860. var browser = {exports: {}};
  45861. var debug$8 = {exports: {}};
  45862. (function (module, exports) {
  45863. /**
  45864. * This is the common logic for both the Node.js and web browser
  45865. * implementations of `debug()`.
  45866. *
  45867. * Expose `debug()` as the module.
  45868. */
  45869. exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
  45870. exports.coerce = coerce;
  45871. exports.disable = disable;
  45872. exports.enable = enable;
  45873. exports.enabled = enabled;
  45874. exports.humanize = ms;
  45875. /**
  45876. * The currently active debug mode names, and names to skip.
  45877. */
  45878. exports.names = [];
  45879. exports.skips = [];
  45880. /**
  45881. * Map of special "%n" handling functions, for the debug "format" argument.
  45882. *
  45883. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  45884. */
  45885. exports.formatters = {};
  45886. /**
  45887. * Previous log timestamp.
  45888. */
  45889. var prevTime;
  45890. /**
  45891. * Select a color.
  45892. * @param {String} namespace
  45893. * @return {Number}
  45894. * @api private
  45895. */
  45896. function selectColor(namespace) {
  45897. var hash = 0, i;
  45898. for (i in namespace) {
  45899. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  45900. hash |= 0; // Convert to 32bit integer
  45901. }
  45902. return exports.colors[Math.abs(hash) % exports.colors.length];
  45903. }
  45904. /**
  45905. * Create a debugger with the given `namespace`.
  45906. *
  45907. * @param {String} namespace
  45908. * @return {Function}
  45909. * @api public
  45910. */
  45911. function createDebug(namespace) {
  45912. function debug() {
  45913. // disabled?
  45914. if (!debug.enabled) return;
  45915. var self = debug;
  45916. // set `diff` timestamp
  45917. var curr = +new Date();
  45918. var ms = curr - (prevTime || curr);
  45919. self.diff = ms;
  45920. self.prev = prevTime;
  45921. self.curr = curr;
  45922. prevTime = curr;
  45923. // turn the `arguments` into a proper Array
  45924. var args = new Array(arguments.length);
  45925. for (var i = 0; i < args.length; i++) {
  45926. args[i] = arguments[i];
  45927. }
  45928. args[0] = exports.coerce(args[0]);
  45929. if ('string' !== typeof args[0]) {
  45930. // anything else let's inspect with %O
  45931. args.unshift('%O');
  45932. }
  45933. // apply any `formatters` transformations
  45934. var index = 0;
  45935. args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
  45936. // if we encounter an escaped % then don't increase the array index
  45937. if (match === '%%') return match;
  45938. index++;
  45939. var formatter = exports.formatters[format];
  45940. if ('function' === typeof formatter) {
  45941. var val = args[index];
  45942. match = formatter.call(self, val);
  45943. // now we need to remove `args[index]` since it's inlined in the `format`
  45944. args.splice(index, 1);
  45945. index--;
  45946. }
  45947. return match;
  45948. });
  45949. // apply env-specific formatting (colors, etc.)
  45950. exports.formatArgs.call(self, args);
  45951. var logFn = debug.log || exports.log || console.log.bind(console);
  45952. logFn.apply(self, args);
  45953. }
  45954. debug.namespace = namespace;
  45955. debug.enabled = exports.enabled(namespace);
  45956. debug.useColors = exports.useColors();
  45957. debug.color = selectColor(namespace);
  45958. // env-specific initialization logic for debug instances
  45959. if ('function' === typeof exports.init) {
  45960. exports.init(debug);
  45961. }
  45962. return debug;
  45963. }
  45964. /**
  45965. * Enables a debug mode by namespaces. This can include modes
  45966. * separated by a colon and wildcards.
  45967. *
  45968. * @param {String} namespaces
  45969. * @api public
  45970. */
  45971. function enable(namespaces) {
  45972. exports.save(namespaces);
  45973. exports.names = [];
  45974. exports.skips = [];
  45975. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  45976. var len = split.length;
  45977. for (var i = 0; i < len; i++) {
  45978. if (!split[i]) continue; // ignore empty strings
  45979. namespaces = split[i].replace(/\*/g, '.*?');
  45980. if (namespaces[0] === '-') {
  45981. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  45982. } else {
  45983. exports.names.push(new RegExp('^' + namespaces + '$'));
  45984. }
  45985. }
  45986. }
  45987. /**
  45988. * Disable debug output.
  45989. *
  45990. * @api public
  45991. */
  45992. function disable() {
  45993. exports.enable('');
  45994. }
  45995. /**
  45996. * Returns true if the given mode name is enabled, false otherwise.
  45997. *
  45998. * @param {String} name
  45999. * @return {Boolean}
  46000. * @api public
  46001. */
  46002. function enabled(name) {
  46003. var i, len;
  46004. for (i = 0, len = exports.skips.length; i < len; i++) {
  46005. if (exports.skips[i].test(name)) {
  46006. return false;
  46007. }
  46008. }
  46009. for (i = 0, len = exports.names.length; i < len; i++) {
  46010. if (exports.names[i].test(name)) {
  46011. return true;
  46012. }
  46013. }
  46014. return false;
  46015. }
  46016. /**
  46017. * Coerce `val`.
  46018. *
  46019. * @param {Mixed} val
  46020. * @return {Mixed}
  46021. * @api private
  46022. */
  46023. function coerce(val) {
  46024. if (val instanceof Error) return val.stack || val.message;
  46025. return val;
  46026. }
  46027. }(debug$8, debug$8.exports));
  46028. /**
  46029. * This is the web browser implementation of `debug()`.
  46030. *
  46031. * Expose `debug()` as the module.
  46032. */
  46033. (function (module, exports) {
  46034. exports = module.exports = debug$8.exports;
  46035. exports.log = log;
  46036. exports.formatArgs = formatArgs;
  46037. exports.save = save;
  46038. exports.load = load;
  46039. exports.useColors = useColors;
  46040. exports.storage = 'undefined' != typeof chrome
  46041. && 'undefined' != typeof chrome.storage
  46042. ? chrome.storage.local
  46043. : localstorage();
  46044. /**
  46045. * Colors.
  46046. */
  46047. exports.colors = [
  46048. 'lightseagreen',
  46049. 'forestgreen',
  46050. 'goldenrod',
  46051. 'dodgerblue',
  46052. 'darkorchid',
  46053. 'crimson'
  46054. ];
  46055. /**
  46056. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  46057. * and the Firebug extension (any Firefox version) are known
  46058. * to support "%c" CSS customizations.
  46059. *
  46060. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  46061. */
  46062. function useColors() {
  46063. // NB: In an Electron preload script, document will be defined but not fully
  46064. // initialized. Since we know we're in Chrome, we'll just detect this case
  46065. // explicitly
  46066. if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
  46067. return true;
  46068. }
  46069. // is webkit? http://stackoverflow.com/a/16459606/376773
  46070. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  46071. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  46072. // is firebug? http://stackoverflow.com/a/398120/376773
  46073. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  46074. // is firefox >= v31?
  46075. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  46076. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  46077. // double check webkit in userAgent just in case we are in a worker
  46078. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  46079. }
  46080. /**
  46081. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  46082. */
  46083. exports.formatters.j = function(v) {
  46084. try {
  46085. return JSON.stringify(v);
  46086. } catch (err) {
  46087. return '[UnexpectedJSONParseError]: ' + err.message;
  46088. }
  46089. };
  46090. /**
  46091. * Colorize log arguments if enabled.
  46092. *
  46093. * @api public
  46094. */
  46095. function formatArgs(args) {
  46096. var useColors = this.useColors;
  46097. args[0] = (useColors ? '%c' : '')
  46098. + this.namespace
  46099. + (useColors ? ' %c' : ' ')
  46100. + args[0]
  46101. + (useColors ? '%c ' : ' ')
  46102. + '+' + exports.humanize(this.diff);
  46103. if (!useColors) return;
  46104. var c = 'color: ' + this.color;
  46105. args.splice(1, 0, c, 'color: inherit');
  46106. // the final "%c" is somewhat tricky, because there could be other
  46107. // arguments passed either before or after the %c, so we need to
  46108. // figure out the correct index to insert the CSS into
  46109. var index = 0;
  46110. var lastC = 0;
  46111. args[0].replace(/%[a-zA-Z%]/g, function(match) {
  46112. if ('%%' === match) return;
  46113. index++;
  46114. if ('%c' === match) {
  46115. // we only are interested in the *last* %c
  46116. // (the user may have provided their own)
  46117. lastC = index;
  46118. }
  46119. });
  46120. args.splice(lastC, 0, c);
  46121. }
  46122. /**
  46123. * Invokes `console.log()` when available.
  46124. * No-op when `console.log` is not a "function".
  46125. *
  46126. * @api public
  46127. */
  46128. function log() {
  46129. // this hackery is required for IE8/9, where
  46130. // the `console.log` function doesn't have 'apply'
  46131. return 'object' === typeof console
  46132. && console.log
  46133. && Function.prototype.apply.call(console.log, console, arguments);
  46134. }
  46135. /**
  46136. * Save `namespaces`.
  46137. *
  46138. * @param {String} namespaces
  46139. * @api private
  46140. */
  46141. function save(namespaces) {
  46142. try {
  46143. if (null == namespaces) {
  46144. exports.storage.removeItem('debug');
  46145. } else {
  46146. exports.storage.debug = namespaces;
  46147. }
  46148. } catch(e) {}
  46149. }
  46150. /**
  46151. * Load `namespaces`.
  46152. *
  46153. * @return {String} returns the previously persisted debug modes
  46154. * @api private
  46155. */
  46156. function load() {
  46157. var r;
  46158. try {
  46159. r = exports.storage.debug;
  46160. } catch(e) {}
  46161. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  46162. if (!r && typeof process !== 'undefined' && 'env' in process) {
  46163. r = process.env.DEBUG;
  46164. }
  46165. return r;
  46166. }
  46167. /**
  46168. * Enable namespaces listed in `localStorage.debug` initially.
  46169. */
  46170. exports.enable(load());
  46171. /**
  46172. * Localstorage attempts to return the localstorage.
  46173. *
  46174. * This is necessary because safari throws
  46175. * when a user disables cookies/localstorage
  46176. * and you attempt to access it.
  46177. *
  46178. * @return {LocalStorage}
  46179. * @api private
  46180. */
  46181. function localstorage() {
  46182. try {
  46183. return window.localStorage;
  46184. } catch (e) {}
  46185. }
  46186. }(browser, browser.exports));
  46187. var node = {exports: {}};
  46188. /**
  46189. * Module dependencies.
  46190. */
  46191. (function (module, exports) {
  46192. var tty = require$$0__default;
  46193. var util = require$$0__default$3;
  46194. /**
  46195. * This is the Node.js implementation of `debug()`.
  46196. *
  46197. * Expose `debug()` as the module.
  46198. */
  46199. exports = module.exports = debug$8.exports;
  46200. exports.init = init;
  46201. exports.log = log;
  46202. exports.formatArgs = formatArgs;
  46203. exports.save = save;
  46204. exports.load = load;
  46205. exports.useColors = useColors;
  46206. /**
  46207. * Colors.
  46208. */
  46209. exports.colors = [6, 2, 3, 4, 5, 1];
  46210. /**
  46211. * Build up the default `inspectOpts` object from the environment variables.
  46212. *
  46213. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  46214. */
  46215. exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  46216. return /^debug_/i.test(key);
  46217. }).reduce(function (obj, key) {
  46218. // camel-case
  46219. var prop = key
  46220. .substring(6)
  46221. .toLowerCase()
  46222. .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
  46223. // coerce string value into JS value
  46224. var val = process.env[key];
  46225. if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  46226. else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  46227. else if (val === 'null') val = null;
  46228. else val = Number(val);
  46229. obj[prop] = val;
  46230. return obj;
  46231. }, {});
  46232. /**
  46233. * The file descriptor to write the `debug()` calls to.
  46234. * Set the `DEBUG_FD` env variable to override with another value. i.e.:
  46235. *
  46236. * $ DEBUG_FD=3 node script.js 3>debug.log
  46237. */
  46238. var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
  46239. if (1 !== fd && 2 !== fd) {
  46240. util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
  46241. }
  46242. var stream = 1 === fd ? process.stdout :
  46243. 2 === fd ? process.stderr :
  46244. createWritableStdioStream(fd);
  46245. /**
  46246. * Is stdout a TTY? Colored output is enabled when `true`.
  46247. */
  46248. function useColors() {
  46249. return 'colors' in exports.inspectOpts
  46250. ? Boolean(exports.inspectOpts.colors)
  46251. : tty.isatty(fd);
  46252. }
  46253. /**
  46254. * Map %o to `util.inspect()`, all on a single line.
  46255. */
  46256. exports.formatters.o = function(v) {
  46257. this.inspectOpts.colors = this.useColors;
  46258. return util.inspect(v, this.inspectOpts)
  46259. .split('\n').map(function(str) {
  46260. return str.trim()
  46261. }).join(' ');
  46262. };
  46263. /**
  46264. * Map %o to `util.inspect()`, allowing multiple lines if needed.
  46265. */
  46266. exports.formatters.O = function(v) {
  46267. this.inspectOpts.colors = this.useColors;
  46268. return util.inspect(v, this.inspectOpts);
  46269. };
  46270. /**
  46271. * Adds ANSI color escape codes if enabled.
  46272. *
  46273. * @api public
  46274. */
  46275. function formatArgs(args) {
  46276. var name = this.namespace;
  46277. var useColors = this.useColors;
  46278. if (useColors) {
  46279. var c = this.color;
  46280. var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
  46281. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  46282. args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  46283. } else {
  46284. args[0] = new Date().toUTCString()
  46285. + ' ' + name + ' ' + args[0];
  46286. }
  46287. }
  46288. /**
  46289. * Invokes `util.format()` with the specified arguments and writes to `stream`.
  46290. */
  46291. function log() {
  46292. return stream.write(util.format.apply(util, arguments) + '\n');
  46293. }
  46294. /**
  46295. * Save `namespaces`.
  46296. *
  46297. * @param {String} namespaces
  46298. * @api private
  46299. */
  46300. function save(namespaces) {
  46301. if (null == namespaces) {
  46302. // If you set a process.env field to null or undefined, it gets cast to the
  46303. // string 'null' or 'undefined'. Just delete instead.
  46304. delete process.env.DEBUG;
  46305. } else {
  46306. process.env.DEBUG = namespaces;
  46307. }
  46308. }
  46309. /**
  46310. * Load `namespaces`.
  46311. *
  46312. * @return {String} returns the previously persisted debug modes
  46313. * @api private
  46314. */
  46315. function load() {
  46316. return process.env.DEBUG;
  46317. }
  46318. /**
  46319. * Copied from `node/src/node.js`.
  46320. *
  46321. * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
  46322. * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
  46323. */
  46324. function createWritableStdioStream (fd) {
  46325. var stream;
  46326. var tty_wrap = process.binding('tty_wrap');
  46327. // Note stream._type is used for test-module-load-list.js
  46328. switch (tty_wrap.guessHandleType(fd)) {
  46329. case 'TTY':
  46330. stream = new tty.WriteStream(fd);
  46331. stream._type = 'tty';
  46332. // Hack to have stream not keep the event loop alive.
  46333. // See https://github.com/joyent/node/issues/1726
  46334. if (stream._handle && stream._handle.unref) {
  46335. stream._handle.unref();
  46336. }
  46337. break;
  46338. case 'FILE':
  46339. var fs = fs__default;
  46340. stream = new fs.SyncWriteStream(fd, { autoClose: false });
  46341. stream._type = 'fs';
  46342. break;
  46343. case 'PIPE':
  46344. case 'TCP':
  46345. var net = require$$4__default$1;
  46346. stream = new net.Socket({
  46347. fd: fd,
  46348. readable: false,
  46349. writable: true
  46350. });
  46351. // FIXME Should probably have an option in net.Socket to create a
  46352. // stream from an existing fd which is writable only. But for now
  46353. // we'll just add this hack and set the `readable` member to false.
  46354. // Test: ./node test/fixtures/echo.js < /etc/passwd
  46355. stream.readable = false;
  46356. stream.read = null;
  46357. stream._type = 'pipe';
  46358. // FIXME Hack to have stream not keep the event loop alive.
  46359. // See https://github.com/joyent/node/issues/1726
  46360. if (stream._handle && stream._handle.unref) {
  46361. stream._handle.unref();
  46362. }
  46363. break;
  46364. default:
  46365. // Probably an error on in uv_guess_handle()
  46366. throw new Error('Implement me. Unknown stream file type!');
  46367. }
  46368. // For supporting legacy API we put the FD here.
  46369. stream.fd = fd;
  46370. stream._isStdio = true;
  46371. return stream;
  46372. }
  46373. /**
  46374. * Init logic for `debug` instances.
  46375. *
  46376. * Create a new `inspectOpts` object in case `useColors` is set
  46377. * differently for a particular `debug` instance.
  46378. */
  46379. function init (debug) {
  46380. debug.inspectOpts = {};
  46381. var keys = Object.keys(exports.inspectOpts);
  46382. for (var i = 0; i < keys.length; i++) {
  46383. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  46384. }
  46385. }
  46386. /**
  46387. * Enable namespaces listed in `process.env.DEBUG` initially.
  46388. */
  46389. exports.enable(load());
  46390. }(node, node.exports));
  46391. /**
  46392. * Detect Electron renderer process, which is node, but we should
  46393. * treat as a browser.
  46394. */
  46395. if (typeof process !== 'undefined' && process.type === 'renderer') {
  46396. src.exports = browser.exports;
  46397. } else {
  46398. src.exports = node.exports;
  46399. }
  46400. /*!
  46401. * encodeurl
  46402. * Copyright(c) 2016 Douglas Christopher Wilson
  46403. * MIT Licensed
  46404. */
  46405. /**
  46406. * Module exports.
  46407. * @public
  46408. */
  46409. var encodeurl = encodeUrl$1;
  46410. /**
  46411. * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
  46412. * and including invalid escape sequences.
  46413. * @private
  46414. */
  46415. var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
  46416. /**
  46417. * RegExp to match unmatched surrogate pair.
  46418. * @private
  46419. */
  46420. var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
  46421. /**
  46422. * String to replace unmatched surrogate pair with.
  46423. * @private
  46424. */
  46425. var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2';
  46426. /**
  46427. * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
  46428. *
  46429. * This function will take an already-encoded URL and encode all the non-URL
  46430. * code points. This function will not encode the "%" character unless it is
  46431. * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
  46432. * be encoded as `%25foo`).
  46433. *
  46434. * This encode is meant to be "safe" and does not throw errors. It will try as
  46435. * hard as it can to properly encode the given URL, including replacing any raw,
  46436. * unpaired surrogate pairs with the Unicode replacement character prior to
  46437. * encoding.
  46438. *
  46439. * @param {string} url
  46440. * @return {string}
  46441. * @public
  46442. */
  46443. function encodeUrl$1 (url) {
  46444. return String(url)
  46445. .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)
  46446. .replace(ENCODE_CHARS_REGEXP, encodeURI)
  46447. }
  46448. /*!
  46449. * escape-html
  46450. * Copyright(c) 2012-2013 TJ Holowaychuk
  46451. * Copyright(c) 2015 Andreas Lubbe
  46452. * Copyright(c) 2015 Tiancheng "Timothy" Gu
  46453. * MIT Licensed
  46454. */
  46455. /**
  46456. * Module variables.
  46457. * @private
  46458. */
  46459. var matchHtmlRegExp = /["'&<>]/;
  46460. /**
  46461. * Module exports.
  46462. * @public
  46463. */
  46464. var escapeHtml_1 = escapeHtml$1;
  46465. /**
  46466. * Escape special characters in the given string of html.
  46467. *
  46468. * @param {string} string The string to escape for inserting into HTML
  46469. * @return {string}
  46470. * @public
  46471. */
  46472. function escapeHtml$1(string) {
  46473. var str = '' + string;
  46474. var match = matchHtmlRegExp.exec(str);
  46475. if (!match) {
  46476. return str;
  46477. }
  46478. var escape;
  46479. var html = '';
  46480. var index = 0;
  46481. var lastIndex = 0;
  46482. for (index = match.index; index < str.length; index++) {
  46483. switch (str.charCodeAt(index)) {
  46484. case 34: // "
  46485. escape = '&quot;';
  46486. break;
  46487. case 38: // &
  46488. escape = '&amp;';
  46489. break;
  46490. case 39: // '
  46491. escape = '&#39;';
  46492. break;
  46493. case 60: // <
  46494. escape = '&lt;';
  46495. break;
  46496. case 62: // >
  46497. escape = '&gt;';
  46498. break;
  46499. default:
  46500. continue;
  46501. }
  46502. if (lastIndex !== index) {
  46503. html += str.substring(lastIndex, index);
  46504. }
  46505. lastIndex = index + 1;
  46506. html += escape;
  46507. }
  46508. return lastIndex !== index
  46509. ? html + str.substring(lastIndex, index)
  46510. : html;
  46511. }
  46512. var onFinished$2 = {exports: {}};
  46513. /*!
  46514. * ee-first
  46515. * Copyright(c) 2014 Jonathan Ong
  46516. * MIT Licensed
  46517. */
  46518. /**
  46519. * Module exports.
  46520. * @public
  46521. */
  46522. var eeFirst = first$1;
  46523. /**
  46524. * Get the first event in a set of event emitters and event pairs.
  46525. *
  46526. * @param {array} stuff
  46527. * @param {function} done
  46528. * @public
  46529. */
  46530. function first$1(stuff, done) {
  46531. if (!Array.isArray(stuff))
  46532. throw new TypeError('arg must be an array of [ee, events...] arrays')
  46533. var cleanups = [];
  46534. for (var i = 0; i < stuff.length; i++) {
  46535. var arr = stuff[i];
  46536. if (!Array.isArray(arr) || arr.length < 2)
  46537. throw new TypeError('each array member must be [ee, events...]')
  46538. var ee = arr[0];
  46539. for (var j = 1; j < arr.length; j++) {
  46540. var event = arr[j];
  46541. var fn = listener(event, callback);
  46542. // listen to the event
  46543. ee.on(event, fn);
  46544. // push this listener to the list of cleanups
  46545. cleanups.push({
  46546. ee: ee,
  46547. event: event,
  46548. fn: fn,
  46549. });
  46550. }
  46551. }
  46552. function callback() {
  46553. cleanup();
  46554. done.apply(null, arguments);
  46555. }
  46556. function cleanup() {
  46557. var x;
  46558. for (var i = 0; i < cleanups.length; i++) {
  46559. x = cleanups[i];
  46560. x.ee.removeListener(x.event, x.fn);
  46561. }
  46562. }
  46563. function thunk(fn) {
  46564. done = fn;
  46565. }
  46566. thunk.cancel = cleanup;
  46567. return thunk
  46568. }
  46569. /**
  46570. * Create the event listener.
  46571. * @private
  46572. */
  46573. function listener(event, done) {
  46574. return function onevent(arg1) {
  46575. var args = new Array(arguments.length);
  46576. var ee = this;
  46577. var err = event === 'error'
  46578. ? arg1
  46579. : null;
  46580. // copy args to prevent arguments escaping scope
  46581. for (var i = 0; i < args.length; i++) {
  46582. args[i] = arguments[i];
  46583. }
  46584. done(err, ee, event, args);
  46585. }
  46586. }
  46587. /*!
  46588. * on-finished
  46589. * Copyright(c) 2013 Jonathan Ong
  46590. * Copyright(c) 2014 Douglas Christopher Wilson
  46591. * MIT Licensed
  46592. */
  46593. /**
  46594. * Module exports.
  46595. * @public
  46596. */
  46597. onFinished$2.exports = onFinished$1;
  46598. onFinished$2.exports.isFinished = isFinished$1;
  46599. /**
  46600. * Module dependencies.
  46601. * @private
  46602. */
  46603. var first = eeFirst;
  46604. /**
  46605. * Variables.
  46606. * @private
  46607. */
  46608. /* istanbul ignore next */
  46609. var defer$2 = typeof setImmediate === 'function'
  46610. ? setImmediate
  46611. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  46612. /**
  46613. * Invoke callback when the response has finished, useful for
  46614. * cleaning up resources afterwards.
  46615. *
  46616. * @param {object} msg
  46617. * @param {function} listener
  46618. * @return {object}
  46619. * @public
  46620. */
  46621. function onFinished$1(msg, listener) {
  46622. if (isFinished$1(msg) !== false) {
  46623. defer$2(listener, null, msg);
  46624. return msg
  46625. }
  46626. // attach the listener to the message
  46627. attachListener(msg, listener);
  46628. return msg
  46629. }
  46630. /**
  46631. * Determine if message is already finished.
  46632. *
  46633. * @param {object} msg
  46634. * @return {boolean}
  46635. * @public
  46636. */
  46637. function isFinished$1(msg) {
  46638. var socket = msg.socket;
  46639. if (typeof msg.finished === 'boolean') {
  46640. // OutgoingMessage
  46641. return Boolean(msg.finished || (socket && !socket.writable))
  46642. }
  46643. if (typeof msg.complete === 'boolean') {
  46644. // IncomingMessage
  46645. return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
  46646. }
  46647. // don't know
  46648. return undefined
  46649. }
  46650. /**
  46651. * Attach a finished listener to the message.
  46652. *
  46653. * @param {object} msg
  46654. * @param {function} callback
  46655. * @private
  46656. */
  46657. function attachFinishedListener(msg, callback) {
  46658. var eeMsg;
  46659. var eeSocket;
  46660. var finished = false;
  46661. function onFinish(error) {
  46662. eeMsg.cancel();
  46663. eeSocket.cancel();
  46664. finished = true;
  46665. callback(error);
  46666. }
  46667. // finished on first message event
  46668. eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish);
  46669. function onSocket(socket) {
  46670. // remove listener
  46671. msg.removeListener('socket', onSocket);
  46672. if (finished) return
  46673. if (eeMsg !== eeSocket) return
  46674. // finished on first socket event
  46675. eeSocket = first([[socket, 'error', 'close']], onFinish);
  46676. }
  46677. if (msg.socket) {
  46678. // socket already assigned
  46679. onSocket(msg.socket);
  46680. return
  46681. }
  46682. // wait for socket to be assigned
  46683. msg.on('socket', onSocket);
  46684. if (msg.socket === undefined) {
  46685. // node.js 0.8 patch
  46686. patchAssignSocket(msg, onSocket);
  46687. }
  46688. }
  46689. /**
  46690. * Attach the listener to the message.
  46691. *
  46692. * @param {object} msg
  46693. * @return {function}
  46694. * @private
  46695. */
  46696. function attachListener(msg, listener) {
  46697. var attached = msg.__onFinished;
  46698. // create a private single listener with queue
  46699. if (!attached || !attached.queue) {
  46700. attached = msg.__onFinished = createListener(msg);
  46701. attachFinishedListener(msg, attached);
  46702. }
  46703. attached.queue.push(listener);
  46704. }
  46705. /**
  46706. * Create listener on message.
  46707. *
  46708. * @param {object} msg
  46709. * @return {function}
  46710. * @private
  46711. */
  46712. function createListener(msg) {
  46713. function listener(err) {
  46714. if (msg.__onFinished === listener) msg.__onFinished = null;
  46715. if (!listener.queue) return
  46716. var queue = listener.queue;
  46717. listener.queue = null;
  46718. for (var i = 0; i < queue.length; i++) {
  46719. queue[i](err, msg);
  46720. }
  46721. }
  46722. listener.queue = [];
  46723. return listener
  46724. }
  46725. /**
  46726. * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
  46727. *
  46728. * @param {ServerResponse} res
  46729. * @param {function} callback
  46730. * @private
  46731. */
  46732. function patchAssignSocket(res, callback) {
  46733. var assignSocket = res.assignSocket;
  46734. if (typeof assignSocket !== 'function') return
  46735. // res.on('socket', callback) is broken in 0.8
  46736. res.assignSocket = function _assignSocket(socket) {
  46737. assignSocket.call(this, socket);
  46738. callback(socket);
  46739. };
  46740. }
  46741. var parseurl$1 = {exports: {}};
  46742. /*!
  46743. * parseurl
  46744. * Copyright(c) 2014 Jonathan Ong
  46745. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  46746. * MIT Licensed
  46747. */
  46748. /**
  46749. * Module dependencies.
  46750. * @private
  46751. */
  46752. var url$3 = require$$0__default$7;
  46753. var parse$9 = url$3.parse;
  46754. var Url = url$3.Url;
  46755. /**
  46756. * Module exports.
  46757. * @public
  46758. */
  46759. parseurl$1.exports = parseurl;
  46760. parseurl$1.exports.original = originalurl;
  46761. /**
  46762. * Parse the `req` url with memoization.
  46763. *
  46764. * @param {ServerRequest} req
  46765. * @return {Object}
  46766. * @public
  46767. */
  46768. function parseurl (req) {
  46769. var url = req.url;
  46770. if (url === undefined) {
  46771. // URL is undefined
  46772. return undefined
  46773. }
  46774. var parsed = req._parsedUrl;
  46775. if (fresh(url, parsed)) {
  46776. // Return cached URL parse
  46777. return parsed
  46778. }
  46779. // Parse the URL
  46780. parsed = fastparse(url);
  46781. parsed._raw = url;
  46782. return (req._parsedUrl = parsed)
  46783. }
  46784. /**
  46785. * Parse the `req` original url with fallback and memoization.
  46786. *
  46787. * @param {ServerRequest} req
  46788. * @return {Object}
  46789. * @public
  46790. */
  46791. function originalurl (req) {
  46792. var url = req.originalUrl;
  46793. if (typeof url !== 'string') {
  46794. // Fallback
  46795. return parseurl(req)
  46796. }
  46797. var parsed = req._parsedOriginalUrl;
  46798. if (fresh(url, parsed)) {
  46799. // Return cached URL parse
  46800. return parsed
  46801. }
  46802. // Parse the URL
  46803. parsed = fastparse(url);
  46804. parsed._raw = url;
  46805. return (req._parsedOriginalUrl = parsed)
  46806. }
  46807. /**
  46808. * Parse the `str` url with fast-path short-cut.
  46809. *
  46810. * @param {string} str
  46811. * @return {Object}
  46812. * @private
  46813. */
  46814. function fastparse (str) {
  46815. if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
  46816. return parse$9(str)
  46817. }
  46818. var pathname = str;
  46819. var query = null;
  46820. var search = null;
  46821. // This takes the regexp from https://github.com/joyent/node/pull/7878
  46822. // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/
  46823. // And unrolls it into a for loop
  46824. for (var i = 1; i < str.length; i++) {
  46825. switch (str.charCodeAt(i)) {
  46826. case 0x3f: /* ? */
  46827. if (search === null) {
  46828. pathname = str.substring(0, i);
  46829. query = str.substring(i + 1);
  46830. search = str.substring(i);
  46831. }
  46832. break
  46833. case 0x09: /* \t */
  46834. case 0x0a: /* \n */
  46835. case 0x0c: /* \f */
  46836. case 0x0d: /* \r */
  46837. case 0x20: /* */
  46838. case 0x23: /* # */
  46839. case 0xa0:
  46840. case 0xfeff:
  46841. return parse$9(str)
  46842. }
  46843. }
  46844. var url = Url !== undefined
  46845. ? new Url()
  46846. : {};
  46847. url.path = str;
  46848. url.href = str;
  46849. url.pathname = pathname;
  46850. if (search !== null) {
  46851. url.query = query;
  46852. url.search = search;
  46853. }
  46854. return url
  46855. }
  46856. /**
  46857. * Determine if parsed is still fresh for url.
  46858. *
  46859. * @param {string} url
  46860. * @param {object} parsedUrl
  46861. * @return {boolean}
  46862. * @private
  46863. */
  46864. function fresh (url, parsedUrl) {
  46865. return typeof parsedUrl === 'object' &&
  46866. parsedUrl !== null &&
  46867. (Url === undefined || parsedUrl instanceof Url) &&
  46868. parsedUrl._raw === url
  46869. }
  46870. var require$$0$1 = {
  46871. "100": "Continue",
  46872. "101": "Switching Protocols",
  46873. "102": "Processing",
  46874. "103": "Early Hints",
  46875. "200": "OK",
  46876. "201": "Created",
  46877. "202": "Accepted",
  46878. "203": "Non-Authoritative Information",
  46879. "204": "No Content",
  46880. "205": "Reset Content",
  46881. "206": "Partial Content",
  46882. "207": "Multi-Status",
  46883. "208": "Already Reported",
  46884. "226": "IM Used",
  46885. "300": "Multiple Choices",
  46886. "301": "Moved Permanently",
  46887. "302": "Found",
  46888. "303": "See Other",
  46889. "304": "Not Modified",
  46890. "305": "Use Proxy",
  46891. "306": "(Unused)",
  46892. "307": "Temporary Redirect",
  46893. "308": "Permanent Redirect",
  46894. "400": "Bad Request",
  46895. "401": "Unauthorized",
  46896. "402": "Payment Required",
  46897. "403": "Forbidden",
  46898. "404": "Not Found",
  46899. "405": "Method Not Allowed",
  46900. "406": "Not Acceptable",
  46901. "407": "Proxy Authentication Required",
  46902. "408": "Request Timeout",
  46903. "409": "Conflict",
  46904. "410": "Gone",
  46905. "411": "Length Required",
  46906. "412": "Precondition Failed",
  46907. "413": "Payload Too Large",
  46908. "414": "URI Too Long",
  46909. "415": "Unsupported Media Type",
  46910. "416": "Range Not Satisfiable",
  46911. "417": "Expectation Failed",
  46912. "418": "I'm a teapot",
  46913. "421": "Misdirected Request",
  46914. "422": "Unprocessable Entity",
  46915. "423": "Locked",
  46916. "424": "Failed Dependency",
  46917. "425": "Unordered Collection",
  46918. "426": "Upgrade Required",
  46919. "428": "Precondition Required",
  46920. "429": "Too Many Requests",
  46921. "431": "Request Header Fields Too Large",
  46922. "451": "Unavailable For Legal Reasons",
  46923. "500": "Internal Server Error",
  46924. "501": "Not Implemented",
  46925. "502": "Bad Gateway",
  46926. "503": "Service Unavailable",
  46927. "504": "Gateway Timeout",
  46928. "505": "HTTP Version Not Supported",
  46929. "506": "Variant Also Negotiates",
  46930. "507": "Insufficient Storage",
  46931. "508": "Loop Detected",
  46932. "509": "Bandwidth Limit Exceeded",
  46933. "510": "Not Extended",
  46934. "511": "Network Authentication Required"
  46935. };
  46936. /*!
  46937. * statuses
  46938. * Copyright(c) 2014 Jonathan Ong
  46939. * Copyright(c) 2016 Douglas Christopher Wilson
  46940. * MIT Licensed
  46941. */
  46942. /**
  46943. * Module dependencies.
  46944. * @private
  46945. */
  46946. var codes = require$$0$1;
  46947. /**
  46948. * Module exports.
  46949. * @public
  46950. */
  46951. var statuses$1 = status;
  46952. // status code to message map
  46953. status.STATUS_CODES = codes;
  46954. // array of status codes
  46955. status.codes = populateStatusesMap(status, codes);
  46956. // status codes for redirects
  46957. status.redirect = {
  46958. 300: true,
  46959. 301: true,
  46960. 302: true,
  46961. 303: true,
  46962. 305: true,
  46963. 307: true,
  46964. 308: true
  46965. };
  46966. // status codes for empty bodies
  46967. status.empty = {
  46968. 204: true,
  46969. 205: true,
  46970. 304: true
  46971. };
  46972. // status codes for when you should retry the request
  46973. status.retry = {
  46974. 502: true,
  46975. 503: true,
  46976. 504: true
  46977. };
  46978. /**
  46979. * Populate the statuses map for given codes.
  46980. * @private
  46981. */
  46982. function populateStatusesMap (statuses, codes) {
  46983. var arr = [];
  46984. Object.keys(codes).forEach(function forEachCode (code) {
  46985. var message = codes[code];
  46986. var status = Number(code);
  46987. // Populate properties
  46988. statuses[status] = message;
  46989. statuses[message] = status;
  46990. statuses[message.toLowerCase()] = status;
  46991. // Add to array
  46992. arr.push(status);
  46993. });
  46994. return arr
  46995. }
  46996. /**
  46997. * Get the status code.
  46998. *
  46999. * Given a number, this will throw if it is not a known status
  47000. * code, otherwise the code will be returned. Given a string,
  47001. * the string will be parsed for a number and return the code
  47002. * if valid, otherwise will lookup the code assuming this is
  47003. * the status message.
  47004. *
  47005. * @param {string|number} code
  47006. * @returns {number}
  47007. * @public
  47008. */
  47009. function status (code) {
  47010. if (typeof code === 'number') {
  47011. if (!status[code]) throw new Error('invalid status code: ' + code)
  47012. return code
  47013. }
  47014. if (typeof code !== 'string') {
  47015. throw new TypeError('code must be a number or string')
  47016. }
  47017. // '403'
  47018. var n = parseInt(code, 10);
  47019. if (!isNaN(n)) {
  47020. if (!status[n]) throw new Error('invalid status code: ' + n)
  47021. return n
  47022. }
  47023. n = status[code.toLowerCase()];
  47024. if (!n) throw new Error('invalid status message: "' + code + '"')
  47025. return n
  47026. }
  47027. /*!
  47028. * unpipe
  47029. * Copyright(c) 2015 Douglas Christopher Wilson
  47030. * MIT Licensed
  47031. */
  47032. /**
  47033. * Module exports.
  47034. * @public
  47035. */
  47036. var unpipe_1 = unpipe$1;
  47037. /**
  47038. * Determine if there are Node.js pipe-like data listeners.
  47039. * @private
  47040. */
  47041. function hasPipeDataListeners(stream) {
  47042. var listeners = stream.listeners('data');
  47043. for (var i = 0; i < listeners.length; i++) {
  47044. if (listeners[i].name === 'ondata') {
  47045. return true
  47046. }
  47047. }
  47048. return false
  47049. }
  47050. /**
  47051. * Unpipe a stream from all destinations.
  47052. *
  47053. * @param {object} stream
  47054. * @public
  47055. */
  47056. function unpipe$1(stream) {
  47057. if (!stream) {
  47058. throw new TypeError('argument stream is required')
  47059. }
  47060. if (typeof stream.unpipe === 'function') {
  47061. // new-style
  47062. stream.unpipe();
  47063. return
  47064. }
  47065. // Node.js 0.8 hack
  47066. if (!hasPipeDataListeners(stream)) {
  47067. return
  47068. }
  47069. var listener;
  47070. var listeners = stream.listeners('close');
  47071. for (var i = 0; i < listeners.length; i++) {
  47072. listener = listeners[i];
  47073. if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
  47074. continue
  47075. }
  47076. // invoke the listener
  47077. listener.call(stream);
  47078. }
  47079. }
  47080. /*!
  47081. * finalhandler
  47082. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  47083. * MIT Licensed
  47084. */
  47085. /**
  47086. * Module dependencies.
  47087. * @private
  47088. */
  47089. var debug$7 = src.exports('finalhandler');
  47090. var encodeUrl = encodeurl;
  47091. var escapeHtml = escapeHtml_1;
  47092. var onFinished = onFinished$2.exports;
  47093. var parseUrl$1 = parseurl$1.exports;
  47094. var statuses = statuses$1;
  47095. var unpipe = unpipe_1;
  47096. /**
  47097. * Module variables.
  47098. * @private
  47099. */
  47100. var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
  47101. var NEWLINE_REGEXP = /\n/g;
  47102. /* istanbul ignore next */
  47103. var defer$1 = typeof setImmediate === 'function'
  47104. ? setImmediate
  47105. : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)); };
  47106. var isFinished = onFinished.isFinished;
  47107. /**
  47108. * Create a minimal HTML document.
  47109. *
  47110. * @param {string} message
  47111. * @private
  47112. */
  47113. function createHtmlDocument (message) {
  47114. var body = escapeHtml(message)
  47115. .replace(NEWLINE_REGEXP, '<br>')
  47116. .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;');
  47117. return '<!DOCTYPE html>\n' +
  47118. '<html lang="en">\n' +
  47119. '<head>\n' +
  47120. '<meta charset="utf-8">\n' +
  47121. '<title>Error</title>\n' +
  47122. '</head>\n' +
  47123. '<body>\n' +
  47124. '<pre>' + body + '</pre>\n' +
  47125. '</body>\n' +
  47126. '</html>\n'
  47127. }
  47128. /**
  47129. * Module exports.
  47130. * @public
  47131. */
  47132. var finalhandler_1 = finalhandler$1;
  47133. /**
  47134. * Create a function to handle the final response.
  47135. *
  47136. * @param {Request} req
  47137. * @param {Response} res
  47138. * @param {Object} [options]
  47139. * @return {Function}
  47140. * @public
  47141. */
  47142. function finalhandler$1 (req, res, options) {
  47143. var opts = options || {};
  47144. // get environment
  47145. var env = opts.env || process.env.NODE_ENV || 'development';
  47146. // get error callback
  47147. var onerror = opts.onerror;
  47148. return function (err) {
  47149. var headers;
  47150. var msg;
  47151. var status;
  47152. // ignore 404 on in-flight response
  47153. if (!err && headersSent(res)) {
  47154. debug$7('cannot 404 after headers sent');
  47155. return
  47156. }
  47157. // unhandled error
  47158. if (err) {
  47159. // respect status code from error
  47160. status = getErrorStatusCode(err);
  47161. if (status === undefined) {
  47162. // fallback to status code on response
  47163. status = getResponseStatusCode(res);
  47164. } else {
  47165. // respect headers from error
  47166. headers = getErrorHeaders(err);
  47167. }
  47168. // get error message
  47169. msg = getErrorMessage(err, status, env);
  47170. } else {
  47171. // not found
  47172. status = 404;
  47173. msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req));
  47174. }
  47175. debug$7('default %s', status);
  47176. // schedule onerror callback
  47177. if (err && onerror) {
  47178. defer$1(onerror, err, req, res);
  47179. }
  47180. // cannot actually respond
  47181. if (headersSent(res)) {
  47182. debug$7('cannot %d after headers sent', status);
  47183. req.socket.destroy();
  47184. return
  47185. }
  47186. // send response
  47187. send$2(req, res, status, headers, msg);
  47188. }
  47189. }
  47190. /**
  47191. * Get headers from Error object.
  47192. *
  47193. * @param {Error} err
  47194. * @return {object}
  47195. * @private
  47196. */
  47197. function getErrorHeaders (err) {
  47198. if (!err.headers || typeof err.headers !== 'object') {
  47199. return undefined
  47200. }
  47201. var headers = Object.create(null);
  47202. var keys = Object.keys(err.headers);
  47203. for (var i = 0; i < keys.length; i++) {
  47204. var key = keys[i];
  47205. headers[key] = err.headers[key];
  47206. }
  47207. return headers
  47208. }
  47209. /**
  47210. * Get message from Error object, fallback to status message.
  47211. *
  47212. * @param {Error} err
  47213. * @param {number} status
  47214. * @param {string} env
  47215. * @return {string}
  47216. * @private
  47217. */
  47218. function getErrorMessage (err, status, env) {
  47219. var msg;
  47220. if (env !== 'production') {
  47221. // use err.stack, which typically includes err.message
  47222. msg = err.stack;
  47223. // fallback to err.toString() when possible
  47224. if (!msg && typeof err.toString === 'function') {
  47225. msg = err.toString();
  47226. }
  47227. }
  47228. return msg || statuses[status]
  47229. }
  47230. /**
  47231. * Get status code from Error object.
  47232. *
  47233. * @param {Error} err
  47234. * @return {number}
  47235. * @private
  47236. */
  47237. function getErrorStatusCode (err) {
  47238. // check err.status
  47239. if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
  47240. return err.status
  47241. }
  47242. // check err.statusCode
  47243. if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
  47244. return err.statusCode
  47245. }
  47246. return undefined
  47247. }
  47248. /**
  47249. * Get resource name for the request.
  47250. *
  47251. * This is typically just the original pathname of the request
  47252. * but will fallback to "resource" is that cannot be determined.
  47253. *
  47254. * @param {IncomingMessage} req
  47255. * @return {string}
  47256. * @private
  47257. */
  47258. function getResourceName (req) {
  47259. try {
  47260. return parseUrl$1.original(req).pathname
  47261. } catch (e) {
  47262. return 'resource'
  47263. }
  47264. }
  47265. /**
  47266. * Get status code from response.
  47267. *
  47268. * @param {OutgoingMessage} res
  47269. * @return {number}
  47270. * @private
  47271. */
  47272. function getResponseStatusCode (res) {
  47273. var status = res.statusCode;
  47274. // default status code to 500 if outside valid range
  47275. if (typeof status !== 'number' || status < 400 || status > 599) {
  47276. status = 500;
  47277. }
  47278. return status
  47279. }
  47280. /**
  47281. * Determine if the response headers have been sent.
  47282. *
  47283. * @param {object} res
  47284. * @returns {boolean}
  47285. * @private
  47286. */
  47287. function headersSent (res) {
  47288. return typeof res.headersSent !== 'boolean'
  47289. ? Boolean(res._header)
  47290. : res.headersSent
  47291. }
  47292. /**
  47293. * Send response.
  47294. *
  47295. * @param {IncomingMessage} req
  47296. * @param {OutgoingMessage} res
  47297. * @param {number} status
  47298. * @param {object} headers
  47299. * @param {string} message
  47300. * @private
  47301. */
  47302. function send$2 (req, res, status, headers, message) {
  47303. function write () {
  47304. // response body
  47305. var body = createHtmlDocument(message);
  47306. // response status
  47307. res.statusCode = status;
  47308. res.statusMessage = statuses[status];
  47309. // response headers
  47310. setHeaders(res, headers);
  47311. // security headers
  47312. res.setHeader('Content-Security-Policy', "default-src 'none'");
  47313. res.setHeader('X-Content-Type-Options', 'nosniff');
  47314. // standard headers
  47315. res.setHeader('Content-Type', 'text/html; charset=utf-8');
  47316. res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'));
  47317. if (req.method === 'HEAD') {
  47318. res.end();
  47319. return
  47320. }
  47321. res.end(body, 'utf8');
  47322. }
  47323. if (isFinished(req)) {
  47324. write();
  47325. return
  47326. }
  47327. // unpipe everything from the request
  47328. unpipe(req);
  47329. // flush the request
  47330. onFinished(req, write);
  47331. req.resume();
  47332. }
  47333. /**
  47334. * Set response headers from an object.
  47335. *
  47336. * @param {OutgoingMessage} res
  47337. * @param {object} headers
  47338. * @private
  47339. */
  47340. function setHeaders (res, headers) {
  47341. if (!headers) {
  47342. return
  47343. }
  47344. var keys = Object.keys(headers);
  47345. for (var i = 0; i < keys.length; i++) {
  47346. var key = keys[i];
  47347. res.setHeader(key, headers[key]);
  47348. }
  47349. }
  47350. var utilsMerge = {exports: {}};
  47351. /**
  47352. * Merge object b with object a.
  47353. *
  47354. * var a = { foo: 'bar' }
  47355. * , b = { bar: 'baz' };
  47356. *
  47357. * merge(a, b);
  47358. * // => { foo: 'bar', bar: 'baz' }
  47359. *
  47360. * @param {Object} a
  47361. * @param {Object} b
  47362. * @return {Object}
  47363. * @api public
  47364. */
  47365. (function (module, exports) {
  47366. module.exports = function(a, b){
  47367. if (a && b) {
  47368. for (var key in b) {
  47369. a[key] = b[key];
  47370. }
  47371. }
  47372. return a;
  47373. };
  47374. }(utilsMerge));
  47375. /*!
  47376. * connect
  47377. * Copyright(c) 2010 Sencha Inc.
  47378. * Copyright(c) 2011 TJ Holowaychuk
  47379. * Copyright(c) 2015 Douglas Christopher Wilson
  47380. * MIT Licensed
  47381. */
  47382. /**
  47383. * Module dependencies.
  47384. * @private
  47385. */
  47386. var debug$6 = src$1.exports('connect:dispatcher');
  47387. var EventEmitter$3 = require$$0__default$6.EventEmitter;
  47388. var finalhandler = finalhandler_1;
  47389. var http$4 = require$$1__default$1;
  47390. var merge = utilsMerge.exports;
  47391. var parseUrl = parseurl$1.exports;
  47392. /**
  47393. * Module exports.
  47394. * @public
  47395. */
  47396. var connect = createServer$1;
  47397. /**
  47398. * Module variables.
  47399. * @private
  47400. */
  47401. var env$1 = process.env.NODE_ENV || 'development';
  47402. var proto = {};
  47403. /* istanbul ignore next */
  47404. var defer = typeof setImmediate === 'function'
  47405. ? setImmediate
  47406. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  47407. /**
  47408. * Create a new connect server.
  47409. *
  47410. * @return {function}
  47411. * @public
  47412. */
  47413. function createServer$1() {
  47414. function app(req, res, next){ app.handle(req, res, next); }
  47415. merge(app, proto);
  47416. merge(app, EventEmitter$3.prototype);
  47417. app.route = '/';
  47418. app.stack = [];
  47419. return app;
  47420. }
  47421. /**
  47422. * Utilize the given middleware `handle` to the given `route`,
  47423. * defaulting to _/_. This "route" is the mount-point for the
  47424. * middleware, when given a value other than _/_ the middleware
  47425. * is only effective when that segment is present in the request's
  47426. * pathname.
  47427. *
  47428. * For example if we were to mount a function at _/admin_, it would
  47429. * be invoked on _/admin_, and _/admin/settings_, however it would
  47430. * not be invoked for _/_, or _/posts_.
  47431. *
  47432. * @param {String|Function|Server} route, callback or server
  47433. * @param {Function|Server} callback or server
  47434. * @return {Server} for chaining
  47435. * @public
  47436. */
  47437. proto.use = function use(route, fn) {
  47438. var handle = fn;
  47439. var path = route;
  47440. // default route to '/'
  47441. if (typeof route !== 'string') {
  47442. handle = route;
  47443. path = '/';
  47444. }
  47445. // wrap sub-apps
  47446. if (typeof handle.handle === 'function') {
  47447. var server = handle;
  47448. server.route = path;
  47449. handle = function (req, res, next) {
  47450. server.handle(req, res, next);
  47451. };
  47452. }
  47453. // wrap vanilla http.Servers
  47454. if (handle instanceof http$4.Server) {
  47455. handle = handle.listeners('request')[0];
  47456. }
  47457. // strip trailing slash
  47458. if (path[path.length - 1] === '/') {
  47459. path = path.slice(0, -1);
  47460. }
  47461. // add the middleware
  47462. debug$6('use %s %s', path || '/', handle.name || 'anonymous');
  47463. this.stack.push({ route: path, handle: handle });
  47464. return this;
  47465. };
  47466. /**
  47467. * Handle server requests, punting them down
  47468. * the middleware stack.
  47469. *
  47470. * @private
  47471. */
  47472. proto.handle = function handle(req, res, out) {
  47473. var index = 0;
  47474. var protohost = getProtohost(req.url) || '';
  47475. var removed = '';
  47476. var slashAdded = false;
  47477. var stack = this.stack;
  47478. // final function handler
  47479. var done = out || finalhandler(req, res, {
  47480. env: env$1,
  47481. onerror: logerror
  47482. });
  47483. // store the original URL
  47484. req.originalUrl = req.originalUrl || req.url;
  47485. function next(err) {
  47486. if (slashAdded) {
  47487. req.url = req.url.substr(1);
  47488. slashAdded = false;
  47489. }
  47490. if (removed.length !== 0) {
  47491. req.url = protohost + removed + req.url.substr(protohost.length);
  47492. removed = '';
  47493. }
  47494. // next callback
  47495. var layer = stack[index++];
  47496. // all done
  47497. if (!layer) {
  47498. defer(done, err);
  47499. return;
  47500. }
  47501. // route data
  47502. var path = parseUrl(req).pathname || '/';
  47503. var route = layer.route;
  47504. // skip this layer if the route doesn't match
  47505. if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
  47506. return next(err);
  47507. }
  47508. // skip if route match does not border "/", ".", or end
  47509. var c = path.length > route.length && path[route.length];
  47510. if (c && c !== '/' && c !== '.') {
  47511. return next(err);
  47512. }
  47513. // trim off the part of the url that matches the route
  47514. if (route.length !== 0 && route !== '/') {
  47515. removed = route;
  47516. req.url = protohost + req.url.substr(protohost.length + removed.length);
  47517. // ensure leading slash
  47518. if (!protohost && req.url[0] !== '/') {
  47519. req.url = '/' + req.url;
  47520. slashAdded = true;
  47521. }
  47522. }
  47523. // call the layer handle
  47524. call(layer.handle, route, err, req, res, next);
  47525. }
  47526. next();
  47527. };
  47528. /**
  47529. * Listen for connections.
  47530. *
  47531. * This method takes the same arguments
  47532. * as node's `http.Server#listen()`.
  47533. *
  47534. * HTTP and HTTPS:
  47535. *
  47536. * If you run your application both as HTTP
  47537. * and HTTPS you may wrap them individually,
  47538. * since your Connect "server" is really just
  47539. * a JavaScript `Function`.
  47540. *
  47541. * var connect = require('connect')
  47542. * , http = require('http')
  47543. * , https = require('https');
  47544. *
  47545. * var app = connect();
  47546. *
  47547. * http.createServer(app).listen(80);
  47548. * https.createServer(options, app).listen(443);
  47549. *
  47550. * @return {http.Server}
  47551. * @api public
  47552. */
  47553. proto.listen = function listen() {
  47554. var server = http$4.createServer(this);
  47555. return server.listen.apply(server, arguments);
  47556. };
  47557. /**
  47558. * Invoke a route handle.
  47559. * @private
  47560. */
  47561. function call(handle, route, err, req, res, next) {
  47562. var arity = handle.length;
  47563. var error = err;
  47564. var hasError = Boolean(err);
  47565. debug$6('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
  47566. try {
  47567. if (hasError && arity === 4) {
  47568. // error-handling middleware
  47569. handle(err, req, res, next);
  47570. return;
  47571. } else if (!hasError && arity < 4) {
  47572. // request-handling middleware
  47573. handle(req, res, next);
  47574. return;
  47575. }
  47576. } catch (e) {
  47577. // replace the error
  47578. error = e;
  47579. }
  47580. // continue
  47581. next(error);
  47582. }
  47583. /**
  47584. * Log error using console.error.
  47585. *
  47586. * @param {Error} err
  47587. * @private
  47588. */
  47589. function logerror(err) {
  47590. if (env$1 !== 'test') console.error(err.stack || err.toString());
  47591. }
  47592. /**
  47593. * Get get protocol + host for a URL.
  47594. *
  47595. * @param {string} url
  47596. * @private
  47597. */
  47598. function getProtohost(url) {
  47599. if (url.length === 0 || url[0] === '/') {
  47600. return undefined;
  47601. }
  47602. var fqdnIndex = url.indexOf('://');
  47603. return fqdnIndex !== -1 && url.lastIndexOf('?', fqdnIndex) === -1
  47604. ? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
  47605. : undefined;
  47606. }
  47607. var lib$1 = {exports: {}};
  47608. /*
  47609. object-assign
  47610. (c) Sindre Sorhus
  47611. @license MIT
  47612. */
  47613. /* eslint-disable no-unused-vars */
  47614. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  47615. var hasOwnProperty = Object.prototype.hasOwnProperty;
  47616. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  47617. function toObject(val) {
  47618. if (val === null || val === undefined) {
  47619. throw new TypeError('Object.assign cannot be called with null or undefined');
  47620. }
  47621. return Object(val);
  47622. }
  47623. function shouldUseNative() {
  47624. try {
  47625. if (!Object.assign) {
  47626. return false;
  47627. }
  47628. // Detect buggy property enumeration order in older V8 versions.
  47629. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  47630. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  47631. test1[5] = 'de';
  47632. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  47633. return false;
  47634. }
  47635. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  47636. var test2 = {};
  47637. for (var i = 0; i < 10; i++) {
  47638. test2['_' + String.fromCharCode(i)] = i;
  47639. }
  47640. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  47641. return test2[n];
  47642. });
  47643. if (order2.join('') !== '0123456789') {
  47644. return false;
  47645. }
  47646. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  47647. var test3 = {};
  47648. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  47649. test3[letter] = letter;
  47650. });
  47651. if (Object.keys(Object.assign({}, test3)).join('') !==
  47652. 'abcdefghijklmnopqrst') {
  47653. return false;
  47654. }
  47655. return true;
  47656. } catch (err) {
  47657. // We don't expect any of the above to throw, but better to be safe.
  47658. return false;
  47659. }
  47660. }
  47661. var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  47662. var from;
  47663. var to = toObject(target);
  47664. var symbols;
  47665. for (var s = 1; s < arguments.length; s++) {
  47666. from = Object(arguments[s]);
  47667. for (var key in from) {
  47668. if (hasOwnProperty.call(from, key)) {
  47669. to[key] = from[key];
  47670. }
  47671. }
  47672. if (getOwnPropertySymbols) {
  47673. symbols = getOwnPropertySymbols(from);
  47674. for (var i = 0; i < symbols.length; i++) {
  47675. if (propIsEnumerable.call(from, symbols[i])) {
  47676. to[symbols[i]] = from[symbols[i]];
  47677. }
  47678. }
  47679. }
  47680. }
  47681. return to;
  47682. };
  47683. var vary$1 = {exports: {}};
  47684. /*!
  47685. * vary
  47686. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  47687. * MIT Licensed
  47688. */
  47689. /**
  47690. * Module exports.
  47691. */
  47692. vary$1.exports = vary;
  47693. vary$1.exports.append = append;
  47694. /**
  47695. * RegExp to match field-name in RFC 7230 sec 3.2
  47696. *
  47697. * field-name = token
  47698. * token = 1*tchar
  47699. * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  47700. * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  47701. * / DIGIT / ALPHA
  47702. * ; any VCHAR, except delimiters
  47703. */
  47704. var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  47705. /**
  47706. * Append a field to a vary header.
  47707. *
  47708. * @param {String} header
  47709. * @param {String|Array} field
  47710. * @return {String}
  47711. * @public
  47712. */
  47713. function append (header, field) {
  47714. if (typeof header !== 'string') {
  47715. throw new TypeError('header argument is required')
  47716. }
  47717. if (!field) {
  47718. throw new TypeError('field argument is required')
  47719. }
  47720. // get fields array
  47721. var fields = !Array.isArray(field)
  47722. ? parse$8(String(field))
  47723. : field;
  47724. // assert on invalid field names
  47725. for (var j = 0; j < fields.length; j++) {
  47726. if (!FIELD_NAME_REGEXP.test(fields[j])) {
  47727. throw new TypeError('field argument contains an invalid header name')
  47728. }
  47729. }
  47730. // existing, unspecified vary
  47731. if (header === '*') {
  47732. return header
  47733. }
  47734. // enumerate current values
  47735. var val = header;
  47736. var vals = parse$8(header.toLowerCase());
  47737. // unspecified vary
  47738. if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
  47739. return '*'
  47740. }
  47741. for (var i = 0; i < fields.length; i++) {
  47742. var fld = fields[i].toLowerCase();
  47743. // append value (case-preserving)
  47744. if (vals.indexOf(fld) === -1) {
  47745. vals.push(fld);
  47746. val = val
  47747. ? val + ', ' + fields[i]
  47748. : fields[i];
  47749. }
  47750. }
  47751. return val
  47752. }
  47753. /**
  47754. * Parse a vary header into an array.
  47755. *
  47756. * @param {String} header
  47757. * @return {Array}
  47758. * @private
  47759. */
  47760. function parse$8 (header) {
  47761. var end = 0;
  47762. var list = [];
  47763. var start = 0;
  47764. // gather tokens
  47765. for (var i = 0, len = header.length; i < len; i++) {
  47766. switch (header.charCodeAt(i)) {
  47767. case 0x20: /* */
  47768. if (start === end) {
  47769. start = end = i + 1;
  47770. }
  47771. break
  47772. case 0x2c: /* , */
  47773. list.push(header.substring(start, end));
  47774. start = end = i + 1;
  47775. break
  47776. default:
  47777. end = i + 1;
  47778. break
  47779. }
  47780. }
  47781. // final token
  47782. list.push(header.substring(start, end));
  47783. return list
  47784. }
  47785. /**
  47786. * Mark that a request is varied on a header field.
  47787. *
  47788. * @param {Object} res
  47789. * @param {String|Array} field
  47790. * @public
  47791. */
  47792. function vary (res, field) {
  47793. if (!res || !res.getHeader || !res.setHeader) {
  47794. // quack quack
  47795. throw new TypeError('res argument is required')
  47796. }
  47797. // get existing header
  47798. var val = res.getHeader('Vary') || '';
  47799. var header = Array.isArray(val)
  47800. ? val.join(', ')
  47801. : String(val);
  47802. // set new header
  47803. if ((val = append(header, field))) {
  47804. res.setHeader('Vary', val);
  47805. }
  47806. }
  47807. (function () {
  47808. var assign = objectAssign;
  47809. var vary = vary$1.exports;
  47810. var defaults = {
  47811. origin: '*',
  47812. methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  47813. preflightContinue: false,
  47814. optionsSuccessStatus: 204
  47815. };
  47816. function isString(s) {
  47817. return typeof s === 'string' || s instanceof String;
  47818. }
  47819. function isOriginAllowed(origin, allowedOrigin) {
  47820. if (Array.isArray(allowedOrigin)) {
  47821. for (var i = 0; i < allowedOrigin.length; ++i) {
  47822. if (isOriginAllowed(origin, allowedOrigin[i])) {
  47823. return true;
  47824. }
  47825. }
  47826. return false;
  47827. } else if (isString(allowedOrigin)) {
  47828. return origin === allowedOrigin;
  47829. } else if (allowedOrigin instanceof RegExp) {
  47830. return allowedOrigin.test(origin);
  47831. } else {
  47832. return !!allowedOrigin;
  47833. }
  47834. }
  47835. function configureOrigin(options, req) {
  47836. var requestOrigin = req.headers.origin,
  47837. headers = [],
  47838. isAllowed;
  47839. if (!options.origin || options.origin === '*') {
  47840. // allow any origin
  47841. headers.push([{
  47842. key: 'Access-Control-Allow-Origin',
  47843. value: '*'
  47844. }]);
  47845. } else if (isString(options.origin)) {
  47846. // fixed origin
  47847. headers.push([{
  47848. key: 'Access-Control-Allow-Origin',
  47849. value: options.origin
  47850. }]);
  47851. headers.push([{
  47852. key: 'Vary',
  47853. value: 'Origin'
  47854. }]);
  47855. } else {
  47856. isAllowed = isOriginAllowed(requestOrigin, options.origin);
  47857. // reflect origin
  47858. headers.push([{
  47859. key: 'Access-Control-Allow-Origin',
  47860. value: isAllowed ? requestOrigin : false
  47861. }]);
  47862. headers.push([{
  47863. key: 'Vary',
  47864. value: 'Origin'
  47865. }]);
  47866. }
  47867. return headers;
  47868. }
  47869. function configureMethods(options) {
  47870. var methods = options.methods;
  47871. if (methods.join) {
  47872. methods = options.methods.join(','); // .methods is an array, so turn it into a string
  47873. }
  47874. return {
  47875. key: 'Access-Control-Allow-Methods',
  47876. value: methods
  47877. };
  47878. }
  47879. function configureCredentials(options) {
  47880. if (options.credentials === true) {
  47881. return {
  47882. key: 'Access-Control-Allow-Credentials',
  47883. value: 'true'
  47884. };
  47885. }
  47886. return null;
  47887. }
  47888. function configureAllowedHeaders(options, req) {
  47889. var allowedHeaders = options.allowedHeaders || options.headers;
  47890. var headers = [];
  47891. if (!allowedHeaders) {
  47892. allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
  47893. headers.push([{
  47894. key: 'Vary',
  47895. value: 'Access-Control-Request-Headers'
  47896. }]);
  47897. } else if (allowedHeaders.join) {
  47898. allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
  47899. }
  47900. if (allowedHeaders && allowedHeaders.length) {
  47901. headers.push([{
  47902. key: 'Access-Control-Allow-Headers',
  47903. value: allowedHeaders
  47904. }]);
  47905. }
  47906. return headers;
  47907. }
  47908. function configureExposedHeaders(options) {
  47909. var headers = options.exposedHeaders;
  47910. if (!headers) {
  47911. return null;
  47912. } else if (headers.join) {
  47913. headers = headers.join(','); // .headers is an array, so turn it into a string
  47914. }
  47915. if (headers && headers.length) {
  47916. return {
  47917. key: 'Access-Control-Expose-Headers',
  47918. value: headers
  47919. };
  47920. }
  47921. return null;
  47922. }
  47923. function configureMaxAge(options) {
  47924. var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString();
  47925. if (maxAge && maxAge.length) {
  47926. return {
  47927. key: 'Access-Control-Max-Age',
  47928. value: maxAge
  47929. };
  47930. }
  47931. return null;
  47932. }
  47933. function applyHeaders(headers, res) {
  47934. for (var i = 0, n = headers.length; i < n; i++) {
  47935. var header = headers[i];
  47936. if (header) {
  47937. if (Array.isArray(header)) {
  47938. applyHeaders(header, res);
  47939. } else if (header.key === 'Vary' && header.value) {
  47940. vary(res, header.value);
  47941. } else if (header.value) {
  47942. res.setHeader(header.key, header.value);
  47943. }
  47944. }
  47945. }
  47946. }
  47947. function cors(options, req, res, next) {
  47948. var headers = [],
  47949. method = req.method && req.method.toUpperCase && req.method.toUpperCase();
  47950. if (method === 'OPTIONS') {
  47951. // preflight
  47952. headers.push(configureOrigin(options, req));
  47953. headers.push(configureCredentials(options));
  47954. headers.push(configureMethods(options));
  47955. headers.push(configureAllowedHeaders(options, req));
  47956. headers.push(configureMaxAge(options));
  47957. headers.push(configureExposedHeaders(options));
  47958. applyHeaders(headers, res);
  47959. if (options.preflightContinue) {
  47960. next();
  47961. } else {
  47962. // Safari (and potentially other browsers) need content-length 0,
  47963. // for 204 or they just hang waiting for a body
  47964. res.statusCode = options.optionsSuccessStatus;
  47965. res.setHeader('Content-Length', '0');
  47966. res.end();
  47967. }
  47968. } else {
  47969. // actual response
  47970. headers.push(configureOrigin(options, req));
  47971. headers.push(configureCredentials(options));
  47972. headers.push(configureExposedHeaders(options));
  47973. applyHeaders(headers, res);
  47974. next();
  47975. }
  47976. }
  47977. function middlewareWrapper(o) {
  47978. // if options are static (either via defaults or custom options passed in), wrap in a function
  47979. var optionsCallback = null;
  47980. if (typeof o === 'function') {
  47981. optionsCallback = o;
  47982. } else {
  47983. optionsCallback = function (req, cb) {
  47984. cb(null, o);
  47985. };
  47986. }
  47987. return function corsMiddleware(req, res, next) {
  47988. optionsCallback(req, function (err, options) {
  47989. if (err) {
  47990. next(err);
  47991. } else {
  47992. var corsOptions = assign({}, defaults, options);
  47993. var originCallback = null;
  47994. if (corsOptions.origin && typeof corsOptions.origin === 'function') {
  47995. originCallback = corsOptions.origin;
  47996. } else if (corsOptions.origin) {
  47997. originCallback = function (origin, cb) {
  47998. cb(null, corsOptions.origin);
  47999. };
  48000. }
  48001. if (originCallback) {
  48002. originCallback(req.headers.origin, function (err2, origin) {
  48003. if (err2 || !origin) {
  48004. next(err2);
  48005. } else {
  48006. corsOptions.origin = origin;
  48007. cors(corsOptions, req, res, next);
  48008. }
  48009. });
  48010. } else {
  48011. next();
  48012. }
  48013. }
  48014. });
  48015. };
  48016. }
  48017. // can pass either an options hash, an options delegate, or nothing
  48018. lib$1.exports = middlewareWrapper;
  48019. }());
  48020. var corsMiddleware = lib$1.exports;
  48021. var chokidar = {};
  48022. const fs$b = fs__default;
  48023. const { Readable } = require$$0__default$2;
  48024. const sysPath$3 = path__default;
  48025. const { promisify: promisify$4 } = require$$0__default$3;
  48026. const picomatch$1 = picomatch$3;
  48027. const readdir$1 = promisify$4(fs$b.readdir);
  48028. const stat$3 = promisify$4(fs$b.stat);
  48029. const lstat$2 = promisify$4(fs$b.lstat);
  48030. const realpath$1 = promisify$4(fs$b.realpath);
  48031. /**
  48032. * @typedef {Object} EntryInfo
  48033. * @property {String} path
  48034. * @property {String} fullPath
  48035. * @property {fs.Stats=} stats
  48036. * @property {fs.Dirent=} dirent
  48037. * @property {String} basename
  48038. */
  48039. const BANG$2 = '!';
  48040. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  48041. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  48042. const FILE_TYPE = 'files';
  48043. const DIR_TYPE = 'directories';
  48044. const FILE_DIR_TYPE = 'files_directories';
  48045. const EVERYTHING_TYPE = 'all';
  48046. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  48047. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  48048. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  48049. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  48050. const normalizeFilter = filter => {
  48051. if (filter === undefined) return;
  48052. if (typeof filter === 'function') return filter;
  48053. if (typeof filter === 'string') {
  48054. const glob = picomatch$1(filter.trim());
  48055. return entry => glob(entry.basename);
  48056. }
  48057. if (Array.isArray(filter)) {
  48058. const positive = [];
  48059. const negative = [];
  48060. for (const item of filter) {
  48061. const trimmed = item.trim();
  48062. if (trimmed.charAt(0) === BANG$2) {
  48063. negative.push(picomatch$1(trimmed.slice(1)));
  48064. } else {
  48065. positive.push(picomatch$1(trimmed));
  48066. }
  48067. }
  48068. if (negative.length > 0) {
  48069. if (positive.length > 0) {
  48070. return entry =>
  48071. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  48072. }
  48073. return entry => !negative.some(f => f(entry.basename));
  48074. }
  48075. return entry => positive.some(f => f(entry.basename));
  48076. }
  48077. };
  48078. class ReaddirpStream extends Readable {
  48079. static get defaultOptions() {
  48080. return {
  48081. root: '.',
  48082. /* eslint-disable no-unused-vars */
  48083. fileFilter: (path) => true,
  48084. directoryFilter: (path) => true,
  48085. /* eslint-enable no-unused-vars */
  48086. type: FILE_TYPE,
  48087. lstat: false,
  48088. depth: 2147483648,
  48089. alwaysStat: false
  48090. };
  48091. }
  48092. constructor(options = {}) {
  48093. super({
  48094. objectMode: true,
  48095. autoDestroy: true,
  48096. highWaterMark: options.highWaterMark || 4096
  48097. });
  48098. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  48099. const { root, type } = opts;
  48100. this._fileFilter = normalizeFilter(opts.fileFilter);
  48101. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  48102. const statMethod = opts.lstat ? lstat$2 : stat$3;
  48103. // Use bigint stats if it's windows and stat() supports options (node 10+).
  48104. if (wantBigintFsStats) {
  48105. this._stat = path => statMethod(path, { bigint: true });
  48106. } else {
  48107. this._stat = statMethod;
  48108. }
  48109. this._maxDepth = opts.depth;
  48110. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  48111. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  48112. this._wantsEverything = type === EVERYTHING_TYPE;
  48113. this._root = sysPath$3.resolve(root);
  48114. this._isDirent = ('Dirent' in fs$b) && !opts.alwaysStat;
  48115. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  48116. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  48117. // Launch stream with one parent, the root dir.
  48118. this.parents = [this._exploreDir(root, 1)];
  48119. this.reading = false;
  48120. this.parent = undefined;
  48121. }
  48122. async _read(batch) {
  48123. if (this.reading) return;
  48124. this.reading = true;
  48125. try {
  48126. while (!this.destroyed && batch > 0) {
  48127. const { path, depth, files = [] } = this.parent || {};
  48128. if (files.length > 0) {
  48129. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  48130. for (const entry of await Promise.all(slice)) {
  48131. if (this.destroyed) return;
  48132. const entryType = await this._getEntryType(entry);
  48133. if (entryType === 'directory' && this._directoryFilter(entry)) {
  48134. if (depth <= this._maxDepth) {
  48135. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  48136. }
  48137. if (this._wantsDir) {
  48138. this.push(entry);
  48139. batch--;
  48140. }
  48141. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  48142. if (this._wantsFile) {
  48143. this.push(entry);
  48144. batch--;
  48145. }
  48146. }
  48147. }
  48148. } else {
  48149. const parent = this.parents.pop();
  48150. if (!parent) {
  48151. this.push(null);
  48152. break;
  48153. }
  48154. this.parent = await parent;
  48155. if (this.destroyed) return;
  48156. }
  48157. }
  48158. } catch (error) {
  48159. this.destroy(error);
  48160. } finally {
  48161. this.reading = false;
  48162. }
  48163. }
  48164. async _exploreDir(path, depth) {
  48165. let files;
  48166. try {
  48167. files = await readdir$1(path, this._rdOptions);
  48168. } catch (error) {
  48169. this._onError(error);
  48170. }
  48171. return { files, depth, path };
  48172. }
  48173. async _formatEntry(dirent, path) {
  48174. let entry;
  48175. try {
  48176. const basename = this._isDirent ? dirent.name : dirent;
  48177. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  48178. entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
  48179. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  48180. } catch (err) {
  48181. this._onError(err);
  48182. }
  48183. return entry;
  48184. }
  48185. _onError(err) {
  48186. if (isNormalFlowError(err) && !this.destroyed) {
  48187. this.emit('warn', err);
  48188. } else {
  48189. this.destroy(err);
  48190. }
  48191. }
  48192. async _getEntryType(entry) {
  48193. // entry may be undefined, because a warning or an error were emitted
  48194. // and the statsProp is undefined
  48195. const stats = entry && entry[this._statsProp];
  48196. if (!stats) {
  48197. return;
  48198. }
  48199. if (stats.isFile()) {
  48200. return 'file';
  48201. }
  48202. if (stats.isDirectory()) {
  48203. return 'directory';
  48204. }
  48205. if (stats && stats.isSymbolicLink()) {
  48206. const full = entry.fullPath;
  48207. try {
  48208. const entryRealPath = await realpath$1(full);
  48209. const entryRealPathStats = await lstat$2(entryRealPath);
  48210. if (entryRealPathStats.isFile()) {
  48211. return 'file';
  48212. }
  48213. if (entryRealPathStats.isDirectory()) {
  48214. const len = entryRealPath.length;
  48215. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  48216. const recursiveError = new Error(
  48217. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  48218. );
  48219. recursiveError.code = RECURSIVE_ERROR_CODE;
  48220. return this._onError(recursiveError);
  48221. }
  48222. return 'directory';
  48223. }
  48224. } catch (error) {
  48225. this._onError(error);
  48226. }
  48227. }
  48228. }
  48229. _includeAsFile(entry) {
  48230. const stats = entry && entry[this._statsProp];
  48231. return stats && this._wantsEverything && !stats.isDirectory();
  48232. }
  48233. }
  48234. /**
  48235. * @typedef {Object} ReaddirpArguments
  48236. * @property {Function=} fileFilter
  48237. * @property {Function=} directoryFilter
  48238. * @property {String=} type
  48239. * @property {Number=} depth
  48240. * @property {String=} root
  48241. * @property {Boolean=} lstat
  48242. * @property {Boolean=} bigint
  48243. */
  48244. /**
  48245. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  48246. * @param {String} root Root directory
  48247. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  48248. */
  48249. const readdirp$1 = (root, options = {}) => {
  48250. let type = options.entryType || options.type;
  48251. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  48252. if (type) options.type = type;
  48253. if (!root) {
  48254. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  48255. } else if (typeof root !== 'string') {
  48256. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  48257. } else if (type && !ALL_TYPES.includes(type)) {
  48258. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  48259. }
  48260. options.root = root;
  48261. return new ReaddirpStream(options);
  48262. };
  48263. const readdirpPromise = (root, options = {}) => {
  48264. return new Promise((resolve, reject) => {
  48265. const files = [];
  48266. readdirp$1(root, options)
  48267. .on('data', entry => files.push(entry))
  48268. .on('end', () => resolve(files))
  48269. .on('error', error => reject(error));
  48270. });
  48271. };
  48272. readdirp$1.promise = readdirpPromise;
  48273. readdirp$1.ReaddirpStream = ReaddirpStream;
  48274. readdirp$1.default = readdirp$1;
  48275. var readdirp_1 = readdirp$1;
  48276. var anymatch$2 = {exports: {}};
  48277. /*!
  48278. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  48279. *
  48280. * Copyright (c) 2014-2018, Jon Schlinkert.
  48281. * Released under the MIT License.
  48282. */
  48283. var normalizePath$2 = function(path, stripTrailing) {
  48284. if (typeof path !== 'string') {
  48285. throw new TypeError('expected path to be a string');
  48286. }
  48287. if (path === '\\' || path === '/') return '/';
  48288. var len = path.length;
  48289. if (len <= 1) return path;
  48290. // ensure that win32 namespaces has two leading slashes, so that the path is
  48291. // handled properly by the win32 version of path.parse() after being normalized
  48292. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  48293. var prefix = '';
  48294. if (len > 4 && path[3] === '\\') {
  48295. var ch = path[2];
  48296. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  48297. path = path.slice(2);
  48298. prefix = '//';
  48299. }
  48300. }
  48301. var segs = path.split(/[/\\]+/);
  48302. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  48303. segs.pop();
  48304. }
  48305. return prefix + segs.join('/');
  48306. };
  48307. Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
  48308. const picomatch = picomatch$3;
  48309. const normalizePath$1 = normalizePath$2;
  48310. /**
  48311. * @typedef {(testString: string) => boolean} AnymatchFn
  48312. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  48313. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  48314. */
  48315. const BANG$1 = '!';
  48316. const DEFAULT_OPTIONS = {returnIndex: false};
  48317. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  48318. /**
  48319. * @param {AnymatchPattern} matcher
  48320. * @param {object} options
  48321. * @returns {AnymatchFn}
  48322. */
  48323. const createPattern = (matcher, options) => {
  48324. if (typeof matcher === 'function') {
  48325. return matcher;
  48326. }
  48327. if (typeof matcher === 'string') {
  48328. const glob = picomatch(matcher, options);
  48329. return (string) => matcher === string || glob(string);
  48330. }
  48331. if (matcher instanceof RegExp) {
  48332. return (string) => matcher.test(string);
  48333. }
  48334. return (string) => false;
  48335. };
  48336. /**
  48337. * @param {Array<Function>} patterns
  48338. * @param {Array<Function>} negPatterns
  48339. * @param {String|Array} args
  48340. * @param {Boolean} returnIndex
  48341. * @returns {boolean|number}
  48342. */
  48343. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  48344. const isList = Array.isArray(args);
  48345. const _path = isList ? args[0] : args;
  48346. if (!isList && typeof _path !== 'string') {
  48347. throw new TypeError('anymatch: second argument must be a string: got ' +
  48348. Object.prototype.toString.call(_path))
  48349. }
  48350. const path = normalizePath$1(_path);
  48351. for (let index = 0; index < negPatterns.length; index++) {
  48352. const nglob = negPatterns[index];
  48353. if (nglob(path)) {
  48354. return returnIndex ? -1 : false;
  48355. }
  48356. }
  48357. const applied = isList && [path].concat(args.slice(1));
  48358. for (let index = 0; index < patterns.length; index++) {
  48359. const pattern = patterns[index];
  48360. if (isList ? pattern(...applied) : pattern(path)) {
  48361. return returnIndex ? index : true;
  48362. }
  48363. }
  48364. return returnIndex ? -1 : false;
  48365. };
  48366. /**
  48367. * @param {AnymatchMatcher} matchers
  48368. * @param {Array|string} testString
  48369. * @param {object} options
  48370. * @returns {boolean|number|Function}
  48371. */
  48372. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  48373. if (matchers == null) {
  48374. throw new TypeError('anymatch: specify first argument');
  48375. }
  48376. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  48377. const returnIndex = opts.returnIndex || false;
  48378. // Early cache for matchers.
  48379. const mtchers = arrify$1(matchers);
  48380. const negatedGlobs = mtchers
  48381. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  48382. .map(item => item.slice(1))
  48383. .map(item => picomatch(item, opts));
  48384. const patterns = mtchers
  48385. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
  48386. .map(matcher => createPattern(matcher, opts));
  48387. if (testString == null) {
  48388. return (testString, ri = false) => {
  48389. const returnIndex = typeof ri === 'boolean' ? ri : false;
  48390. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  48391. }
  48392. }
  48393. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  48394. };
  48395. anymatch$1.default = anymatch$1;
  48396. anymatch$2.exports = anymatch$1;
  48397. var require$$0 = [
  48398. "3dm",
  48399. "3ds",
  48400. "3g2",
  48401. "3gp",
  48402. "7z",
  48403. "a",
  48404. "aac",
  48405. "adp",
  48406. "ai",
  48407. "aif",
  48408. "aiff",
  48409. "alz",
  48410. "ape",
  48411. "apk",
  48412. "appimage",
  48413. "ar",
  48414. "arj",
  48415. "asf",
  48416. "au",
  48417. "avi",
  48418. "bak",
  48419. "baml",
  48420. "bh",
  48421. "bin",
  48422. "bk",
  48423. "bmp",
  48424. "btif",
  48425. "bz2",
  48426. "bzip2",
  48427. "cab",
  48428. "caf",
  48429. "cgm",
  48430. "class",
  48431. "cmx",
  48432. "cpio",
  48433. "cr2",
  48434. "cur",
  48435. "dat",
  48436. "dcm",
  48437. "deb",
  48438. "dex",
  48439. "djvu",
  48440. "dll",
  48441. "dmg",
  48442. "dng",
  48443. "doc",
  48444. "docm",
  48445. "docx",
  48446. "dot",
  48447. "dotm",
  48448. "dra",
  48449. "DS_Store",
  48450. "dsk",
  48451. "dts",
  48452. "dtshd",
  48453. "dvb",
  48454. "dwg",
  48455. "dxf",
  48456. "ecelp4800",
  48457. "ecelp7470",
  48458. "ecelp9600",
  48459. "egg",
  48460. "eol",
  48461. "eot",
  48462. "epub",
  48463. "exe",
  48464. "f4v",
  48465. "fbs",
  48466. "fh",
  48467. "fla",
  48468. "flac",
  48469. "flatpak",
  48470. "fli",
  48471. "flv",
  48472. "fpx",
  48473. "fst",
  48474. "fvt",
  48475. "g3",
  48476. "gh",
  48477. "gif",
  48478. "graffle",
  48479. "gz",
  48480. "gzip",
  48481. "h261",
  48482. "h263",
  48483. "h264",
  48484. "icns",
  48485. "ico",
  48486. "ief",
  48487. "img",
  48488. "ipa",
  48489. "iso",
  48490. "jar",
  48491. "jpeg",
  48492. "jpg",
  48493. "jpgv",
  48494. "jpm",
  48495. "jxr",
  48496. "key",
  48497. "ktx",
  48498. "lha",
  48499. "lib",
  48500. "lvp",
  48501. "lz",
  48502. "lzh",
  48503. "lzma",
  48504. "lzo",
  48505. "m3u",
  48506. "m4a",
  48507. "m4v",
  48508. "mar",
  48509. "mdi",
  48510. "mht",
  48511. "mid",
  48512. "midi",
  48513. "mj2",
  48514. "mka",
  48515. "mkv",
  48516. "mmr",
  48517. "mng",
  48518. "mobi",
  48519. "mov",
  48520. "movie",
  48521. "mp3",
  48522. "mp4",
  48523. "mp4a",
  48524. "mpeg",
  48525. "mpg",
  48526. "mpga",
  48527. "mxu",
  48528. "nef",
  48529. "npx",
  48530. "numbers",
  48531. "nupkg",
  48532. "o",
  48533. "odp",
  48534. "ods",
  48535. "odt",
  48536. "oga",
  48537. "ogg",
  48538. "ogv",
  48539. "otf",
  48540. "ott",
  48541. "pages",
  48542. "pbm",
  48543. "pcx",
  48544. "pdb",
  48545. "pdf",
  48546. "pea",
  48547. "pgm",
  48548. "pic",
  48549. "png",
  48550. "pnm",
  48551. "pot",
  48552. "potm",
  48553. "potx",
  48554. "ppa",
  48555. "ppam",
  48556. "ppm",
  48557. "pps",
  48558. "ppsm",
  48559. "ppsx",
  48560. "ppt",
  48561. "pptm",
  48562. "pptx",
  48563. "psd",
  48564. "pya",
  48565. "pyc",
  48566. "pyo",
  48567. "pyv",
  48568. "qt",
  48569. "rar",
  48570. "ras",
  48571. "raw",
  48572. "resources",
  48573. "rgb",
  48574. "rip",
  48575. "rlc",
  48576. "rmf",
  48577. "rmvb",
  48578. "rpm",
  48579. "rtf",
  48580. "rz",
  48581. "s3m",
  48582. "s7z",
  48583. "scpt",
  48584. "sgi",
  48585. "shar",
  48586. "snap",
  48587. "sil",
  48588. "sketch",
  48589. "slk",
  48590. "smv",
  48591. "snk",
  48592. "so",
  48593. "stl",
  48594. "suo",
  48595. "sub",
  48596. "swf",
  48597. "tar",
  48598. "tbz",
  48599. "tbz2",
  48600. "tga",
  48601. "tgz",
  48602. "thmx",
  48603. "tif",
  48604. "tiff",
  48605. "tlz",
  48606. "ttc",
  48607. "ttf",
  48608. "txz",
  48609. "udf",
  48610. "uvh",
  48611. "uvi",
  48612. "uvm",
  48613. "uvp",
  48614. "uvs",
  48615. "uvu",
  48616. "viv",
  48617. "vob",
  48618. "war",
  48619. "wav",
  48620. "wax",
  48621. "wbmp",
  48622. "wdp",
  48623. "weba",
  48624. "webm",
  48625. "webp",
  48626. "whl",
  48627. "wim",
  48628. "wm",
  48629. "wma",
  48630. "wmv",
  48631. "wmx",
  48632. "woff",
  48633. "woff2",
  48634. "wrm",
  48635. "wvx",
  48636. "xbm",
  48637. "xif",
  48638. "xla",
  48639. "xlam",
  48640. "xls",
  48641. "xlsb",
  48642. "xlsm",
  48643. "xlsx",
  48644. "xlt",
  48645. "xltm",
  48646. "xltx",
  48647. "xm",
  48648. "xmind",
  48649. "xpi",
  48650. "xpm",
  48651. "xwd",
  48652. "xz",
  48653. "z",
  48654. "zip",
  48655. "zipx"
  48656. ];
  48657. var binaryExtensions$1 = require$$0;
  48658. const path$a = path__default;
  48659. const binaryExtensions = binaryExtensions$1;
  48660. const extensions = new Set(binaryExtensions);
  48661. var isBinaryPath$1 = filePath => extensions.has(path$a.extname(filePath).slice(1).toLowerCase());
  48662. var constants$1 = {};
  48663. (function (exports) {
  48664. const {sep} = path__default;
  48665. const {platform} = process;
  48666. const os = require$$0__default$1;
  48667. exports.EV_ALL = 'all';
  48668. exports.EV_READY = 'ready';
  48669. exports.EV_ADD = 'add';
  48670. exports.EV_CHANGE = 'change';
  48671. exports.EV_ADD_DIR = 'addDir';
  48672. exports.EV_UNLINK = 'unlink';
  48673. exports.EV_UNLINK_DIR = 'unlinkDir';
  48674. exports.EV_RAW = 'raw';
  48675. exports.EV_ERROR = 'error';
  48676. exports.STR_DATA = 'data';
  48677. exports.STR_END = 'end';
  48678. exports.STR_CLOSE = 'close';
  48679. exports.FSEVENT_CREATED = 'created';
  48680. exports.FSEVENT_MODIFIED = 'modified';
  48681. exports.FSEVENT_DELETED = 'deleted';
  48682. exports.FSEVENT_MOVED = 'moved';
  48683. exports.FSEVENT_CLONED = 'cloned';
  48684. exports.FSEVENT_UNKNOWN = 'unknown';
  48685. exports.FSEVENT_TYPE_FILE = 'file';
  48686. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  48687. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  48688. exports.KEY_LISTENERS = 'listeners';
  48689. exports.KEY_ERR = 'errHandlers';
  48690. exports.KEY_RAW = 'rawEmitters';
  48691. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  48692. exports.DOT_SLASH = `.${sep}`;
  48693. exports.BACK_SLASH_RE = /\\/g;
  48694. exports.DOUBLE_SLASH_RE = /\/\//;
  48695. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  48696. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  48697. exports.REPLACER_RE = /^\.[/\\]/;
  48698. exports.SLASH = '/';
  48699. exports.SLASH_SLASH = '//';
  48700. exports.BRACE_START = '{';
  48701. exports.BANG = '!';
  48702. exports.ONE_DOT = '.';
  48703. exports.TWO_DOTS = '..';
  48704. exports.STAR = '*';
  48705. exports.GLOBSTAR = '**';
  48706. exports.ROOT_GLOBSTAR = '/**/*';
  48707. exports.SLASH_GLOBSTAR = '/**';
  48708. exports.DIR_SUFFIX = 'Dir';
  48709. exports.ANYMATCH_OPTS = {dot: true};
  48710. exports.STRING_TYPE = 'string';
  48711. exports.FUNCTION_TYPE = 'function';
  48712. exports.EMPTY_STR = '';
  48713. exports.EMPTY_FN = () => {};
  48714. exports.IDENTITY_FN = val => val;
  48715. exports.isWindows = platform === 'win32';
  48716. exports.isMacos = platform === 'darwin';
  48717. exports.isLinux = platform === 'linux';
  48718. exports.isIBMi = os.type() === 'OS400';
  48719. }(constants$1));
  48720. const fs$a = fs__default;
  48721. const sysPath$2 = path__default;
  48722. const { promisify: promisify$3 } = require$$0__default$3;
  48723. const isBinaryPath = isBinaryPath$1;
  48724. const {
  48725. isWindows: isWindows$2,
  48726. isLinux,
  48727. EMPTY_FN: EMPTY_FN$2,
  48728. EMPTY_STR: EMPTY_STR$1,
  48729. KEY_LISTENERS,
  48730. KEY_ERR,
  48731. KEY_RAW,
  48732. HANDLER_KEYS,
  48733. EV_CHANGE: EV_CHANGE$2,
  48734. EV_ADD: EV_ADD$2,
  48735. EV_ADD_DIR: EV_ADD_DIR$2,
  48736. EV_ERROR: EV_ERROR$2,
  48737. STR_DATA: STR_DATA$1,
  48738. STR_END: STR_END$2,
  48739. BRACE_START: BRACE_START$1,
  48740. STAR
  48741. } = constants$1;
  48742. const THROTTLE_MODE_WATCH = 'watch';
  48743. const open$1 = promisify$3(fs$a.open);
  48744. const stat$2 = promisify$3(fs$a.stat);
  48745. const lstat$1 = promisify$3(fs$a.lstat);
  48746. const close = promisify$3(fs$a.close);
  48747. const fsrealpath = promisify$3(fs$a.realpath);
  48748. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  48749. // TODO: emit errors properly. Example: EMFILE on Macos.
  48750. const foreach = (val, fn) => {
  48751. if (val instanceof Set) {
  48752. val.forEach(fn);
  48753. } else {
  48754. fn(val);
  48755. }
  48756. };
  48757. const addAndConvert = (main, prop, item) => {
  48758. let container = main[prop];
  48759. if (!(container instanceof Set)) {
  48760. main[prop] = container = new Set([container]);
  48761. }
  48762. container.add(item);
  48763. };
  48764. const clearItem = cont => key => {
  48765. const set = cont[key];
  48766. if (set instanceof Set) {
  48767. set.clear();
  48768. } else {
  48769. delete cont[key];
  48770. }
  48771. };
  48772. const delFromSet = (main, prop, item) => {
  48773. const container = main[prop];
  48774. if (container instanceof Set) {
  48775. container.delete(item);
  48776. } else if (container === item) {
  48777. delete main[prop];
  48778. }
  48779. };
  48780. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  48781. /**
  48782. * @typedef {String} Path
  48783. */
  48784. // fs_watch helpers
  48785. // object to hold per-process fs_watch instances
  48786. // (may be shared across chokidar FSWatcher instances)
  48787. /**
  48788. * @typedef {Object} FsWatchContainer
  48789. * @property {Set} listeners
  48790. * @property {Set} errHandlers
  48791. * @property {Set} rawEmitters
  48792. * @property {fs.FSWatcher=} watcher
  48793. * @property {Boolean=} watcherUnusable
  48794. */
  48795. /**
  48796. * @type {Map<String,FsWatchContainer>}
  48797. */
  48798. const FsWatchInstances = new Map();
  48799. /**
  48800. * Instantiates the fs_watch interface
  48801. * @param {String} path to be watched
  48802. * @param {Object} options to be passed to fs_watch
  48803. * @param {Function} listener main event handler
  48804. * @param {Function} errHandler emits info about errors
  48805. * @param {Function} emitRaw emits raw event data
  48806. * @returns {fs.FSWatcher} new fsevents instance
  48807. */
  48808. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  48809. const handleEvent = (rawEvent, evPath) => {
  48810. listener(path);
  48811. emitRaw(rawEvent, evPath, {watchedPath: path});
  48812. // emit based on events occurring for files from a directory's watcher in
  48813. // case the file's watcher misses it (and rely on throttling to de-dupe)
  48814. if (evPath && path !== evPath) {
  48815. fsWatchBroadcast(
  48816. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  48817. );
  48818. }
  48819. };
  48820. try {
  48821. return fs$a.watch(path, options, handleEvent);
  48822. } catch (error) {
  48823. errHandler(error);
  48824. }
  48825. }
  48826. /**
  48827. * Helper for passing fs_watch event data to a collection of listeners
  48828. * @param {Path} fullPath absolute path bound to fs_watch instance
  48829. * @param {String} type listener type
  48830. * @param {*=} val1 arguments to be passed to listeners
  48831. * @param {*=} val2
  48832. * @param {*=} val3
  48833. */
  48834. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  48835. const cont = FsWatchInstances.get(fullPath);
  48836. if (!cont) return;
  48837. foreach(cont[type], (listener) => {
  48838. listener(val1, val2, val3);
  48839. });
  48840. };
  48841. /**
  48842. * Instantiates the fs_watch interface or binds listeners
  48843. * to an existing one covering the same file system entry
  48844. * @param {String} path
  48845. * @param {String} fullPath absolute path
  48846. * @param {Object} options to be passed to fs_watch
  48847. * @param {Object} handlers container for event listener functions
  48848. */
  48849. const setFsWatchListener = (path, fullPath, options, handlers) => {
  48850. const {listener, errHandler, rawEmitter} = handlers;
  48851. let cont = FsWatchInstances.get(fullPath);
  48852. /** @type {fs.FSWatcher=} */
  48853. let watcher;
  48854. if (!options.persistent) {
  48855. watcher = createFsWatchInstance(
  48856. path, options, listener, errHandler, rawEmitter
  48857. );
  48858. return watcher.close.bind(watcher);
  48859. }
  48860. if (cont) {
  48861. addAndConvert(cont, KEY_LISTENERS, listener);
  48862. addAndConvert(cont, KEY_ERR, errHandler);
  48863. addAndConvert(cont, KEY_RAW, rawEmitter);
  48864. } else {
  48865. watcher = createFsWatchInstance(
  48866. path,
  48867. options,
  48868. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  48869. errHandler, // no need to use broadcast here
  48870. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  48871. );
  48872. if (!watcher) return;
  48873. watcher.on(EV_ERROR$2, async (error) => {
  48874. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  48875. cont.watcherUnusable = true; // documented since Node 10.4.1
  48876. // Workaround for https://github.com/joyent/node/issues/4337
  48877. if (isWindows$2 && error.code === 'EPERM') {
  48878. try {
  48879. const fd = await open$1(path, 'r');
  48880. await close(fd);
  48881. broadcastErr(error);
  48882. } catch (err) {}
  48883. } else {
  48884. broadcastErr(error);
  48885. }
  48886. });
  48887. cont = {
  48888. listeners: listener,
  48889. errHandlers: errHandler,
  48890. rawEmitters: rawEmitter,
  48891. watcher
  48892. };
  48893. FsWatchInstances.set(fullPath, cont);
  48894. }
  48895. // const index = cont.listeners.indexOf(listener);
  48896. // removes this instance's listeners and closes the underlying fs_watch
  48897. // instance if there are no more listeners left
  48898. return () => {
  48899. delFromSet(cont, KEY_LISTENERS, listener);
  48900. delFromSet(cont, KEY_ERR, errHandler);
  48901. delFromSet(cont, KEY_RAW, rawEmitter);
  48902. if (isEmptySet(cont.listeners)) {
  48903. // Check to protect against issue gh-730.
  48904. // if (cont.watcherUnusable) {
  48905. cont.watcher.close();
  48906. // }
  48907. FsWatchInstances.delete(fullPath);
  48908. HANDLER_KEYS.forEach(clearItem(cont));
  48909. cont.watcher = undefined;
  48910. Object.freeze(cont);
  48911. }
  48912. };
  48913. };
  48914. // fs_watchFile helpers
  48915. // object to hold per-process fs_watchFile instances
  48916. // (may be shared across chokidar FSWatcher instances)
  48917. const FsWatchFileInstances = new Map();
  48918. /**
  48919. * Instantiates the fs_watchFile interface or binds listeners
  48920. * to an existing one covering the same file system entry
  48921. * @param {String} path to be watched
  48922. * @param {String} fullPath absolute path
  48923. * @param {Object} options options to be passed to fs_watchFile
  48924. * @param {Object} handlers container for event listener functions
  48925. * @returns {Function} closer
  48926. */
  48927. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  48928. const {listener, rawEmitter} = handlers;
  48929. let cont = FsWatchFileInstances.get(fullPath);
  48930. const copts = cont && cont.options;
  48931. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  48932. fs$a.unwatchFile(fullPath);
  48933. cont = undefined;
  48934. }
  48935. /* eslint-enable no-unused-vars, prefer-destructuring */
  48936. if (cont) {
  48937. addAndConvert(cont, KEY_LISTENERS, listener);
  48938. addAndConvert(cont, KEY_RAW, rawEmitter);
  48939. } else {
  48940. // TODO
  48941. // listeners.add(listener);
  48942. // rawEmitters.add(rawEmitter);
  48943. cont = {
  48944. listeners: listener,
  48945. rawEmitters: rawEmitter,
  48946. options,
  48947. watcher: fs$a.watchFile(fullPath, options, (curr, prev) => {
  48948. foreach(cont.rawEmitters, (rawEmitter) => {
  48949. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  48950. });
  48951. const currmtime = curr.mtimeMs;
  48952. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  48953. foreach(cont.listeners, (listener) => listener(path, curr));
  48954. }
  48955. })
  48956. };
  48957. FsWatchFileInstances.set(fullPath, cont);
  48958. }
  48959. // const index = cont.listeners.indexOf(listener);
  48960. // Removes this instance's listeners and closes the underlying fs_watchFile
  48961. // instance if there are no more listeners left.
  48962. return () => {
  48963. delFromSet(cont, KEY_LISTENERS, listener);
  48964. delFromSet(cont, KEY_RAW, rawEmitter);
  48965. if (isEmptySet(cont.listeners)) {
  48966. FsWatchFileInstances.delete(fullPath);
  48967. fs$a.unwatchFile(fullPath);
  48968. cont.options = cont.watcher = undefined;
  48969. Object.freeze(cont);
  48970. }
  48971. };
  48972. };
  48973. /**
  48974. * @mixin
  48975. */
  48976. class NodeFsHandler$1 {
  48977. /**
  48978. * @param {import("../index").FSWatcher} fsW
  48979. */
  48980. constructor(fsW) {
  48981. this.fsw = fsW;
  48982. this._boundHandleError = (error) => fsW._handleError(error);
  48983. }
  48984. /**
  48985. * Watch file for changes with fs_watchFile or fs_watch.
  48986. * @param {String} path to file or dir
  48987. * @param {Function} listener on fs change
  48988. * @returns {Function} closer for the watcher instance
  48989. */
  48990. _watchWithNodeFs(path, listener) {
  48991. const opts = this.fsw.options;
  48992. const directory = sysPath$2.dirname(path);
  48993. const basename = sysPath$2.basename(path);
  48994. const parent = this.fsw._getWatchedDir(directory);
  48995. parent.add(basename);
  48996. const absolutePath = sysPath$2.resolve(path);
  48997. const options = {persistent: opts.persistent};
  48998. if (!listener) listener = EMPTY_FN$2;
  48999. let closer;
  49000. if (opts.usePolling) {
  49001. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  49002. opts.binaryInterval : opts.interval;
  49003. closer = setFsWatchFileListener(path, absolutePath, options, {
  49004. listener,
  49005. rawEmitter: this.fsw._emitRaw
  49006. });
  49007. } else {
  49008. closer = setFsWatchListener(path, absolutePath, options, {
  49009. listener,
  49010. errHandler: this._boundHandleError,
  49011. rawEmitter: this.fsw._emitRaw
  49012. });
  49013. }
  49014. return closer;
  49015. }
  49016. /**
  49017. * Watch a file and emit add event if warranted.
  49018. * @param {Path} file Path
  49019. * @param {fs.Stats} stats result of fs_stat
  49020. * @param {Boolean} initialAdd was the file added at watch instantiation?
  49021. * @returns {Function} closer for the watcher instance
  49022. */
  49023. _handleFile(file, stats, initialAdd) {
  49024. if (this.fsw.closed) {
  49025. return;
  49026. }
  49027. const dirname = sysPath$2.dirname(file);
  49028. const basename = sysPath$2.basename(file);
  49029. const parent = this.fsw._getWatchedDir(dirname);
  49030. // stats is always present
  49031. let prevStats = stats;
  49032. // if the file is already being watched, do nothing
  49033. if (parent.has(basename)) return;
  49034. const listener = async (path, newStats) => {
  49035. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  49036. if (!newStats || newStats.mtimeMs === 0) {
  49037. try {
  49038. const newStats = await stat$2(file);
  49039. if (this.fsw.closed) return;
  49040. // Check that change event was not fired because of changed only accessTime.
  49041. const at = newStats.atimeMs;
  49042. const mt = newStats.mtimeMs;
  49043. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  49044. this.fsw._emit(EV_CHANGE$2, file, newStats);
  49045. }
  49046. if (isLinux && prevStats.ino !== newStats.ino) {
  49047. this.fsw._closeFile(path);
  49048. prevStats = newStats;
  49049. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  49050. } else {
  49051. prevStats = newStats;
  49052. }
  49053. } catch (error) {
  49054. // Fix issues where mtime is null but file is still present
  49055. this.fsw._remove(dirname, basename);
  49056. }
  49057. // add is about to be emitted if file not already tracked in parent
  49058. } else if (parent.has(basename)) {
  49059. // Check that change event was not fired because of changed only accessTime.
  49060. const at = newStats.atimeMs;
  49061. const mt = newStats.mtimeMs;
  49062. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  49063. this.fsw._emit(EV_CHANGE$2, file, newStats);
  49064. }
  49065. prevStats = newStats;
  49066. }
  49067. };
  49068. // kick off the watcher
  49069. const closer = this._watchWithNodeFs(file, listener);
  49070. // emit an add event if we're supposed to
  49071. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  49072. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  49073. this.fsw._emit(EV_ADD$2, file, stats);
  49074. }
  49075. return closer;
  49076. }
  49077. /**
  49078. * Handle symlinks encountered while reading a dir.
  49079. * @param {Object} entry returned by readdirp
  49080. * @param {String} directory path of dir being read
  49081. * @param {String} path of this item
  49082. * @param {String} item basename of this item
  49083. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  49084. */
  49085. async _handleSymlink(entry, directory, path, item) {
  49086. if (this.fsw.closed) {
  49087. return;
  49088. }
  49089. const full = entry.fullPath;
  49090. const dir = this.fsw._getWatchedDir(directory);
  49091. if (!this.fsw.options.followSymlinks) {
  49092. // watch symlink directly (don't follow) and detect changes
  49093. this.fsw._incrReadyCount();
  49094. const linkPath = await fsrealpath(path);
  49095. if (this.fsw.closed) return;
  49096. if (dir.has(item)) {
  49097. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  49098. this.fsw._symlinkPaths.set(full, linkPath);
  49099. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  49100. }
  49101. } else {
  49102. dir.add(item);
  49103. this.fsw._symlinkPaths.set(full, linkPath);
  49104. this.fsw._emit(EV_ADD$2, path, entry.stats);
  49105. }
  49106. this.fsw._emitReady();
  49107. return true;
  49108. }
  49109. // don't follow the same symlink more than once
  49110. if (this.fsw._symlinkPaths.has(full)) {
  49111. return true;
  49112. }
  49113. this.fsw._symlinkPaths.set(full, true);
  49114. }
  49115. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  49116. // Normalize the directory name on Windows
  49117. directory = sysPath$2.join(directory, EMPTY_STR$1);
  49118. if (!wh.hasGlob) {
  49119. throttler = this.fsw._throttle('readdir', directory, 1000);
  49120. if (!throttler) return;
  49121. }
  49122. const previous = this.fsw._getWatchedDir(wh.path);
  49123. const current = new Set();
  49124. let stream = this.fsw._readdirp(directory, {
  49125. fileFilter: entry => wh.filterPath(entry),
  49126. directoryFilter: entry => wh.filterDir(entry),
  49127. depth: 0
  49128. }).on(STR_DATA$1, async (entry) => {
  49129. if (this.fsw.closed) {
  49130. stream = undefined;
  49131. return;
  49132. }
  49133. const item = entry.path;
  49134. let path = sysPath$2.join(directory, item);
  49135. current.add(item);
  49136. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  49137. return;
  49138. }
  49139. if (this.fsw.closed) {
  49140. stream = undefined;
  49141. return;
  49142. }
  49143. // Files that present in current directory snapshot
  49144. // but absent in previous are added to watch list and
  49145. // emit `add` event.
  49146. if (item === target || !target && !previous.has(item)) {
  49147. this.fsw._incrReadyCount();
  49148. // ensure relativeness of path is preserved in case of watcher reuse
  49149. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  49150. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  49151. }
  49152. }).on(EV_ERROR$2, this._boundHandleError);
  49153. return new Promise(resolve =>
  49154. stream.once(STR_END$2, () => {
  49155. if (this.fsw.closed) {
  49156. stream = undefined;
  49157. return;
  49158. }
  49159. const wasThrottled = throttler ? throttler.clear() : false;
  49160. resolve();
  49161. // Files that absent in current directory snapshot
  49162. // but present in previous emit `remove` event
  49163. // and are removed from @watched[directory].
  49164. previous.getChildren().filter((item) => {
  49165. return item !== directory &&
  49166. !current.has(item) &&
  49167. // in case of intersecting globs;
  49168. // a path may have been filtered out of this readdir, but
  49169. // shouldn't be removed because it matches a different glob
  49170. (!wh.hasGlob || wh.filterPath({
  49171. fullPath: sysPath$2.resolve(directory, item)
  49172. }));
  49173. }).forEach((item) => {
  49174. this.fsw._remove(directory, item);
  49175. });
  49176. stream = undefined;
  49177. // one more time for any missed in case changes came in extremely quickly
  49178. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  49179. })
  49180. );
  49181. }
  49182. /**
  49183. * Read directory to add / remove files from `@watched` list and re-read it on change.
  49184. * @param {String} dir fs path
  49185. * @param {fs.Stats} stats
  49186. * @param {Boolean} initialAdd
  49187. * @param {Number} depth relative to user-supplied path
  49188. * @param {String} target child path targeted for watch
  49189. * @param {Object} wh Common watch helpers for this path
  49190. * @param {String} realpath
  49191. * @returns {Promise<Function>} closer for the watcher instance.
  49192. */
  49193. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  49194. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  49195. const tracked = parentDir.has(sysPath$2.basename(dir));
  49196. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  49197. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  49198. }
  49199. // ensure dir is tracked (harmless if redundant)
  49200. parentDir.add(sysPath$2.basename(dir));
  49201. this.fsw._getWatchedDir(dir);
  49202. let throttler;
  49203. let closer;
  49204. const oDepth = this.fsw.options.depth;
  49205. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  49206. if (!target) {
  49207. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  49208. if (this.fsw.closed) return;
  49209. }
  49210. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  49211. // if current directory is removed, do nothing
  49212. if (stats && stats.mtimeMs === 0) return;
  49213. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  49214. });
  49215. }
  49216. return closer;
  49217. }
  49218. /**
  49219. * Handle added file, directory, or glob pattern.
  49220. * Delegates call to _handleFile / _handleDir after checks.
  49221. * @param {String} path to file or ir
  49222. * @param {Boolean} initialAdd was the file added at watch instantiation?
  49223. * @param {Object} priorWh depth relative to user-supplied path
  49224. * @param {Number} depth Child path actually targeted for watch
  49225. * @param {String=} target Child path actually targeted for watch
  49226. * @returns {Promise}
  49227. */
  49228. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  49229. const ready = this.fsw._emitReady;
  49230. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  49231. ready();
  49232. return false;
  49233. }
  49234. const wh = this.fsw._getWatchHelpers(path, depth);
  49235. if (!wh.hasGlob && priorWh) {
  49236. wh.hasGlob = priorWh.hasGlob;
  49237. wh.globFilter = priorWh.globFilter;
  49238. wh.filterPath = entry => priorWh.filterPath(entry);
  49239. wh.filterDir = entry => priorWh.filterDir(entry);
  49240. }
  49241. // evaluate what is at the path we're being asked to watch
  49242. try {
  49243. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  49244. if (this.fsw.closed) return;
  49245. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  49246. ready();
  49247. return false;
  49248. }
  49249. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  49250. let closer;
  49251. if (stats.isDirectory()) {
  49252. const absPath = sysPath$2.resolve(path);
  49253. const targetPath = follow ? await fsrealpath(path) : path;
  49254. if (this.fsw.closed) return;
  49255. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  49256. if (this.fsw.closed) return;
  49257. // preserve this symlink's target path
  49258. if (absPath !== targetPath && targetPath !== undefined) {
  49259. this.fsw._symlinkPaths.set(absPath, targetPath);
  49260. }
  49261. } else if (stats.isSymbolicLink()) {
  49262. const targetPath = follow ? await fsrealpath(path) : path;
  49263. if (this.fsw.closed) return;
  49264. const parent = sysPath$2.dirname(wh.watchPath);
  49265. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  49266. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  49267. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  49268. if (this.fsw.closed) return;
  49269. // preserve this symlink's target path
  49270. if (targetPath !== undefined) {
  49271. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  49272. }
  49273. } else {
  49274. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  49275. }
  49276. ready();
  49277. this.fsw._addPathCloser(path, closer);
  49278. return false;
  49279. } catch (error) {
  49280. if (this.fsw._handleError(error)) {
  49281. ready();
  49282. return path;
  49283. }
  49284. }
  49285. }
  49286. }
  49287. var nodefsHandler = NodeFsHandler$1;
  49288. var fseventsHandler = {exports: {}};
  49289. const fs$9 = fs__default;
  49290. const sysPath$1 = path__default;
  49291. const { promisify: promisify$2 } = require$$0__default$3;
  49292. let fsevents;
  49293. try {
  49294. fsevents = eval('require')('fsevents');
  49295. } catch (error) {
  49296. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  49297. }
  49298. if (fsevents) {
  49299. // TODO: real check
  49300. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  49301. if (mtch && mtch[1] && mtch[2]) {
  49302. const maj = Number.parseInt(mtch[1], 10);
  49303. const min = Number.parseInt(mtch[2], 10);
  49304. if (maj === 8 && min < 16) {
  49305. fsevents = undefined;
  49306. }
  49307. }
  49308. }
  49309. const {
  49310. EV_ADD: EV_ADD$1,
  49311. EV_CHANGE: EV_CHANGE$1,
  49312. EV_ADD_DIR: EV_ADD_DIR$1,
  49313. EV_UNLINK: EV_UNLINK$1,
  49314. EV_ERROR: EV_ERROR$1,
  49315. STR_DATA,
  49316. STR_END: STR_END$1,
  49317. FSEVENT_CREATED,
  49318. FSEVENT_MODIFIED,
  49319. FSEVENT_DELETED,
  49320. FSEVENT_MOVED,
  49321. // FSEVENT_CLONED,
  49322. FSEVENT_UNKNOWN,
  49323. FSEVENT_TYPE_FILE,
  49324. FSEVENT_TYPE_DIRECTORY,
  49325. FSEVENT_TYPE_SYMLINK,
  49326. ROOT_GLOBSTAR,
  49327. DIR_SUFFIX,
  49328. DOT_SLASH,
  49329. FUNCTION_TYPE: FUNCTION_TYPE$1,
  49330. EMPTY_FN: EMPTY_FN$1,
  49331. IDENTITY_FN
  49332. } = constants$1;
  49333. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  49334. const stat$1 = promisify$2(fs$9.stat);
  49335. const lstat = promisify$2(fs$9.lstat);
  49336. const realpath = promisify$2(fs$9.realpath);
  49337. const statMethods = { stat: stat$1, lstat };
  49338. /**
  49339. * @typedef {String} Path
  49340. */
  49341. /**
  49342. * @typedef {Object} FsEventsWatchContainer
  49343. * @property {Set<Function>} listeners
  49344. * @property {Function} rawEmitter
  49345. * @property {{stop: Function}} watcher
  49346. */
  49347. // fsevents instance helper functions
  49348. /**
  49349. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  49350. * @type {Map<Path,FsEventsWatchContainer>}
  49351. */
  49352. const FSEventsWatchers = new Map();
  49353. // Threshold of duplicate path prefixes at which to start
  49354. // consolidating going forward
  49355. const consolidateThreshhold = 10;
  49356. const wrongEventFlags = new Set([
  49357. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  49358. ]);
  49359. /**
  49360. * Instantiates the fsevents interface
  49361. * @param {Path} path path to be watched
  49362. * @param {Function} callback called when fsevents is bound and ready
  49363. * @returns {{stop: Function}} new fsevents instance
  49364. */
  49365. const createFSEventsInstance = (path, callback) => {
  49366. const stop = fsevents.watch(path, callback);
  49367. return {stop};
  49368. };
  49369. /**
  49370. * Instantiates the fsevents interface or binds listeners to an existing one covering
  49371. * the same file tree.
  49372. * @param {Path} path - to be watched
  49373. * @param {Path} realPath - real path for symlinks
  49374. * @param {Function} listener - called when fsevents emits events
  49375. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  49376. * @returns {Function} closer
  49377. */
  49378. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  49379. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  49380. const parentPath = sysPath$1.dirname(watchPath);
  49381. let cont = FSEventsWatchers.get(watchPath);
  49382. // If we've accumulated a substantial number of paths that
  49383. // could have been consolidated by watching one directory
  49384. // above the current one, create a watcher on the parent
  49385. // path instead, so that we do consolidate going forward.
  49386. if (couldConsolidate(parentPath)) {
  49387. watchPath = parentPath;
  49388. }
  49389. const resolvedPath = sysPath$1.resolve(path);
  49390. const hasSymlink = resolvedPath !== realPath;
  49391. const filteredListener = (fullPath, flags, info) => {
  49392. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  49393. if (
  49394. fullPath === resolvedPath ||
  49395. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  49396. ) listener(fullPath, flags, info);
  49397. };
  49398. // check if there is already a watcher on a parent path
  49399. // modifies `watchPath` to the parent path when it finds a match
  49400. let watchedParent = false;
  49401. for (const watchedPath of FSEventsWatchers.keys()) {
  49402. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  49403. watchPath = watchedPath;
  49404. cont = FSEventsWatchers.get(watchPath);
  49405. watchedParent = true;
  49406. break;
  49407. }
  49408. }
  49409. if (cont || watchedParent) {
  49410. cont.listeners.add(filteredListener);
  49411. } else {
  49412. cont = {
  49413. listeners: new Set([filteredListener]),
  49414. rawEmitter,
  49415. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  49416. if (!cont.listeners.size) return;
  49417. const info = fsevents.getInfo(fullPath, flags);
  49418. cont.listeners.forEach(list => {
  49419. list(fullPath, flags, info);
  49420. });
  49421. cont.rawEmitter(info.event, fullPath, info);
  49422. })
  49423. };
  49424. FSEventsWatchers.set(watchPath, cont);
  49425. }
  49426. // removes this instance's listeners and closes the underlying fsevents
  49427. // instance if there are no more listeners left
  49428. return () => {
  49429. const lst = cont.listeners;
  49430. lst.delete(filteredListener);
  49431. if (!lst.size) {
  49432. FSEventsWatchers.delete(watchPath);
  49433. if (cont.watcher) return cont.watcher.stop().then(() => {
  49434. cont.rawEmitter = cont.watcher = undefined;
  49435. Object.freeze(cont);
  49436. });
  49437. }
  49438. };
  49439. }
  49440. // Decide whether or not we should start a new higher-level
  49441. // parent watcher
  49442. const couldConsolidate = (path) => {
  49443. let count = 0;
  49444. for (const watchPath of FSEventsWatchers.keys()) {
  49445. if (watchPath.indexOf(path) === 0) {
  49446. count++;
  49447. if (count >= consolidateThreshhold) {
  49448. return true;
  49449. }
  49450. }
  49451. }
  49452. return false;
  49453. };
  49454. // returns boolean indicating whether fsevents can be used
  49455. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  49456. // determines subdirectory traversal levels from root to path
  49457. const calcDepth = (path, root) => {
  49458. let i = 0;
  49459. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  49460. return i;
  49461. };
  49462. // returns boolean indicating whether the fsevents' event info has the same type
  49463. // as the one returned by fs.stat
  49464. const sameTypes = (info, stats) => (
  49465. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  49466. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  49467. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  49468. );
  49469. /**
  49470. * @mixin
  49471. */
  49472. class FsEventsHandler$1 {
  49473. /**
  49474. * @param {import('../index').FSWatcher} fsw
  49475. */
  49476. constructor(fsw) {
  49477. this.fsw = fsw;
  49478. }
  49479. checkIgnored(path, stats) {
  49480. const ipaths = this.fsw._ignoredPaths;
  49481. if (this.fsw._isIgnored(path, stats)) {
  49482. ipaths.add(path);
  49483. if (stats && stats.isDirectory()) {
  49484. ipaths.add(path + ROOT_GLOBSTAR);
  49485. }
  49486. return true;
  49487. }
  49488. ipaths.delete(path);
  49489. ipaths.delete(path + ROOT_GLOBSTAR);
  49490. }
  49491. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  49492. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  49493. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49494. }
  49495. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  49496. try {
  49497. const stats = await stat$1(path);
  49498. if (this.fsw.closed) return;
  49499. if (sameTypes(info, stats)) {
  49500. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49501. } else {
  49502. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49503. }
  49504. } catch (error) {
  49505. if (error.code === 'EACCES') {
  49506. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49507. } else {
  49508. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49509. }
  49510. }
  49511. }
  49512. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  49513. if (this.fsw.closed || this.checkIgnored(path)) return;
  49514. if (event === EV_UNLINK$1) {
  49515. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  49516. // suppress unlink events on never before seen files
  49517. if (isDirectory || watchedDir.has(item)) {
  49518. this.fsw._remove(parent, item, isDirectory);
  49519. }
  49520. } else {
  49521. if (event === EV_ADD$1) {
  49522. // track new directories
  49523. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  49524. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  49525. // push symlinks back to the top of the stack to get handled
  49526. const curDepth = opts.depth === undefined ?
  49527. undefined : calcDepth(fullPath, realPath) + 1;
  49528. return this._addToFsEvents(path, false, true, curDepth);
  49529. }
  49530. // track new paths
  49531. // (other than symlinks being followed, which will be tracked soon)
  49532. this.fsw._getWatchedDir(parent).add(item);
  49533. }
  49534. /**
  49535. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  49536. */
  49537. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  49538. this.fsw._emit(eventName, path);
  49539. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  49540. }
  49541. }
  49542. /**
  49543. * Handle symlinks encountered during directory scan
  49544. * @param {String} watchPath - file/dir path to be watched with fsevents
  49545. * @param {String} realPath - real path (in case of symlinks)
  49546. * @param {Function} transform - path transformer
  49547. * @param {Function} globFilter - path filter in case a glob pattern was provided
  49548. * @returns {Function} closer for the watcher instance
  49549. */
  49550. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  49551. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  49552. const opts = this.fsw.options;
  49553. const watchCallback = async (fullPath, flags, info) => {
  49554. if (this.fsw.closed) return;
  49555. if (
  49556. opts.depth !== undefined &&
  49557. calcDepth(fullPath, realPath) > opts.depth
  49558. ) return;
  49559. const path = transform(sysPath$1.join(
  49560. watchPath, sysPath$1.relative(watchPath, fullPath)
  49561. ));
  49562. if (globFilter && !globFilter(path)) return;
  49563. // ensure directories are tracked
  49564. const parent = sysPath$1.dirname(path);
  49565. const item = sysPath$1.basename(path);
  49566. const watchedDir = this.fsw._getWatchedDir(
  49567. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  49568. );
  49569. // correct for wrong events emitted
  49570. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  49571. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  49572. let stats;
  49573. try {
  49574. stats = await stat$1(path);
  49575. } catch (error) {}
  49576. if (this.fsw.closed) return;
  49577. if (this.checkIgnored(path, stats)) return;
  49578. if (sameTypes(info, stats)) {
  49579. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49580. } else {
  49581. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49582. }
  49583. } else {
  49584. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49585. }
  49586. } else {
  49587. switch (info.event) {
  49588. case FSEVENT_CREATED:
  49589. case FSEVENT_MODIFIED:
  49590. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49591. case FSEVENT_DELETED:
  49592. case FSEVENT_MOVED:
  49593. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  49594. }
  49595. }
  49596. };
  49597. const closer = setFSEventsListener(
  49598. watchPath,
  49599. realPath,
  49600. watchCallback,
  49601. this.fsw._emitRaw
  49602. );
  49603. this.fsw._emitReady();
  49604. return closer;
  49605. }
  49606. /**
  49607. * Handle symlinks encountered during directory scan
  49608. * @param {String} linkPath path to symlink
  49609. * @param {String} fullPath absolute path to the symlink
  49610. * @param {Function} transform pre-existing path transformer
  49611. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  49612. * @returns {Promise<void>}
  49613. */
  49614. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  49615. // don't follow the same symlink more than once
  49616. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  49617. this.fsw._symlinkPaths.set(fullPath, true);
  49618. this.fsw._incrReadyCount();
  49619. try {
  49620. const linkTarget = await realpath(linkPath);
  49621. if (this.fsw.closed) return;
  49622. if (this.fsw._isIgnored(linkTarget)) {
  49623. return this.fsw._emitReady();
  49624. }
  49625. this.fsw._incrReadyCount();
  49626. // add the linkTarget for watching with a wrapper for transform
  49627. // that causes emitted paths to incorporate the link's path
  49628. this._addToFsEvents(linkTarget || linkPath, (path) => {
  49629. let aliasedPath = linkPath;
  49630. if (linkTarget && linkTarget !== DOT_SLASH) {
  49631. aliasedPath = path.replace(linkTarget, linkPath);
  49632. } else if (path !== DOT_SLASH) {
  49633. aliasedPath = sysPath$1.join(linkPath, path);
  49634. }
  49635. return transform(aliasedPath);
  49636. }, false, curDepth);
  49637. } catch(error) {
  49638. if (this.fsw._handleError(error)) {
  49639. return this.fsw._emitReady();
  49640. }
  49641. }
  49642. }
  49643. /**
  49644. *
  49645. * @param {Path} newPath
  49646. * @param {fs.Stats} stats
  49647. */
  49648. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  49649. const pp = processPath(newPath);
  49650. const isDir = stats.isDirectory();
  49651. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  49652. const base = sysPath$1.basename(pp);
  49653. // ensure empty dirs get tracked
  49654. if (isDir) this.fsw._getWatchedDir(pp);
  49655. if (dirObj.has(base)) return;
  49656. dirObj.add(base);
  49657. if (!opts.ignoreInitial || forceAdd === true) {
  49658. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  49659. }
  49660. }
  49661. initWatch(realPath, path, wh, processPath) {
  49662. if (this.fsw.closed) return;
  49663. const closer = this._watchWithFsEvents(
  49664. wh.watchPath,
  49665. sysPath$1.resolve(realPath || wh.watchPath),
  49666. processPath,
  49667. wh.globFilter
  49668. );
  49669. this.fsw._addPathCloser(path, closer);
  49670. }
  49671. /**
  49672. * Handle added path with fsevents
  49673. * @param {String} path file/dir path or glob pattern
  49674. * @param {Function|Boolean=} transform converts working path to what the user expects
  49675. * @param {Boolean=} forceAdd ensure add is emitted
  49676. * @param {Number=} priorDepth Level of subdirectories already traversed.
  49677. * @returns {Promise<void>}
  49678. */
  49679. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  49680. if (this.fsw.closed) {
  49681. return;
  49682. }
  49683. const opts = this.fsw.options;
  49684. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  49685. const wh = this.fsw._getWatchHelpers(path);
  49686. // evaluate what is at the path we're being asked to watch
  49687. try {
  49688. const stats = await statMethods[wh.statMethod](wh.watchPath);
  49689. if (this.fsw.closed) return;
  49690. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  49691. throw null;
  49692. }
  49693. if (stats.isDirectory()) {
  49694. // emit addDir unless this is a glob parent
  49695. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  49696. // don't recurse further if it would exceed depth setting
  49697. if (priorDepth && priorDepth > opts.depth) return;
  49698. // scan the contents of the dir
  49699. this.fsw._readdirp(wh.watchPath, {
  49700. fileFilter: entry => wh.filterPath(entry),
  49701. directoryFilter: entry => wh.filterDir(entry),
  49702. ...Depth(opts.depth - (priorDepth || 0))
  49703. }).on(STR_DATA, (entry) => {
  49704. // need to check filterPath on dirs b/c filterDir is less restrictive
  49705. if (this.fsw.closed) {
  49706. return;
  49707. }
  49708. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  49709. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  49710. const {fullPath} = entry;
  49711. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  49712. // preserve the current depth here since it can't be derived from
  49713. // real paths past the symlink
  49714. const curDepth = opts.depth === undefined ?
  49715. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  49716. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  49717. } else {
  49718. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  49719. }
  49720. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  49721. this.fsw._emitReady();
  49722. });
  49723. } else {
  49724. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  49725. this.fsw._emitReady();
  49726. }
  49727. } catch (error) {
  49728. if (!error || this.fsw._handleError(error)) {
  49729. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  49730. this.fsw._emitReady();
  49731. this.fsw._emitReady();
  49732. }
  49733. }
  49734. if (opts.persistent && forceAdd !== true) {
  49735. if (typeof transform === FUNCTION_TYPE$1) {
  49736. // realpath has already been resolved
  49737. this.initWatch(undefined, path, wh, processPath);
  49738. } else {
  49739. let realPath;
  49740. try {
  49741. realPath = await realpath(wh.watchPath);
  49742. } catch (e) {}
  49743. this.initWatch(realPath, path, wh, processPath);
  49744. }
  49745. }
  49746. }
  49747. }
  49748. fseventsHandler.exports = FsEventsHandler$1;
  49749. fseventsHandler.exports.canUse = canUse;
  49750. const { EventEmitter: EventEmitter$2 } = require$$0__default$6;
  49751. const fs$8 = fs__default;
  49752. const sysPath = path__default;
  49753. const { promisify: promisify$1 } = require$$0__default$3;
  49754. const readdirp = readdirp_1;
  49755. const anymatch = anymatch$2.exports.default;
  49756. const globParent = globParent$2;
  49757. const isGlob = isGlob$2;
  49758. const braces = braces_1;
  49759. const normalizePath = normalizePath$2;
  49760. const NodeFsHandler = nodefsHandler;
  49761. const FsEventsHandler = fseventsHandler.exports;
  49762. const {
  49763. EV_ALL,
  49764. EV_READY,
  49765. EV_ADD,
  49766. EV_CHANGE,
  49767. EV_UNLINK,
  49768. EV_ADD_DIR,
  49769. EV_UNLINK_DIR,
  49770. EV_RAW,
  49771. EV_ERROR,
  49772. STR_CLOSE,
  49773. STR_END,
  49774. BACK_SLASH_RE,
  49775. DOUBLE_SLASH_RE,
  49776. SLASH_OR_BACK_SLASH_RE,
  49777. DOT_RE,
  49778. REPLACER_RE,
  49779. SLASH,
  49780. SLASH_SLASH,
  49781. BRACE_START,
  49782. BANG,
  49783. ONE_DOT,
  49784. TWO_DOTS,
  49785. GLOBSTAR,
  49786. SLASH_GLOBSTAR,
  49787. ANYMATCH_OPTS,
  49788. STRING_TYPE,
  49789. FUNCTION_TYPE,
  49790. EMPTY_STR,
  49791. EMPTY_FN,
  49792. isWindows: isWindows$1,
  49793. isMacos,
  49794. isIBMi
  49795. } = constants$1;
  49796. const stat = promisify$1(fs$8.stat);
  49797. const readdir = promisify$1(fs$8.readdir);
  49798. /**
  49799. * @typedef {String} Path
  49800. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  49801. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  49802. */
  49803. /**
  49804. *
  49805. * @typedef {Object} WatchHelpers
  49806. * @property {Boolean} followSymlinks
  49807. * @property {'stat'|'lstat'} statMethod
  49808. * @property {Path} path
  49809. * @property {Path} watchPath
  49810. * @property {Function} entryPath
  49811. * @property {Boolean} hasGlob
  49812. * @property {Object} globFilter
  49813. * @property {Function} filterPath
  49814. * @property {Function} filterDir
  49815. */
  49816. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  49817. const flatten = (list, result = []) => {
  49818. list.forEach(item => {
  49819. if (Array.isArray(item)) {
  49820. flatten(item, result);
  49821. } else {
  49822. result.push(item);
  49823. }
  49824. });
  49825. return result;
  49826. };
  49827. const unifyPaths = (paths_) => {
  49828. /**
  49829. * @type {Array<String>}
  49830. */
  49831. const paths = flatten(arrify(paths_));
  49832. if (!paths.every(p => typeof p === STRING_TYPE)) {
  49833. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  49834. }
  49835. return paths.map(normalizePathToUnix);
  49836. };
  49837. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  49838. // because "//StoragePC/DrivePool/Movies" is a valid network path
  49839. const toUnix = (string) => {
  49840. let str = string.replace(BACK_SLASH_RE, SLASH);
  49841. let prepend = false;
  49842. if (str.startsWith(SLASH_SLASH)) {
  49843. prepend = true;
  49844. }
  49845. while (str.match(DOUBLE_SLASH_RE)) {
  49846. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  49847. }
  49848. if (prepend) {
  49849. str = SLASH + str;
  49850. }
  49851. return str;
  49852. };
  49853. // Our version of upath.normalize
  49854. // TODO: this is not equal to path-normalize module - investigate why
  49855. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  49856. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  49857. if (typeof path !== STRING_TYPE) return path;
  49858. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  49859. };
  49860. const getAbsolutePath = (path, cwd) => {
  49861. if (sysPath.isAbsolute(path)) {
  49862. return path;
  49863. }
  49864. if (path.startsWith(BANG)) {
  49865. return BANG + sysPath.join(cwd, path.slice(1));
  49866. }
  49867. return sysPath.join(cwd, path);
  49868. };
  49869. const undef = (opts, key) => opts[key] === undefined;
  49870. /**
  49871. * Directory entry.
  49872. * @property {Path} path
  49873. * @property {Set<Path>} items
  49874. */
  49875. class DirEntry {
  49876. /**
  49877. * @param {Path} dir
  49878. * @param {Function} removeWatcher
  49879. */
  49880. constructor(dir, removeWatcher) {
  49881. this.path = dir;
  49882. this._removeWatcher = removeWatcher;
  49883. /** @type {Set<Path>} */
  49884. this.items = new Set();
  49885. }
  49886. add(item) {
  49887. const {items} = this;
  49888. if (!items) return;
  49889. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  49890. }
  49891. async remove(item) {
  49892. const {items} = this;
  49893. if (!items) return;
  49894. items.delete(item);
  49895. if (items.size > 0) return;
  49896. const dir = this.path;
  49897. try {
  49898. await readdir(dir);
  49899. } catch (err) {
  49900. if (this._removeWatcher) {
  49901. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  49902. }
  49903. }
  49904. }
  49905. has(item) {
  49906. const {items} = this;
  49907. if (!items) return;
  49908. return items.has(item);
  49909. }
  49910. /**
  49911. * @returns {Array<String>}
  49912. */
  49913. getChildren() {
  49914. const {items} = this;
  49915. if (!items) return;
  49916. return [...items.values()];
  49917. }
  49918. dispose() {
  49919. this.items.clear();
  49920. delete this.path;
  49921. delete this._removeWatcher;
  49922. delete this.items;
  49923. Object.freeze(this);
  49924. }
  49925. }
  49926. const STAT_METHOD_F = 'stat';
  49927. const STAT_METHOD_L = 'lstat';
  49928. class WatchHelper {
  49929. constructor(path, watchPath, follow, fsw) {
  49930. this.fsw = fsw;
  49931. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  49932. this.watchPath = watchPath;
  49933. this.fullWatchPath = sysPath.resolve(watchPath);
  49934. this.hasGlob = watchPath !== path;
  49935. /** @type {object|boolean} */
  49936. if (path === EMPTY_STR) this.hasGlob = false;
  49937. this.globSymlink = this.hasGlob && follow ? undefined : false;
  49938. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  49939. this.dirParts = this.getDirParts(path);
  49940. this.dirParts.forEach((parts) => {
  49941. if (parts.length > 1) parts.pop();
  49942. });
  49943. this.followSymlinks = follow;
  49944. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  49945. }
  49946. checkGlobSymlink(entry) {
  49947. // only need to resolve once
  49948. // first entry should always have entry.parentDir === EMPTY_STR
  49949. if (this.globSymlink === undefined) {
  49950. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  49951. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  49952. }
  49953. if (this.globSymlink) {
  49954. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  49955. }
  49956. return entry.fullPath;
  49957. }
  49958. entryPath(entry) {
  49959. return sysPath.join(this.watchPath,
  49960. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  49961. );
  49962. }
  49963. filterPath(entry) {
  49964. const {stats} = entry;
  49965. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  49966. const resolvedPath = this.entryPath(entry);
  49967. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  49968. this.globFilter(resolvedPath) : true;
  49969. return matchesGlob &&
  49970. this.fsw._isntIgnored(resolvedPath, stats) &&
  49971. this.fsw._hasReadPermissions(stats);
  49972. }
  49973. getDirParts(path) {
  49974. if (!this.hasGlob) return [];
  49975. const parts = [];
  49976. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  49977. expandedPath.forEach((path) => {
  49978. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  49979. });
  49980. return parts;
  49981. }
  49982. filterDir(entry) {
  49983. if (this.hasGlob) {
  49984. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  49985. let globstar = false;
  49986. this.unmatchedGlob = !this.dirParts.some((parts) => {
  49987. return parts.every((part, i) => {
  49988. if (part === GLOBSTAR) globstar = true;
  49989. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  49990. });
  49991. });
  49992. }
  49993. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  49994. }
  49995. }
  49996. /**
  49997. * Watches files & directories for changes. Emitted events:
  49998. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  49999. *
  50000. * new FSWatcher()
  50001. * .add(directories)
  50002. * .on('add', path => log('File', path, 'was added'))
  50003. */
  50004. class FSWatcher extends EventEmitter$2 {
  50005. // Not indenting methods for history sake; for now.
  50006. constructor(_opts) {
  50007. super();
  50008. const opts = {};
  50009. if (_opts) Object.assign(opts, _opts); // for frozen objects
  50010. /** @type {Map<String, DirEntry>} */
  50011. this._watched = new Map();
  50012. /** @type {Map<String, Array>} */
  50013. this._closers = new Map();
  50014. /** @type {Set<String>} */
  50015. this._ignoredPaths = new Set();
  50016. /** @type {Map<ThrottleType, Map>} */
  50017. this._throttled = new Map();
  50018. /** @type {Map<Path, String|Boolean>} */
  50019. this._symlinkPaths = new Map();
  50020. this._streams = new Set();
  50021. this.closed = false;
  50022. // Set up default options.
  50023. if (undef(opts, 'persistent')) opts.persistent = true;
  50024. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  50025. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  50026. if (undef(opts, 'interval')) opts.interval = 100;
  50027. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  50028. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  50029. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  50030. // Enable fsevents on OS X when polling isn't explicitly enabled.
  50031. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  50032. // If we can't use fsevents, ensure the options reflect it's disabled.
  50033. const canUseFsEvents = FsEventsHandler.canUse();
  50034. if (!canUseFsEvents) opts.useFsEvents = false;
  50035. // Use polling on Mac if not using fsevents.
  50036. // Other platforms use non-polling fs_watch.
  50037. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  50038. opts.usePolling = isMacos;
  50039. }
  50040. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  50041. if(isIBMi) {
  50042. opts.usePolling = true;
  50043. }
  50044. // Global override (useful for end-developers that need to force polling for all
  50045. // instances of chokidar, regardless of usage/dependency depth)
  50046. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  50047. if (envPoll !== undefined) {
  50048. const envLower = envPoll.toLowerCase();
  50049. if (envLower === 'false' || envLower === '0') {
  50050. opts.usePolling = false;
  50051. } else if (envLower === 'true' || envLower === '1') {
  50052. opts.usePolling = true;
  50053. } else {
  50054. opts.usePolling = !!envLower;
  50055. }
  50056. }
  50057. const envInterval = process.env.CHOKIDAR_INTERVAL;
  50058. if (envInterval) {
  50059. opts.interval = Number.parseInt(envInterval, 10);
  50060. }
  50061. // Editor atomic write normalization enabled by default with fs.watch
  50062. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  50063. if (opts.atomic) this._pendingUnlinks = new Map();
  50064. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  50065. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  50066. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  50067. const awf = opts.awaitWriteFinish;
  50068. if (awf) {
  50069. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  50070. if (!awf.pollInterval) awf.pollInterval = 100;
  50071. this._pendingWrites = new Map();
  50072. }
  50073. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  50074. let readyCalls = 0;
  50075. this._emitReady = () => {
  50076. readyCalls++;
  50077. if (readyCalls >= this._readyCount) {
  50078. this._emitReady = EMPTY_FN;
  50079. this._readyEmitted = true;
  50080. // use process.nextTick to allow time for listener to be bound
  50081. process.nextTick(() => this.emit(EV_READY));
  50082. }
  50083. };
  50084. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  50085. this._readyEmitted = false;
  50086. this.options = opts;
  50087. // Initialize with proper watcher.
  50088. if (opts.useFsEvents) {
  50089. this._fsEventsHandler = new FsEventsHandler(this);
  50090. } else {
  50091. this._nodeFsHandler = new NodeFsHandler(this);
  50092. }
  50093. // You’re frozen when your heart’s not open.
  50094. Object.freeze(opts);
  50095. }
  50096. // Public methods
  50097. /**
  50098. * Adds paths to be watched on an existing FSWatcher instance
  50099. * @param {Path|Array<Path>} paths_
  50100. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  50101. * @param {Boolean=} _internal private; indicates a non-user add
  50102. * @returns {FSWatcher} for chaining
  50103. */
  50104. add(paths_, _origAdd, _internal) {
  50105. const {cwd, disableGlobbing} = this.options;
  50106. this.closed = false;
  50107. let paths = unifyPaths(paths_);
  50108. if (cwd) {
  50109. paths = paths.map((path) => {
  50110. const absPath = getAbsolutePath(path, cwd);
  50111. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  50112. if (disableGlobbing || !isGlob(path)) {
  50113. return absPath;
  50114. }
  50115. return normalizePath(absPath);
  50116. });
  50117. }
  50118. // set aside negated glob strings
  50119. paths = paths.filter((path) => {
  50120. if (path.startsWith(BANG)) {
  50121. this._ignoredPaths.add(path.slice(1));
  50122. return false;
  50123. }
  50124. // if a path is being added that was previously ignored, stop ignoring it
  50125. this._ignoredPaths.delete(path);
  50126. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  50127. // reset the cached userIgnored anymatch fn
  50128. // to make ignoredPaths changes effective
  50129. this._userIgnored = undefined;
  50130. return true;
  50131. });
  50132. if (this.options.useFsEvents && this._fsEventsHandler) {
  50133. if (!this._readyCount) this._readyCount = paths.length;
  50134. if (this.options.persistent) this._readyCount *= 2;
  50135. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  50136. } else {
  50137. if (!this._readyCount) this._readyCount = 0;
  50138. this._readyCount += paths.length;
  50139. Promise.all(
  50140. paths.map(async path => {
  50141. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  50142. if (res) this._emitReady();
  50143. return res;
  50144. })
  50145. ).then(results => {
  50146. if (this.closed) return;
  50147. results.filter(item => item).forEach(item => {
  50148. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  50149. });
  50150. });
  50151. }
  50152. return this;
  50153. }
  50154. /**
  50155. * Close watchers or start ignoring events from specified paths.
  50156. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  50157. * @returns {FSWatcher} for chaining
  50158. */
  50159. unwatch(paths_) {
  50160. if (this.closed) return this;
  50161. const paths = unifyPaths(paths_);
  50162. const {cwd} = this.options;
  50163. paths.forEach((path) => {
  50164. // convert to absolute path unless relative path already matches
  50165. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  50166. if (cwd) path = sysPath.join(cwd, path);
  50167. path = sysPath.resolve(path);
  50168. }
  50169. this._closePath(path);
  50170. this._ignoredPaths.add(path);
  50171. if (this._watched.has(path)) {
  50172. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  50173. }
  50174. // reset the cached userIgnored anymatch fn
  50175. // to make ignoredPaths changes effective
  50176. this._userIgnored = undefined;
  50177. });
  50178. return this;
  50179. }
  50180. /**
  50181. * Close watchers and remove all listeners from watched paths.
  50182. * @returns {Promise<void>}.
  50183. */
  50184. close() {
  50185. if (this.closed) return this._closePromise;
  50186. this.closed = true;
  50187. // Memory management.
  50188. this.removeAllListeners();
  50189. const closers = [];
  50190. this._closers.forEach(closerList => closerList.forEach(closer => {
  50191. const promise = closer();
  50192. if (promise instanceof Promise) closers.push(promise);
  50193. }));
  50194. this._streams.forEach(stream => stream.destroy());
  50195. this._userIgnored = undefined;
  50196. this._readyCount = 0;
  50197. this._readyEmitted = false;
  50198. this._watched.forEach(dirent => dirent.dispose());
  50199. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  50200. this[`_${key}`].clear();
  50201. });
  50202. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  50203. return this._closePromise;
  50204. }
  50205. /**
  50206. * Expose list of watched paths
  50207. * @returns {Object} for chaining
  50208. */
  50209. getWatched() {
  50210. const watchList = {};
  50211. this._watched.forEach((entry, dir) => {
  50212. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  50213. watchList[key || ONE_DOT] = entry.getChildren().sort();
  50214. });
  50215. return watchList;
  50216. }
  50217. emitWithAll(event, args) {
  50218. this.emit(...args);
  50219. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  50220. }
  50221. // Common helpers
  50222. // --------------
  50223. /**
  50224. * Normalize and emit events.
  50225. * Calling _emit DOES NOT MEAN emit() would be called!
  50226. * @param {EventName} event Type of event
  50227. * @param {Path} path File or directory path
  50228. * @param {*=} val1 arguments to be passed with event
  50229. * @param {*=} val2
  50230. * @param {*=} val3
  50231. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  50232. */
  50233. async _emit(event, path, val1, val2, val3) {
  50234. if (this.closed) return;
  50235. const opts = this.options;
  50236. if (isWindows$1) path = sysPath.normalize(path);
  50237. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  50238. /** @type Array<any> */
  50239. const args = [event, path];
  50240. if (val3 !== undefined) args.push(val1, val2, val3);
  50241. else if (val2 !== undefined) args.push(val1, val2);
  50242. else if (val1 !== undefined) args.push(val1);
  50243. const awf = opts.awaitWriteFinish;
  50244. let pw;
  50245. if (awf && (pw = this._pendingWrites.get(path))) {
  50246. pw.lastChange = new Date();
  50247. return this;
  50248. }
  50249. if (opts.atomic) {
  50250. if (event === EV_UNLINK) {
  50251. this._pendingUnlinks.set(path, args);
  50252. setTimeout(() => {
  50253. this._pendingUnlinks.forEach((entry, path) => {
  50254. this.emit(...entry);
  50255. this.emit(EV_ALL, ...entry);
  50256. this._pendingUnlinks.delete(path);
  50257. });
  50258. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  50259. return this;
  50260. }
  50261. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  50262. event = args[0] = EV_CHANGE;
  50263. this._pendingUnlinks.delete(path);
  50264. }
  50265. }
  50266. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  50267. const awfEmit = (err, stats) => {
  50268. if (err) {
  50269. event = args[0] = EV_ERROR;
  50270. args[1] = err;
  50271. this.emitWithAll(event, args);
  50272. } else if (stats) {
  50273. // if stats doesn't exist the file must have been deleted
  50274. if (args.length > 2) {
  50275. args[2] = stats;
  50276. } else {
  50277. args.push(stats);
  50278. }
  50279. this.emitWithAll(event, args);
  50280. }
  50281. };
  50282. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  50283. return this;
  50284. }
  50285. if (event === EV_CHANGE) {
  50286. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  50287. if (isThrottled) return this;
  50288. }
  50289. if (opts.alwaysStat && val1 === undefined &&
  50290. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  50291. ) {
  50292. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  50293. let stats;
  50294. try {
  50295. stats = await stat(fullPath);
  50296. } catch (err) {}
  50297. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  50298. if (!stats || this.closed) return;
  50299. args.push(stats);
  50300. }
  50301. this.emitWithAll(event, args);
  50302. return this;
  50303. }
  50304. /**
  50305. * Common handler for errors
  50306. * @param {Error} error
  50307. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  50308. */
  50309. _handleError(error) {
  50310. const code = error && error.code;
  50311. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  50312. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  50313. ) {
  50314. this.emit(EV_ERROR, error);
  50315. }
  50316. return error || this.closed;
  50317. }
  50318. /**
  50319. * Helper utility for throttling
  50320. * @param {ThrottleType} actionType type being throttled
  50321. * @param {Path} path being acted upon
  50322. * @param {Number} timeout duration of time to suppress duplicate actions
  50323. * @returns {Object|false} tracking object or false if action should be suppressed
  50324. */
  50325. _throttle(actionType, path, timeout) {
  50326. if (!this._throttled.has(actionType)) {
  50327. this._throttled.set(actionType, new Map());
  50328. }
  50329. /** @type {Map<Path, Object>} */
  50330. const action = this._throttled.get(actionType);
  50331. /** @type {Object} */
  50332. const actionPath = action.get(path);
  50333. if (actionPath) {
  50334. actionPath.count++;
  50335. return false;
  50336. }
  50337. let timeoutObject;
  50338. const clear = () => {
  50339. const item = action.get(path);
  50340. const count = item ? item.count : 0;
  50341. action.delete(path);
  50342. clearTimeout(timeoutObject);
  50343. if (item) clearTimeout(item.timeoutObject);
  50344. return count;
  50345. };
  50346. timeoutObject = setTimeout(clear, timeout);
  50347. const thr = {timeoutObject, clear, count: 0};
  50348. action.set(path, thr);
  50349. return thr;
  50350. }
  50351. _incrReadyCount() {
  50352. return this._readyCount++;
  50353. }
  50354. /**
  50355. * Awaits write operation to finish.
  50356. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  50357. * @param {Path} path being acted upon
  50358. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  50359. * @param {EventName} event
  50360. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  50361. */
  50362. _awaitWriteFinish(path, threshold, event, awfEmit) {
  50363. let timeoutHandler;
  50364. let fullPath = path;
  50365. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  50366. fullPath = sysPath.join(this.options.cwd, path);
  50367. }
  50368. const now = new Date();
  50369. const awaitWriteFinish = (prevStat) => {
  50370. fs$8.stat(fullPath, (err, curStat) => {
  50371. if (err || !this._pendingWrites.has(path)) {
  50372. if (err && err.code !== 'ENOENT') awfEmit(err);
  50373. return;
  50374. }
  50375. const now = Number(new Date());
  50376. if (prevStat && curStat.size !== prevStat.size) {
  50377. this._pendingWrites.get(path).lastChange = now;
  50378. }
  50379. const pw = this._pendingWrites.get(path);
  50380. const df = now - pw.lastChange;
  50381. if (df >= threshold) {
  50382. this._pendingWrites.delete(path);
  50383. awfEmit(undefined, curStat);
  50384. } else {
  50385. timeoutHandler = setTimeout(
  50386. awaitWriteFinish,
  50387. this.options.awaitWriteFinish.pollInterval,
  50388. curStat
  50389. );
  50390. }
  50391. });
  50392. };
  50393. if (!this._pendingWrites.has(path)) {
  50394. this._pendingWrites.set(path, {
  50395. lastChange: now,
  50396. cancelWait: () => {
  50397. this._pendingWrites.delete(path);
  50398. clearTimeout(timeoutHandler);
  50399. return event;
  50400. }
  50401. });
  50402. timeoutHandler = setTimeout(
  50403. awaitWriteFinish,
  50404. this.options.awaitWriteFinish.pollInterval
  50405. );
  50406. }
  50407. }
  50408. _getGlobIgnored() {
  50409. return [...this._ignoredPaths.values()];
  50410. }
  50411. /**
  50412. * Determines whether user has asked to ignore this path.
  50413. * @param {Path} path filepath or dir
  50414. * @param {fs.Stats=} stats result of fs.stat
  50415. * @returns {Boolean}
  50416. */
  50417. _isIgnored(path, stats) {
  50418. if (this.options.atomic && DOT_RE.test(path)) return true;
  50419. if (!this._userIgnored) {
  50420. const {cwd} = this.options;
  50421. const ign = this.options.ignored;
  50422. const ignored = ign && ign.map(normalizeIgnored(cwd));
  50423. const paths = arrify(ignored)
  50424. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  50425. .map((path) => path + SLASH_GLOBSTAR);
  50426. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  50427. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  50428. }
  50429. return this._userIgnored([path, stats]);
  50430. }
  50431. _isntIgnored(path, stat) {
  50432. return !this._isIgnored(path, stat);
  50433. }
  50434. /**
  50435. * Provides a set of common helpers and properties relating to symlink and glob handling.
  50436. * @param {Path} path file, directory, or glob pattern being watched
  50437. * @param {Number=} depth at any depth > 0, this isn't a glob
  50438. * @returns {WatchHelper} object containing helpers for this path
  50439. */
  50440. _getWatchHelpers(path, depth) {
  50441. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  50442. const follow = this.options.followSymlinks;
  50443. return new WatchHelper(path, watchPath, follow, this);
  50444. }
  50445. // Directory helpers
  50446. // -----------------
  50447. /**
  50448. * Provides directory tracking objects
  50449. * @param {String} directory path of the directory
  50450. * @returns {DirEntry} the directory's tracking object
  50451. */
  50452. _getWatchedDir(directory) {
  50453. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  50454. const dir = sysPath.resolve(directory);
  50455. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  50456. return this._watched.get(dir);
  50457. }
  50458. // File helpers
  50459. // ------------
  50460. /**
  50461. * Check for read permissions.
  50462. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  50463. * @param {fs.Stats} stats - object, result of fs_stat
  50464. * @returns {Boolean} indicates whether the file can be read
  50465. */
  50466. _hasReadPermissions(stats) {
  50467. if (this.options.ignorePermissionErrors) return true;
  50468. // stats.mode may be bigint
  50469. const md = stats && Number.parseInt(stats.mode, 10);
  50470. const st = md & 0o777;
  50471. const it = Number.parseInt(st.toString(8)[0], 10);
  50472. return Boolean(4 & it);
  50473. }
  50474. /**
  50475. * Handles emitting unlink events for
  50476. * files and directories, and via recursion, for
  50477. * files and directories within directories that are unlinked
  50478. * @param {String} directory within which the following item is located
  50479. * @param {String} item base path of item/directory
  50480. * @returns {void}
  50481. */
  50482. _remove(directory, item, isDirectory) {
  50483. // if what is being deleted is a directory, get that directory's paths
  50484. // for recursive deleting and cleaning of watched object
  50485. // if it is not a directory, nestedDirectoryChildren will be empty array
  50486. const path = sysPath.join(directory, item);
  50487. const fullPath = sysPath.resolve(path);
  50488. isDirectory = isDirectory != null
  50489. ? isDirectory
  50490. : this._watched.has(path) || this._watched.has(fullPath);
  50491. // prevent duplicate handling in case of arriving here nearly simultaneously
  50492. // via multiple paths (such as _handleFile and _handleDir)
  50493. if (!this._throttle('remove', path, 100)) return;
  50494. // if the only watched file is removed, watch for its return
  50495. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  50496. this.add(directory, item, true);
  50497. }
  50498. // This will create a new entry in the watched object in either case
  50499. // so we got to do the directory check beforehand
  50500. const wp = this._getWatchedDir(path);
  50501. const nestedDirectoryChildren = wp.getChildren();
  50502. // Recursively remove children directories / files.
  50503. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  50504. // Check if item was on the watched list and remove it
  50505. const parent = this._getWatchedDir(directory);
  50506. const wasTracked = parent.has(item);
  50507. parent.remove(item);
  50508. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  50509. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  50510. // but never removed from the map in case the path was deleted.
  50511. // This leads to an incorrect state if the path was recreated:
  50512. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  50513. if (this._symlinkPaths.has(fullPath)) {
  50514. this._symlinkPaths.delete(fullPath);
  50515. }
  50516. // If we wait for this file to be fully written, cancel the wait.
  50517. let relPath = path;
  50518. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  50519. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  50520. const event = this._pendingWrites.get(relPath).cancelWait();
  50521. if (event === EV_ADD) return;
  50522. }
  50523. // The Entry will either be a directory that just got removed
  50524. // or a bogus entry to a file, in either case we have to remove it
  50525. this._watched.delete(path);
  50526. this._watched.delete(fullPath);
  50527. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  50528. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  50529. // Avoid conflicts if we later create another file with the same name
  50530. if (!this.options.useFsEvents) {
  50531. this._closePath(path);
  50532. }
  50533. }
  50534. /**
  50535. * Closes all watchers for a path
  50536. * @param {Path} path
  50537. */
  50538. _closePath(path) {
  50539. this._closeFile(path);
  50540. const dir = sysPath.dirname(path);
  50541. this._getWatchedDir(dir).remove(sysPath.basename(path));
  50542. }
  50543. /**
  50544. * Closes only file-specific watchers
  50545. * @param {Path} path
  50546. */
  50547. _closeFile(path) {
  50548. const closers = this._closers.get(path);
  50549. if (!closers) return;
  50550. closers.forEach(closer => closer());
  50551. this._closers.delete(path);
  50552. }
  50553. /**
  50554. *
  50555. * @param {Path} path
  50556. * @param {Function} closer
  50557. */
  50558. _addPathCloser(path, closer) {
  50559. if (!closer) return;
  50560. let list = this._closers.get(path);
  50561. if (!list) {
  50562. list = [];
  50563. this._closers.set(path, list);
  50564. }
  50565. list.push(closer);
  50566. }
  50567. _readdirp(root, opts) {
  50568. if (this.closed) return;
  50569. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  50570. let stream = readdirp(root, options);
  50571. this._streams.add(stream);
  50572. stream.once(STR_CLOSE, () => {
  50573. stream = undefined;
  50574. });
  50575. stream.once(STR_END, () => {
  50576. if (stream) {
  50577. this._streams.delete(stream);
  50578. stream = undefined;
  50579. }
  50580. });
  50581. return stream;
  50582. }
  50583. }
  50584. // Export FSWatcher class
  50585. chokidar.FSWatcher = FSWatcher;
  50586. /**
  50587. * Instantiates watcher with paths to be tracked.
  50588. * @param {String|Array<String>} paths file/directory paths and/or globs
  50589. * @param {Object=} options chokidar opts
  50590. * @returns an instance of FSWatcher for chaining.
  50591. */
  50592. const watch = (paths, options) => {
  50593. const watcher = new FSWatcher(options);
  50594. watcher.add(paths);
  50595. return watcher;
  50596. };
  50597. chokidar.watch = watch;
  50598. async function resolveHttpServer({ proxy }, app, httpsOptions) {
  50599. if (!httpsOptions) {
  50600. return require('http').createServer(app);
  50601. }
  50602. if (proxy) {
  50603. // #484 fallback to http1 when proxy is needed.
  50604. return require('https').createServer(httpsOptions, app);
  50605. }
  50606. else {
  50607. return require('http2').createSecureServer({
  50608. ...httpsOptions,
  50609. allowHTTP1: true
  50610. }, app);
  50611. }
  50612. }
  50613. async function resolveHttpsConfig(config) {
  50614. if (!config.server.https)
  50615. return undefined;
  50616. const httpsOption = isObject$3(config.server.https) ? config.server.https : {};
  50617. const { ca, cert, key, pfx } = httpsOption;
  50618. Object.assign(httpsOption, {
  50619. ca: readFileIfExists(ca),
  50620. cert: readFileIfExists(cert),
  50621. key: readFileIfExists(key),
  50622. pfx: readFileIfExists(pfx)
  50623. });
  50624. if (!httpsOption.key || !httpsOption.cert) {
  50625. httpsOption.cert = httpsOption.key = await getCertificate(config);
  50626. }
  50627. return httpsOption;
  50628. }
  50629. function readFileIfExists(value) {
  50630. if (typeof value === 'string') {
  50631. try {
  50632. return fs__default.readFileSync(path__default.resolve(value));
  50633. }
  50634. catch (e) {
  50635. return value;
  50636. }
  50637. }
  50638. return value;
  50639. }
  50640. /**
  50641. * https://github.com/webpack/webpack-dev-server/blob/master/lib/utils/createCertificate.js
  50642. *
  50643. * Copyright JS Foundation and other contributors
  50644. * This source code is licensed under the MIT license found in the
  50645. * LICENSE file at
  50646. * https://github.com/webpack/webpack-dev-server/blob/master/LICENSE
  50647. */
  50648. async function createCertificate() {
  50649. const { generate } = await Promise.resolve().then(function () { return require('./dep-0e948eb3.js'); }).then(function (n) { return n.index; });
  50650. const pems = generate(null, {
  50651. algorithm: 'sha256',
  50652. days: 30,
  50653. keySize: 2048,
  50654. extensions: [
  50655. // {
  50656. // name: 'basicConstraints',
  50657. // cA: true,
  50658. // },
  50659. {
  50660. name: 'keyUsage',
  50661. keyCertSign: true,
  50662. digitalSignature: true,
  50663. nonRepudiation: true,
  50664. keyEncipherment: true,
  50665. dataEncipherment: true
  50666. },
  50667. {
  50668. name: 'extKeyUsage',
  50669. serverAuth: true,
  50670. clientAuth: true,
  50671. codeSigning: true,
  50672. timeStamping: true
  50673. },
  50674. {
  50675. name: 'subjectAltName',
  50676. altNames: [
  50677. {
  50678. // type 2 is DNS
  50679. type: 2,
  50680. value: 'localhost'
  50681. },
  50682. {
  50683. type: 2,
  50684. value: 'localhost.localdomain'
  50685. },
  50686. {
  50687. type: 2,
  50688. value: 'lvh.me'
  50689. },
  50690. {
  50691. type: 2,
  50692. value: '*.lvh.me'
  50693. },
  50694. {
  50695. type: 2,
  50696. value: '[::1]'
  50697. },
  50698. {
  50699. // type 7 is IP
  50700. type: 7,
  50701. ip: '127.0.0.1'
  50702. },
  50703. {
  50704. type: 7,
  50705. ip: 'fe80::1'
  50706. }
  50707. ]
  50708. }
  50709. ]
  50710. });
  50711. return pems.private + pems.cert;
  50712. }
  50713. async function getCertificate(config) {
  50714. if (!config.cacheDir)
  50715. return await createCertificate();
  50716. const cachePath = path__default.join(config.cacheDir, '_cert.pem');
  50717. try {
  50718. const [stat, content] = await Promise.all([
  50719. fs$v.promises.stat(cachePath),
  50720. fs$v.promises.readFile(cachePath, 'utf8')
  50721. ]);
  50722. if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1000) {
  50723. throw new Error('cache is outdated.');
  50724. }
  50725. return content;
  50726. }
  50727. catch {
  50728. const content = await createCertificate();
  50729. fs$v.promises
  50730. .mkdir(config.cacheDir, { recursive: true })
  50731. .then(() => fs$v.promises.writeFile(cachePath, content))
  50732. .catch(() => { });
  50733. return content;
  50734. }
  50735. }
  50736. async function httpServerStart(httpServer, serverOptions) {
  50737. return new Promise((resolve, reject) => {
  50738. let { port, strictPort, host, logger } = serverOptions;
  50739. const onError = (e) => {
  50740. if (e.code === 'EADDRINUSE') {
  50741. if (strictPort) {
  50742. httpServer.removeListener('error', onError);
  50743. reject(new Error(`Port ${port} is already in use`));
  50744. }
  50745. else {
  50746. logger.info(`Port ${port} is in use, trying another one...`);
  50747. httpServer.listen(++port, host);
  50748. }
  50749. }
  50750. else {
  50751. httpServer.removeListener('error', onError);
  50752. reject(e);
  50753. }
  50754. };
  50755. httpServer.on('error', onError);
  50756. httpServer.listen(port, host, () => {
  50757. httpServer.removeListener('error', onError);
  50758. resolve(port);
  50759. });
  50760. });
  50761. }
  50762. var bufferUtil$1 = {exports: {}};
  50763. var constants = {
  50764. BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
  50765. GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
  50766. kStatusCode: Symbol('status-code'),
  50767. kWebSocket: Symbol('websocket'),
  50768. EMPTY_BUFFER: Buffer.alloc(0),
  50769. NOOP: () => {}
  50770. };
  50771. const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
  50772. /**
  50773. * Merges an array of buffers into a new buffer.
  50774. *
  50775. * @param {Buffer[]} list The array of buffers to concat
  50776. * @param {Number} totalLength The total length of buffers in the list
  50777. * @return {Buffer} The resulting buffer
  50778. * @public
  50779. */
  50780. function concat$1(list, totalLength) {
  50781. if (list.length === 0) return EMPTY_BUFFER$3;
  50782. if (list.length === 1) return list[0];
  50783. const target = Buffer.allocUnsafe(totalLength);
  50784. let offset = 0;
  50785. for (let i = 0; i < list.length; i++) {
  50786. const buf = list[i];
  50787. target.set(buf, offset);
  50788. offset += buf.length;
  50789. }
  50790. if (offset < totalLength) return target.slice(0, offset);
  50791. return target;
  50792. }
  50793. /**
  50794. * Masks a buffer using the given mask.
  50795. *
  50796. * @param {Buffer} source The buffer to mask
  50797. * @param {Buffer} mask The mask to use
  50798. * @param {Buffer} output The buffer where to store the result
  50799. * @param {Number} offset The offset at which to start writing
  50800. * @param {Number} length The number of bytes to mask.
  50801. * @public
  50802. */
  50803. function _mask(source, mask, output, offset, length) {
  50804. for (let i = 0; i < length; i++) {
  50805. output[offset + i] = source[i] ^ mask[i & 3];
  50806. }
  50807. }
  50808. /**
  50809. * Unmasks a buffer using the given mask.
  50810. *
  50811. * @param {Buffer} buffer The buffer to unmask
  50812. * @param {Buffer} mask The mask to use
  50813. * @public
  50814. */
  50815. function _unmask(buffer, mask) {
  50816. // Required until https://github.com/nodejs/node/issues/9006 is resolved.
  50817. const length = buffer.length;
  50818. for (let i = 0; i < length; i++) {
  50819. buffer[i] ^= mask[i & 3];
  50820. }
  50821. }
  50822. /**
  50823. * Converts a buffer to an `ArrayBuffer`.
  50824. *
  50825. * @param {Buffer} buf The buffer to convert
  50826. * @return {ArrayBuffer} Converted buffer
  50827. * @public
  50828. */
  50829. function toArrayBuffer$1(buf) {
  50830. if (buf.byteLength === buf.buffer.byteLength) {
  50831. return buf.buffer;
  50832. }
  50833. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  50834. }
  50835. /**
  50836. * Converts `data` to a `Buffer`.
  50837. *
  50838. * @param {*} data The data to convert
  50839. * @return {Buffer} The buffer
  50840. * @throws {TypeError}
  50841. * @public
  50842. */
  50843. function toBuffer$2(data) {
  50844. toBuffer$2.readOnly = true;
  50845. if (Buffer.isBuffer(data)) return data;
  50846. let buf;
  50847. if (data instanceof ArrayBuffer) {
  50848. buf = Buffer.from(data);
  50849. } else if (ArrayBuffer.isView(data)) {
  50850. buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
  50851. } else {
  50852. buf = Buffer.from(data);
  50853. toBuffer$2.readOnly = false;
  50854. }
  50855. return buf;
  50856. }
  50857. try {
  50858. const bufferUtil = require('bufferutil');
  50859. const bu = bufferUtil.BufferUtil || bufferUtil;
  50860. bufferUtil$1.exports = {
  50861. concat: concat$1,
  50862. mask(source, mask, output, offset, length) {
  50863. if (length < 48) _mask(source, mask, output, offset, length);
  50864. else bu.mask(source, mask, output, offset, length);
  50865. },
  50866. toArrayBuffer: toArrayBuffer$1,
  50867. toBuffer: toBuffer$2,
  50868. unmask(buffer, mask) {
  50869. if (buffer.length < 32) _unmask(buffer, mask);
  50870. else bu.unmask(buffer, mask);
  50871. }
  50872. };
  50873. } catch (e) /* istanbul ignore next */ {
  50874. bufferUtil$1.exports = {
  50875. concat: concat$1,
  50876. mask: _mask,
  50877. toArrayBuffer: toArrayBuffer$1,
  50878. toBuffer: toBuffer$2,
  50879. unmask: _unmask
  50880. };
  50881. }
  50882. const kDone = Symbol('kDone');
  50883. const kRun = Symbol('kRun');
  50884. /**
  50885. * A very simple job queue with adjustable concurrency. Adapted from
  50886. * https://github.com/STRML/async-limiter
  50887. */
  50888. class Limiter$1 {
  50889. /**
  50890. * Creates a new `Limiter`.
  50891. *
  50892. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  50893. * to run concurrently
  50894. */
  50895. constructor(concurrency) {
  50896. this[kDone] = () => {
  50897. this.pending--;
  50898. this[kRun]();
  50899. };
  50900. this.concurrency = concurrency || Infinity;
  50901. this.jobs = [];
  50902. this.pending = 0;
  50903. }
  50904. /**
  50905. * Adds a job to the queue.
  50906. *
  50907. * @param {Function} job The job to run
  50908. * @public
  50909. */
  50910. add(job) {
  50911. this.jobs.push(job);
  50912. this[kRun]();
  50913. }
  50914. /**
  50915. * Removes a job from the queue and runs it if possible.
  50916. *
  50917. * @private
  50918. */
  50919. [kRun]() {
  50920. if (this.pending === this.concurrency) return;
  50921. if (this.jobs.length) {
  50922. const job = this.jobs.shift();
  50923. this.pending++;
  50924. job(this[kDone]);
  50925. }
  50926. }
  50927. }
  50928. var limiter = Limiter$1;
  50929. const zlib = require$$0__default$4;
  50930. const bufferUtil = bufferUtil$1.exports;
  50931. const Limiter = limiter;
  50932. const { kStatusCode: kStatusCode$2, NOOP: NOOP$1 } = constants;
  50933. const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
  50934. const kPerMessageDeflate = Symbol('permessage-deflate');
  50935. const kTotalLength = Symbol('total-length');
  50936. const kCallback = Symbol('callback');
  50937. const kBuffers = Symbol('buffers');
  50938. const kError = Symbol('error');
  50939. //
  50940. // We limit zlib concurrency, which prevents severe memory fragmentation
  50941. // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
  50942. // and https://github.com/websockets/ws/issues/1202
  50943. //
  50944. // Intentionally global; it's the global thread pool that's an issue.
  50945. //
  50946. let zlibLimiter;
  50947. /**
  50948. * permessage-deflate implementation.
  50949. */
  50950. class PerMessageDeflate$4 {
  50951. /**
  50952. * Creates a PerMessageDeflate instance.
  50953. *
  50954. * @param {Object} [options] Configuration options
  50955. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  50956. * disabling of server context takeover
  50957. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  50958. * acknowledge disabling of client context takeover
  50959. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  50960. * use of a custom server window size
  50961. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  50962. * for, or request, a custom client window size
  50963. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  50964. * deflate
  50965. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  50966. * inflate
  50967. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  50968. * messages should not be compressed
  50969. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  50970. * calls to zlib
  50971. * @param {Boolean} [isServer=false] Create the instance in either server or
  50972. * client mode
  50973. * @param {Number} [maxPayload=0] The maximum allowed message length
  50974. */
  50975. constructor(options, isServer, maxPayload) {
  50976. this._maxPayload = maxPayload | 0;
  50977. this._options = options || {};
  50978. this._threshold =
  50979. this._options.threshold !== undefined ? this._options.threshold : 1024;
  50980. this._isServer = !!isServer;
  50981. this._deflate = null;
  50982. this._inflate = null;
  50983. this.params = null;
  50984. if (!zlibLimiter) {
  50985. const concurrency =
  50986. this._options.concurrencyLimit !== undefined
  50987. ? this._options.concurrencyLimit
  50988. : 10;
  50989. zlibLimiter = new Limiter(concurrency);
  50990. }
  50991. }
  50992. /**
  50993. * @type {String}
  50994. */
  50995. static get extensionName() {
  50996. return 'permessage-deflate';
  50997. }
  50998. /**
  50999. * Create an extension negotiation offer.
  51000. *
  51001. * @return {Object} Extension parameters
  51002. * @public
  51003. */
  51004. offer() {
  51005. const params = {};
  51006. if (this._options.serverNoContextTakeover) {
  51007. params.server_no_context_takeover = true;
  51008. }
  51009. if (this._options.clientNoContextTakeover) {
  51010. params.client_no_context_takeover = true;
  51011. }
  51012. if (this._options.serverMaxWindowBits) {
  51013. params.server_max_window_bits = this._options.serverMaxWindowBits;
  51014. }
  51015. if (this._options.clientMaxWindowBits) {
  51016. params.client_max_window_bits = this._options.clientMaxWindowBits;
  51017. } else if (this._options.clientMaxWindowBits == null) {
  51018. params.client_max_window_bits = true;
  51019. }
  51020. return params;
  51021. }
  51022. /**
  51023. * Accept an extension negotiation offer/response.
  51024. *
  51025. * @param {Array} configurations The extension negotiation offers/reponse
  51026. * @return {Object} Accepted configuration
  51027. * @public
  51028. */
  51029. accept(configurations) {
  51030. configurations = this.normalizeParams(configurations);
  51031. this.params = this._isServer
  51032. ? this.acceptAsServer(configurations)
  51033. : this.acceptAsClient(configurations);
  51034. return this.params;
  51035. }
  51036. /**
  51037. * Releases all resources used by the extension.
  51038. *
  51039. * @public
  51040. */
  51041. cleanup() {
  51042. if (this._inflate) {
  51043. this._inflate.close();
  51044. this._inflate = null;
  51045. }
  51046. if (this._deflate) {
  51047. const callback = this._deflate[kCallback];
  51048. this._deflate.close();
  51049. this._deflate = null;
  51050. if (callback) {
  51051. callback(
  51052. new Error(
  51053. 'The deflate stream was closed while data was being processed'
  51054. )
  51055. );
  51056. }
  51057. }
  51058. }
  51059. /**
  51060. * Accept an extension negotiation offer.
  51061. *
  51062. * @param {Array} offers The extension negotiation offers
  51063. * @return {Object} Accepted configuration
  51064. * @private
  51065. */
  51066. acceptAsServer(offers) {
  51067. const opts = this._options;
  51068. const accepted = offers.find((params) => {
  51069. if (
  51070. (opts.serverNoContextTakeover === false &&
  51071. params.server_no_context_takeover) ||
  51072. (params.server_max_window_bits &&
  51073. (opts.serverMaxWindowBits === false ||
  51074. (typeof opts.serverMaxWindowBits === 'number' &&
  51075. opts.serverMaxWindowBits > params.server_max_window_bits))) ||
  51076. (typeof opts.clientMaxWindowBits === 'number' &&
  51077. !params.client_max_window_bits)
  51078. ) {
  51079. return false;
  51080. }
  51081. return true;
  51082. });
  51083. if (!accepted) {
  51084. throw new Error('None of the extension offers can be accepted');
  51085. }
  51086. if (opts.serverNoContextTakeover) {
  51087. accepted.server_no_context_takeover = true;
  51088. }
  51089. if (opts.clientNoContextTakeover) {
  51090. accepted.client_no_context_takeover = true;
  51091. }
  51092. if (typeof opts.serverMaxWindowBits === 'number') {
  51093. accepted.server_max_window_bits = opts.serverMaxWindowBits;
  51094. }
  51095. if (typeof opts.clientMaxWindowBits === 'number') {
  51096. accepted.client_max_window_bits = opts.clientMaxWindowBits;
  51097. } else if (
  51098. accepted.client_max_window_bits === true ||
  51099. opts.clientMaxWindowBits === false
  51100. ) {
  51101. delete accepted.client_max_window_bits;
  51102. }
  51103. return accepted;
  51104. }
  51105. /**
  51106. * Accept the extension negotiation response.
  51107. *
  51108. * @param {Array} response The extension negotiation response
  51109. * @return {Object} Accepted configuration
  51110. * @private
  51111. */
  51112. acceptAsClient(response) {
  51113. const params = response[0];
  51114. if (
  51115. this._options.clientNoContextTakeover === false &&
  51116. params.client_no_context_takeover
  51117. ) {
  51118. throw new Error('Unexpected parameter "client_no_context_takeover"');
  51119. }
  51120. if (!params.client_max_window_bits) {
  51121. if (typeof this._options.clientMaxWindowBits === 'number') {
  51122. params.client_max_window_bits = this._options.clientMaxWindowBits;
  51123. }
  51124. } else if (
  51125. this._options.clientMaxWindowBits === false ||
  51126. (typeof this._options.clientMaxWindowBits === 'number' &&
  51127. params.client_max_window_bits > this._options.clientMaxWindowBits)
  51128. ) {
  51129. throw new Error(
  51130. 'Unexpected or invalid parameter "client_max_window_bits"'
  51131. );
  51132. }
  51133. return params;
  51134. }
  51135. /**
  51136. * Normalize parameters.
  51137. *
  51138. * @param {Array} configurations The extension negotiation offers/reponse
  51139. * @return {Array} The offers/response with normalized parameters
  51140. * @private
  51141. */
  51142. normalizeParams(configurations) {
  51143. configurations.forEach((params) => {
  51144. Object.keys(params).forEach((key) => {
  51145. let value = params[key];
  51146. if (value.length > 1) {
  51147. throw new Error(`Parameter "${key}" must have only a single value`);
  51148. }
  51149. value = value[0];
  51150. if (key === 'client_max_window_bits') {
  51151. if (value !== true) {
  51152. const num = +value;
  51153. if (!Number.isInteger(num) || num < 8 || num > 15) {
  51154. throw new TypeError(
  51155. `Invalid value for parameter "${key}": ${value}`
  51156. );
  51157. }
  51158. value = num;
  51159. } else if (!this._isServer) {
  51160. throw new TypeError(
  51161. `Invalid value for parameter "${key}": ${value}`
  51162. );
  51163. }
  51164. } else if (key === 'server_max_window_bits') {
  51165. const num = +value;
  51166. if (!Number.isInteger(num) || num < 8 || num > 15) {
  51167. throw new TypeError(
  51168. `Invalid value for parameter "${key}": ${value}`
  51169. );
  51170. }
  51171. value = num;
  51172. } else if (
  51173. key === 'client_no_context_takeover' ||
  51174. key === 'server_no_context_takeover'
  51175. ) {
  51176. if (value !== true) {
  51177. throw new TypeError(
  51178. `Invalid value for parameter "${key}": ${value}`
  51179. );
  51180. }
  51181. } else {
  51182. throw new Error(`Unknown parameter "${key}"`);
  51183. }
  51184. params[key] = value;
  51185. });
  51186. });
  51187. return configurations;
  51188. }
  51189. /**
  51190. * Decompress data. Concurrency limited.
  51191. *
  51192. * @param {Buffer} data Compressed data
  51193. * @param {Boolean} fin Specifies whether or not this is the last fragment
  51194. * @param {Function} callback Callback
  51195. * @public
  51196. */
  51197. decompress(data, fin, callback) {
  51198. zlibLimiter.add((done) => {
  51199. this._decompress(data, fin, (err, result) => {
  51200. done();
  51201. callback(err, result);
  51202. });
  51203. });
  51204. }
  51205. /**
  51206. * Compress data. Concurrency limited.
  51207. *
  51208. * @param {Buffer} data Data to compress
  51209. * @param {Boolean} fin Specifies whether or not this is the last fragment
  51210. * @param {Function} callback Callback
  51211. * @public
  51212. */
  51213. compress(data, fin, callback) {
  51214. zlibLimiter.add((done) => {
  51215. this._compress(data, fin, (err, result) => {
  51216. done();
  51217. callback(err, result);
  51218. });
  51219. });
  51220. }
  51221. /**
  51222. * Decompress data.
  51223. *
  51224. * @param {Buffer} data Compressed data
  51225. * @param {Boolean} fin Specifies whether or not this is the last fragment
  51226. * @param {Function} callback Callback
  51227. * @private
  51228. */
  51229. _decompress(data, fin, callback) {
  51230. const endpoint = this._isServer ? 'client' : 'server';
  51231. if (!this._inflate) {
  51232. const key = `${endpoint}_max_window_bits`;
  51233. const windowBits =
  51234. typeof this.params[key] !== 'number'
  51235. ? zlib.Z_DEFAULT_WINDOWBITS
  51236. : this.params[key];
  51237. this._inflate = zlib.createInflateRaw({
  51238. ...this._options.zlibInflateOptions,
  51239. windowBits
  51240. });
  51241. this._inflate[kPerMessageDeflate] = this;
  51242. this._inflate[kTotalLength] = 0;
  51243. this._inflate[kBuffers] = [];
  51244. this._inflate.on('error', inflateOnError);
  51245. this._inflate.on('data', inflateOnData);
  51246. }
  51247. this._inflate[kCallback] = callback;
  51248. this._inflate.write(data);
  51249. if (fin) this._inflate.write(TRAILER);
  51250. this._inflate.flush(() => {
  51251. const err = this._inflate[kError];
  51252. if (err) {
  51253. this._inflate.close();
  51254. this._inflate = null;
  51255. callback(err);
  51256. return;
  51257. }
  51258. const data = bufferUtil.concat(
  51259. this._inflate[kBuffers],
  51260. this._inflate[kTotalLength]
  51261. );
  51262. if (this._inflate._readableState.endEmitted) {
  51263. this._inflate.close();
  51264. this._inflate = null;
  51265. } else {
  51266. this._inflate[kTotalLength] = 0;
  51267. this._inflate[kBuffers] = [];
  51268. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  51269. this._inflate.reset();
  51270. }
  51271. }
  51272. callback(null, data);
  51273. });
  51274. }
  51275. /**
  51276. * Compress data.
  51277. *
  51278. * @param {Buffer} data Data to compress
  51279. * @param {Boolean} fin Specifies whether or not this is the last fragment
  51280. * @param {Function} callback Callback
  51281. * @private
  51282. */
  51283. _compress(data, fin, callback) {
  51284. const endpoint = this._isServer ? 'server' : 'client';
  51285. if (!this._deflate) {
  51286. const key = `${endpoint}_max_window_bits`;
  51287. const windowBits =
  51288. typeof this.params[key] !== 'number'
  51289. ? zlib.Z_DEFAULT_WINDOWBITS
  51290. : this.params[key];
  51291. this._deflate = zlib.createDeflateRaw({
  51292. ...this._options.zlibDeflateOptions,
  51293. windowBits
  51294. });
  51295. this._deflate[kTotalLength] = 0;
  51296. this._deflate[kBuffers] = [];
  51297. //
  51298. // An `'error'` event is emitted, only on Node.js < 10.0.0, if the
  51299. // `zlib.DeflateRaw` instance is closed while data is being processed.
  51300. // This can happen if `PerMessageDeflate#cleanup()` is called at the wrong
  51301. // time due to an abnormal WebSocket closure.
  51302. //
  51303. this._deflate.on('error', NOOP$1);
  51304. this._deflate.on('data', deflateOnData);
  51305. }
  51306. this._deflate[kCallback] = callback;
  51307. this._deflate.write(data);
  51308. this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
  51309. if (!this._deflate) {
  51310. //
  51311. // The deflate stream was closed while data was being processed.
  51312. //
  51313. return;
  51314. }
  51315. let data = bufferUtil.concat(
  51316. this._deflate[kBuffers],
  51317. this._deflate[kTotalLength]
  51318. );
  51319. if (fin) data = data.slice(0, data.length - 4);
  51320. //
  51321. // Ensure that the callback will not be called again in
  51322. // `PerMessageDeflate#cleanup()`.
  51323. //
  51324. this._deflate[kCallback] = null;
  51325. this._deflate[kTotalLength] = 0;
  51326. this._deflate[kBuffers] = [];
  51327. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  51328. this._deflate.reset();
  51329. }
  51330. callback(null, data);
  51331. });
  51332. }
  51333. }
  51334. var permessageDeflate = PerMessageDeflate$4;
  51335. /**
  51336. * The listener of the `zlib.DeflateRaw` stream `'data'` event.
  51337. *
  51338. * @param {Buffer} chunk A chunk of data
  51339. * @private
  51340. */
  51341. function deflateOnData(chunk) {
  51342. this[kBuffers].push(chunk);
  51343. this[kTotalLength] += chunk.length;
  51344. }
  51345. /**
  51346. * The listener of the `zlib.InflateRaw` stream `'data'` event.
  51347. *
  51348. * @param {Buffer} chunk A chunk of data
  51349. * @private
  51350. */
  51351. function inflateOnData(chunk) {
  51352. this[kTotalLength] += chunk.length;
  51353. if (
  51354. this[kPerMessageDeflate]._maxPayload < 1 ||
  51355. this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
  51356. ) {
  51357. this[kBuffers].push(chunk);
  51358. return;
  51359. }
  51360. this[kError] = new RangeError('Max payload size exceeded');
  51361. this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
  51362. this[kError][kStatusCode$2] = 1009;
  51363. this.removeListener('data', inflateOnData);
  51364. this.reset();
  51365. }
  51366. /**
  51367. * The listener of the `zlib.InflateRaw` stream `'error'` event.
  51368. *
  51369. * @param {Error} err The emitted error
  51370. * @private
  51371. */
  51372. function inflateOnError(err) {
  51373. //
  51374. // There is no need to call `Zlib#close()` as the handle is automatically
  51375. // closed when an error is emitted.
  51376. //
  51377. this[kPerMessageDeflate]._inflate = null;
  51378. err[kStatusCode$2] = 1007;
  51379. this[kCallback](err);
  51380. }
  51381. var validation = {exports: {}};
  51382. /**
  51383. * Checks if a status code is allowed in a close frame.
  51384. *
  51385. * @param {Number} code The status code
  51386. * @return {Boolean} `true` if the status code is valid, else `false`
  51387. * @public
  51388. */
  51389. function isValidStatusCode$2(code) {
  51390. return (
  51391. (code >= 1000 &&
  51392. code <= 1014 &&
  51393. code !== 1004 &&
  51394. code !== 1005 &&
  51395. code !== 1006) ||
  51396. (code >= 3000 && code <= 4999)
  51397. );
  51398. }
  51399. /**
  51400. * Checks if a given buffer contains only correct UTF-8.
  51401. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
  51402. * Markus Kuhn.
  51403. *
  51404. * @param {Buffer} buf The buffer to check
  51405. * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
  51406. * @public
  51407. */
  51408. function _isValidUTF8(buf) {
  51409. const len = buf.length;
  51410. let i = 0;
  51411. while (i < len) {
  51412. if ((buf[i] & 0x80) === 0) {
  51413. // 0xxxxxxx
  51414. i++;
  51415. } else if ((buf[i] & 0xe0) === 0xc0) {
  51416. // 110xxxxx 10xxxxxx
  51417. if (
  51418. i + 1 === len ||
  51419. (buf[i + 1] & 0xc0) !== 0x80 ||
  51420. (buf[i] & 0xfe) === 0xc0 // Overlong
  51421. ) {
  51422. return false;
  51423. }
  51424. i += 2;
  51425. } else if ((buf[i] & 0xf0) === 0xe0) {
  51426. // 1110xxxx 10xxxxxx 10xxxxxx
  51427. if (
  51428. i + 2 >= len ||
  51429. (buf[i + 1] & 0xc0) !== 0x80 ||
  51430. (buf[i + 2] & 0xc0) !== 0x80 ||
  51431. (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
  51432. (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
  51433. ) {
  51434. return false;
  51435. }
  51436. i += 3;
  51437. } else if ((buf[i] & 0xf8) === 0xf0) {
  51438. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  51439. if (
  51440. i + 3 >= len ||
  51441. (buf[i + 1] & 0xc0) !== 0x80 ||
  51442. (buf[i + 2] & 0xc0) !== 0x80 ||
  51443. (buf[i + 3] & 0xc0) !== 0x80 ||
  51444. (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
  51445. (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
  51446. buf[i] > 0xf4 // > U+10FFFF
  51447. ) {
  51448. return false;
  51449. }
  51450. i += 4;
  51451. } else {
  51452. return false;
  51453. }
  51454. }
  51455. return true;
  51456. }
  51457. try {
  51458. let isValidUTF8 = require('utf-8-validate');
  51459. /* istanbul ignore if */
  51460. if (typeof isValidUTF8 === 'object') {
  51461. isValidUTF8 = isValidUTF8.Validation.isValidUTF8; // utf-8-validate@<3.0.0
  51462. }
  51463. validation.exports = {
  51464. isValidStatusCode: isValidStatusCode$2,
  51465. isValidUTF8(buf) {
  51466. return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf);
  51467. }
  51468. };
  51469. } catch (e) /* istanbul ignore next */ {
  51470. validation.exports = {
  51471. isValidStatusCode: isValidStatusCode$2,
  51472. isValidUTF8: _isValidUTF8
  51473. };
  51474. }
  51475. const { Writable: Writable$1 } = require$$0__default$2;
  51476. const PerMessageDeflate$3 = permessageDeflate;
  51477. const {
  51478. BINARY_TYPES: BINARY_TYPES$1,
  51479. EMPTY_BUFFER: EMPTY_BUFFER$2,
  51480. kStatusCode: kStatusCode$1,
  51481. kWebSocket: kWebSocket$2
  51482. } = constants;
  51483. const { concat, toArrayBuffer, unmask } = bufferUtil$1.exports;
  51484. const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validation.exports;
  51485. const GET_INFO = 0;
  51486. const GET_PAYLOAD_LENGTH_16 = 1;
  51487. const GET_PAYLOAD_LENGTH_64 = 2;
  51488. const GET_MASK = 3;
  51489. const GET_DATA = 4;
  51490. const INFLATING = 5;
  51491. /**
  51492. * HyBi Receiver implementation.
  51493. *
  51494. * @extends Writable
  51495. */
  51496. class Receiver$1 extends Writable$1 {
  51497. /**
  51498. * Creates a Receiver instance.
  51499. *
  51500. * @param {String} [binaryType=nodebuffer] The type for binary data
  51501. * @param {Object} [extensions] An object containing the negotiated extensions
  51502. * @param {Boolean} [isServer=false] Specifies whether to operate in client or
  51503. * server mode
  51504. * @param {Number} [maxPayload=0] The maximum allowed message length
  51505. */
  51506. constructor(binaryType, extensions, isServer, maxPayload) {
  51507. super();
  51508. this._binaryType = binaryType || BINARY_TYPES$1[0];
  51509. this[kWebSocket$2] = undefined;
  51510. this._extensions = extensions || {};
  51511. this._isServer = !!isServer;
  51512. this._maxPayload = maxPayload | 0;
  51513. this._bufferedBytes = 0;
  51514. this._buffers = [];
  51515. this._compressed = false;
  51516. this._payloadLength = 0;
  51517. this._mask = undefined;
  51518. this._fragmented = 0;
  51519. this._masked = false;
  51520. this._fin = false;
  51521. this._opcode = 0;
  51522. this._totalPayloadLength = 0;
  51523. this._messageLength = 0;
  51524. this._fragments = [];
  51525. this._state = GET_INFO;
  51526. this._loop = false;
  51527. }
  51528. /**
  51529. * Implements `Writable.prototype._write()`.
  51530. *
  51531. * @param {Buffer} chunk The chunk of data to write
  51532. * @param {String} encoding The character encoding of `chunk`
  51533. * @param {Function} cb Callback
  51534. * @private
  51535. */
  51536. _write(chunk, encoding, cb) {
  51537. if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
  51538. this._bufferedBytes += chunk.length;
  51539. this._buffers.push(chunk);
  51540. this.startLoop(cb);
  51541. }
  51542. /**
  51543. * Consumes `n` bytes from the buffered data.
  51544. *
  51545. * @param {Number} n The number of bytes to consume
  51546. * @return {Buffer} The consumed bytes
  51547. * @private
  51548. */
  51549. consume(n) {
  51550. this._bufferedBytes -= n;
  51551. if (n === this._buffers[0].length) return this._buffers.shift();
  51552. if (n < this._buffers[0].length) {
  51553. const buf = this._buffers[0];
  51554. this._buffers[0] = buf.slice(n);
  51555. return buf.slice(0, n);
  51556. }
  51557. const dst = Buffer.allocUnsafe(n);
  51558. do {
  51559. const buf = this._buffers[0];
  51560. const offset = dst.length - n;
  51561. if (n >= buf.length) {
  51562. dst.set(this._buffers.shift(), offset);
  51563. } else {
  51564. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
  51565. this._buffers[0] = buf.slice(n);
  51566. }
  51567. n -= buf.length;
  51568. } while (n > 0);
  51569. return dst;
  51570. }
  51571. /**
  51572. * Starts the parsing loop.
  51573. *
  51574. * @param {Function} cb Callback
  51575. * @private
  51576. */
  51577. startLoop(cb) {
  51578. let err;
  51579. this._loop = true;
  51580. do {
  51581. switch (this._state) {
  51582. case GET_INFO:
  51583. err = this.getInfo();
  51584. break;
  51585. case GET_PAYLOAD_LENGTH_16:
  51586. err = this.getPayloadLength16();
  51587. break;
  51588. case GET_PAYLOAD_LENGTH_64:
  51589. err = this.getPayloadLength64();
  51590. break;
  51591. case GET_MASK:
  51592. this.getMask();
  51593. break;
  51594. case GET_DATA:
  51595. err = this.getData(cb);
  51596. break;
  51597. default:
  51598. // `INFLATING`
  51599. this._loop = false;
  51600. return;
  51601. }
  51602. } while (this._loop);
  51603. cb(err);
  51604. }
  51605. /**
  51606. * Reads the first two bytes of a frame.
  51607. *
  51608. * @return {(RangeError|undefined)} A possible error
  51609. * @private
  51610. */
  51611. getInfo() {
  51612. if (this._bufferedBytes < 2) {
  51613. this._loop = false;
  51614. return;
  51615. }
  51616. const buf = this.consume(2);
  51617. if ((buf[0] & 0x30) !== 0x00) {
  51618. this._loop = false;
  51619. return error$2(
  51620. RangeError,
  51621. 'RSV2 and RSV3 must be clear',
  51622. true,
  51623. 1002,
  51624. 'WS_ERR_UNEXPECTED_RSV_2_3'
  51625. );
  51626. }
  51627. const compressed = (buf[0] & 0x40) === 0x40;
  51628. if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
  51629. this._loop = false;
  51630. return error$2(
  51631. RangeError,
  51632. 'RSV1 must be clear',
  51633. true,
  51634. 1002,
  51635. 'WS_ERR_UNEXPECTED_RSV_1'
  51636. );
  51637. }
  51638. this._fin = (buf[0] & 0x80) === 0x80;
  51639. this._opcode = buf[0] & 0x0f;
  51640. this._payloadLength = buf[1] & 0x7f;
  51641. if (this._opcode === 0x00) {
  51642. if (compressed) {
  51643. this._loop = false;
  51644. return error$2(
  51645. RangeError,
  51646. 'RSV1 must be clear',
  51647. true,
  51648. 1002,
  51649. 'WS_ERR_UNEXPECTED_RSV_1'
  51650. );
  51651. }
  51652. if (!this._fragmented) {
  51653. this._loop = false;
  51654. return error$2(
  51655. RangeError,
  51656. 'invalid opcode 0',
  51657. true,
  51658. 1002,
  51659. 'WS_ERR_INVALID_OPCODE'
  51660. );
  51661. }
  51662. this._opcode = this._fragmented;
  51663. } else if (this._opcode === 0x01 || this._opcode === 0x02) {
  51664. if (this._fragmented) {
  51665. this._loop = false;
  51666. return error$2(
  51667. RangeError,
  51668. `invalid opcode ${this._opcode}`,
  51669. true,
  51670. 1002,
  51671. 'WS_ERR_INVALID_OPCODE'
  51672. );
  51673. }
  51674. this._compressed = compressed;
  51675. } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
  51676. if (!this._fin) {
  51677. this._loop = false;
  51678. return error$2(
  51679. RangeError,
  51680. 'FIN must be set',
  51681. true,
  51682. 1002,
  51683. 'WS_ERR_EXPECTED_FIN'
  51684. );
  51685. }
  51686. if (compressed) {
  51687. this._loop = false;
  51688. return error$2(
  51689. RangeError,
  51690. 'RSV1 must be clear',
  51691. true,
  51692. 1002,
  51693. 'WS_ERR_UNEXPECTED_RSV_1'
  51694. );
  51695. }
  51696. if (this._payloadLength > 0x7d) {
  51697. this._loop = false;
  51698. return error$2(
  51699. RangeError,
  51700. `invalid payload length ${this._payloadLength}`,
  51701. true,
  51702. 1002,
  51703. 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
  51704. );
  51705. }
  51706. } else {
  51707. this._loop = false;
  51708. return error$2(
  51709. RangeError,
  51710. `invalid opcode ${this._opcode}`,
  51711. true,
  51712. 1002,
  51713. 'WS_ERR_INVALID_OPCODE'
  51714. );
  51715. }
  51716. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  51717. this._masked = (buf[1] & 0x80) === 0x80;
  51718. if (this._isServer) {
  51719. if (!this._masked) {
  51720. this._loop = false;
  51721. return error$2(
  51722. RangeError,
  51723. 'MASK must be set',
  51724. true,
  51725. 1002,
  51726. 'WS_ERR_EXPECTED_MASK'
  51727. );
  51728. }
  51729. } else if (this._masked) {
  51730. this._loop = false;
  51731. return error$2(
  51732. RangeError,
  51733. 'MASK must be clear',
  51734. true,
  51735. 1002,
  51736. 'WS_ERR_UNEXPECTED_MASK'
  51737. );
  51738. }
  51739. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  51740. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  51741. else return this.haveLength();
  51742. }
  51743. /**
  51744. * Gets extended payload length (7+16).
  51745. *
  51746. * @return {(RangeError|undefined)} A possible error
  51747. * @private
  51748. */
  51749. getPayloadLength16() {
  51750. if (this._bufferedBytes < 2) {
  51751. this._loop = false;
  51752. return;
  51753. }
  51754. this._payloadLength = this.consume(2).readUInt16BE(0);
  51755. return this.haveLength();
  51756. }
  51757. /**
  51758. * Gets extended payload length (7+64).
  51759. *
  51760. * @return {(RangeError|undefined)} A possible error
  51761. * @private
  51762. */
  51763. getPayloadLength64() {
  51764. if (this._bufferedBytes < 8) {
  51765. this._loop = false;
  51766. return;
  51767. }
  51768. const buf = this.consume(8);
  51769. const num = buf.readUInt32BE(0);
  51770. //
  51771. // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
  51772. // if payload length is greater than this number.
  51773. //
  51774. if (num > Math.pow(2, 53 - 32) - 1) {
  51775. this._loop = false;
  51776. return error$2(
  51777. RangeError,
  51778. 'Unsupported WebSocket frame: payload length > 2^53 - 1',
  51779. false,
  51780. 1009,
  51781. 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
  51782. );
  51783. }
  51784. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  51785. return this.haveLength();
  51786. }
  51787. /**
  51788. * Payload length has been read.
  51789. *
  51790. * @return {(RangeError|undefined)} A possible error
  51791. * @private
  51792. */
  51793. haveLength() {
  51794. if (this._payloadLength && this._opcode < 0x08) {
  51795. this._totalPayloadLength += this._payloadLength;
  51796. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  51797. this._loop = false;
  51798. return error$2(
  51799. RangeError,
  51800. 'Max payload size exceeded',
  51801. false,
  51802. 1009,
  51803. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  51804. );
  51805. }
  51806. }
  51807. if (this._masked) this._state = GET_MASK;
  51808. else this._state = GET_DATA;
  51809. }
  51810. /**
  51811. * Reads mask bytes.
  51812. *
  51813. * @private
  51814. */
  51815. getMask() {
  51816. if (this._bufferedBytes < 4) {
  51817. this._loop = false;
  51818. return;
  51819. }
  51820. this._mask = this.consume(4);
  51821. this._state = GET_DATA;
  51822. }
  51823. /**
  51824. * Reads data bytes.
  51825. *
  51826. * @param {Function} cb Callback
  51827. * @return {(Error|RangeError|undefined)} A possible error
  51828. * @private
  51829. */
  51830. getData(cb) {
  51831. let data = EMPTY_BUFFER$2;
  51832. if (this._payloadLength) {
  51833. if (this._bufferedBytes < this._payloadLength) {
  51834. this._loop = false;
  51835. return;
  51836. }
  51837. data = this.consume(this._payloadLength);
  51838. if (this._masked) unmask(data, this._mask);
  51839. }
  51840. if (this._opcode > 0x07) return this.controlMessage(data);
  51841. if (this._compressed) {
  51842. this._state = INFLATING;
  51843. this.decompress(data, cb);
  51844. return;
  51845. }
  51846. if (data.length) {
  51847. //
  51848. // This message is not compressed so its lenght is the sum of the payload
  51849. // length of all fragments.
  51850. //
  51851. this._messageLength = this._totalPayloadLength;
  51852. this._fragments.push(data);
  51853. }
  51854. return this.dataMessage();
  51855. }
  51856. /**
  51857. * Decompresses data.
  51858. *
  51859. * @param {Buffer} data Compressed data
  51860. * @param {Function} cb Callback
  51861. * @private
  51862. */
  51863. decompress(data, cb) {
  51864. const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName];
  51865. perMessageDeflate.decompress(data, this._fin, (err, buf) => {
  51866. if (err) return cb(err);
  51867. if (buf.length) {
  51868. this._messageLength += buf.length;
  51869. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  51870. return cb(
  51871. error$2(
  51872. RangeError,
  51873. 'Max payload size exceeded',
  51874. false,
  51875. 1009,
  51876. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  51877. )
  51878. );
  51879. }
  51880. this._fragments.push(buf);
  51881. }
  51882. const er = this.dataMessage();
  51883. if (er) return cb(er);
  51884. this.startLoop(cb);
  51885. });
  51886. }
  51887. /**
  51888. * Handles a data message.
  51889. *
  51890. * @return {(Error|undefined)} A possible error
  51891. * @private
  51892. */
  51893. dataMessage() {
  51894. if (this._fin) {
  51895. const messageLength = this._messageLength;
  51896. const fragments = this._fragments;
  51897. this._totalPayloadLength = 0;
  51898. this._messageLength = 0;
  51899. this._fragmented = 0;
  51900. this._fragments = [];
  51901. if (this._opcode === 2) {
  51902. let data;
  51903. if (this._binaryType === 'nodebuffer') {
  51904. data = concat(fragments, messageLength);
  51905. } else if (this._binaryType === 'arraybuffer') {
  51906. data = toArrayBuffer(concat(fragments, messageLength));
  51907. } else {
  51908. data = fragments;
  51909. }
  51910. this.emit('message', data);
  51911. } else {
  51912. const buf = concat(fragments, messageLength);
  51913. if (!isValidUTF8(buf)) {
  51914. this._loop = false;
  51915. return error$2(
  51916. Error,
  51917. 'invalid UTF-8 sequence',
  51918. true,
  51919. 1007,
  51920. 'WS_ERR_INVALID_UTF8'
  51921. );
  51922. }
  51923. this.emit('message', buf.toString());
  51924. }
  51925. }
  51926. this._state = GET_INFO;
  51927. }
  51928. /**
  51929. * Handles a control message.
  51930. *
  51931. * @param {Buffer} data Data to handle
  51932. * @return {(Error|RangeError|undefined)} A possible error
  51933. * @private
  51934. */
  51935. controlMessage(data) {
  51936. if (this._opcode === 0x08) {
  51937. this._loop = false;
  51938. if (data.length === 0) {
  51939. this.emit('conclude', 1005, '');
  51940. this.end();
  51941. } else if (data.length === 1) {
  51942. return error$2(
  51943. RangeError,
  51944. 'invalid payload length 1',
  51945. true,
  51946. 1002,
  51947. 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
  51948. );
  51949. } else {
  51950. const code = data.readUInt16BE(0);
  51951. if (!isValidStatusCode$1(code)) {
  51952. return error$2(
  51953. RangeError,
  51954. `invalid status code ${code}`,
  51955. true,
  51956. 1002,
  51957. 'WS_ERR_INVALID_CLOSE_CODE'
  51958. );
  51959. }
  51960. const buf = data.slice(2);
  51961. if (!isValidUTF8(buf)) {
  51962. return error$2(
  51963. Error,
  51964. 'invalid UTF-8 sequence',
  51965. true,
  51966. 1007,
  51967. 'WS_ERR_INVALID_UTF8'
  51968. );
  51969. }
  51970. this.emit('conclude', code, buf.toString());
  51971. this.end();
  51972. }
  51973. } else if (this._opcode === 0x09) {
  51974. this.emit('ping', data);
  51975. } else {
  51976. this.emit('pong', data);
  51977. }
  51978. this._state = GET_INFO;
  51979. }
  51980. }
  51981. var receiver = Receiver$1;
  51982. /**
  51983. * Builds an error object.
  51984. *
  51985. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  51986. * @param {String} message The error message
  51987. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  51988. * `message`
  51989. * @param {Number} statusCode The status code
  51990. * @param {String} errorCode The exposed error code
  51991. * @return {(Error|RangeError)} The error
  51992. * @private
  51993. */
  51994. function error$2(ErrorCtor, message, prefix, statusCode, errorCode) {
  51995. const err = new ErrorCtor(
  51996. prefix ? `Invalid WebSocket frame: ${message}` : message
  51997. );
  51998. Error.captureStackTrace(err, error$2);
  51999. err.code = errorCode;
  52000. err[kStatusCode$1] = statusCode;
  52001. return err;
  52002. }
  52003. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */
  52004. const { randomFillSync } = require$$1__default$2;
  52005. const PerMessageDeflate$2 = permessageDeflate;
  52006. const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants;
  52007. const { isValidStatusCode } = validation.exports;
  52008. const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtil$1.exports;
  52009. const mask = Buffer.alloc(4);
  52010. /**
  52011. * HyBi Sender implementation.
  52012. */
  52013. class Sender$1 {
  52014. /**
  52015. * Creates a Sender instance.
  52016. *
  52017. * @param {(net.Socket|tls.Socket)} socket The connection socket
  52018. * @param {Object} [extensions] An object containing the negotiated extensions
  52019. */
  52020. constructor(socket, extensions) {
  52021. this._extensions = extensions || {};
  52022. this._socket = socket;
  52023. this._firstFragment = true;
  52024. this._compress = false;
  52025. this._bufferedBytes = 0;
  52026. this._deflating = false;
  52027. this._queue = [];
  52028. }
  52029. /**
  52030. * Frames a piece of data according to the HyBi WebSocket protocol.
  52031. *
  52032. * @param {Buffer} data The data to frame
  52033. * @param {Object} options Options object
  52034. * @param {Number} options.opcode The opcode
  52035. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  52036. * modified
  52037. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  52038. * FIN bit
  52039. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  52040. * `data`
  52041. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  52042. * RSV1 bit
  52043. * @return {Buffer[]} The framed data as a list of `Buffer` instances
  52044. * @public
  52045. */
  52046. static frame(data, options) {
  52047. const merge = options.mask && options.readOnly;
  52048. let offset = options.mask ? 6 : 2;
  52049. let payloadLength = data.length;
  52050. if (data.length >= 65536) {
  52051. offset += 8;
  52052. payloadLength = 127;
  52053. } else if (data.length > 125) {
  52054. offset += 2;
  52055. payloadLength = 126;
  52056. }
  52057. const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
  52058. target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
  52059. if (options.rsv1) target[0] |= 0x40;
  52060. target[1] = payloadLength;
  52061. if (payloadLength === 126) {
  52062. target.writeUInt16BE(data.length, 2);
  52063. } else if (payloadLength === 127) {
  52064. target.writeUInt32BE(0, 2);
  52065. target.writeUInt32BE(data.length, 6);
  52066. }
  52067. if (!options.mask) return [target, data];
  52068. randomFillSync(mask, 0, 4);
  52069. target[1] |= 0x80;
  52070. target[offset - 4] = mask[0];
  52071. target[offset - 3] = mask[1];
  52072. target[offset - 2] = mask[2];
  52073. target[offset - 1] = mask[3];
  52074. if (merge) {
  52075. applyMask(data, mask, target, offset, data.length);
  52076. return [target];
  52077. }
  52078. applyMask(data, mask, data, 0, data.length);
  52079. return [target, data];
  52080. }
  52081. /**
  52082. * Sends a close message to the other peer.
  52083. *
  52084. * @param {Number} [code] The status code component of the body
  52085. * @param {String} [data] The message component of the body
  52086. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  52087. * @param {Function} [cb] Callback
  52088. * @public
  52089. */
  52090. close(code, data, mask, cb) {
  52091. let buf;
  52092. if (code === undefined) {
  52093. buf = EMPTY_BUFFER$1;
  52094. } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
  52095. throw new TypeError('First argument must be a valid error code number');
  52096. } else if (data === undefined || data === '') {
  52097. buf = Buffer.allocUnsafe(2);
  52098. buf.writeUInt16BE(code, 0);
  52099. } else {
  52100. const length = Buffer.byteLength(data);
  52101. if (length > 123) {
  52102. throw new RangeError('The message must not be greater than 123 bytes');
  52103. }
  52104. buf = Buffer.allocUnsafe(2 + length);
  52105. buf.writeUInt16BE(code, 0);
  52106. buf.write(data, 2);
  52107. }
  52108. if (this._deflating) {
  52109. this.enqueue([this.doClose, buf, mask, cb]);
  52110. } else {
  52111. this.doClose(buf, mask, cb);
  52112. }
  52113. }
  52114. /**
  52115. * Frames and sends a close message.
  52116. *
  52117. * @param {Buffer} data The message to send
  52118. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  52119. * @param {Function} [cb] Callback
  52120. * @private
  52121. */
  52122. doClose(data, mask, cb) {
  52123. this.sendFrame(
  52124. Sender$1.frame(data, {
  52125. fin: true,
  52126. rsv1: false,
  52127. opcode: 0x08,
  52128. mask,
  52129. readOnly: false
  52130. }),
  52131. cb
  52132. );
  52133. }
  52134. /**
  52135. * Sends a ping message to the other peer.
  52136. *
  52137. * @param {*} data The message to send
  52138. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  52139. * @param {Function} [cb] Callback
  52140. * @public
  52141. */
  52142. ping(data, mask, cb) {
  52143. const buf = toBuffer$1(data);
  52144. if (buf.length > 125) {
  52145. throw new RangeError('The data size must not be greater than 125 bytes');
  52146. }
  52147. if (this._deflating) {
  52148. this.enqueue([this.doPing, buf, mask, toBuffer$1.readOnly, cb]);
  52149. } else {
  52150. this.doPing(buf, mask, toBuffer$1.readOnly, cb);
  52151. }
  52152. }
  52153. /**
  52154. * Frames and sends a ping message.
  52155. *
  52156. * @param {Buffer} data The message to send
  52157. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  52158. * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified
  52159. * @param {Function} [cb] Callback
  52160. * @private
  52161. */
  52162. doPing(data, mask, readOnly, cb) {
  52163. this.sendFrame(
  52164. Sender$1.frame(data, {
  52165. fin: true,
  52166. rsv1: false,
  52167. opcode: 0x09,
  52168. mask,
  52169. readOnly
  52170. }),
  52171. cb
  52172. );
  52173. }
  52174. /**
  52175. * Sends a pong message to the other peer.
  52176. *
  52177. * @param {*} data The message to send
  52178. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  52179. * @param {Function} [cb] Callback
  52180. * @public
  52181. */
  52182. pong(data, mask, cb) {
  52183. const buf = toBuffer$1(data);
  52184. if (buf.length > 125) {
  52185. throw new RangeError('The data size must not be greater than 125 bytes');
  52186. }
  52187. if (this._deflating) {
  52188. this.enqueue([this.doPong, buf, mask, toBuffer$1.readOnly, cb]);
  52189. } else {
  52190. this.doPong(buf, mask, toBuffer$1.readOnly, cb);
  52191. }
  52192. }
  52193. /**
  52194. * Frames and sends a pong message.
  52195. *
  52196. * @param {Buffer} data The message to send
  52197. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  52198. * @param {Boolean} [readOnly=false] Specifies whether `data` can be modified
  52199. * @param {Function} [cb] Callback
  52200. * @private
  52201. */
  52202. doPong(data, mask, readOnly, cb) {
  52203. this.sendFrame(
  52204. Sender$1.frame(data, {
  52205. fin: true,
  52206. rsv1: false,
  52207. opcode: 0x0a,
  52208. mask,
  52209. readOnly
  52210. }),
  52211. cb
  52212. );
  52213. }
  52214. /**
  52215. * Sends a data message to the other peer.
  52216. *
  52217. * @param {*} data The message to send
  52218. * @param {Object} options Options object
  52219. * @param {Boolean} [options.compress=false] Specifies whether or not to
  52220. * compress `data`
  52221. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  52222. * or text
  52223. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  52224. * last one
  52225. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  52226. * `data`
  52227. * @param {Function} [cb] Callback
  52228. * @public
  52229. */
  52230. send(data, options, cb) {
  52231. const buf = toBuffer$1(data);
  52232. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  52233. let opcode = options.binary ? 2 : 1;
  52234. let rsv1 = options.compress;
  52235. if (this._firstFragment) {
  52236. this._firstFragment = false;
  52237. if (rsv1 && perMessageDeflate) {
  52238. rsv1 = buf.length >= perMessageDeflate._threshold;
  52239. }
  52240. this._compress = rsv1;
  52241. } else {
  52242. rsv1 = false;
  52243. opcode = 0;
  52244. }
  52245. if (options.fin) this._firstFragment = true;
  52246. if (perMessageDeflate) {
  52247. const opts = {
  52248. fin: options.fin,
  52249. rsv1,
  52250. opcode,
  52251. mask: options.mask,
  52252. readOnly: toBuffer$1.readOnly
  52253. };
  52254. if (this._deflating) {
  52255. this.enqueue([this.dispatch, buf, this._compress, opts, cb]);
  52256. } else {
  52257. this.dispatch(buf, this._compress, opts, cb);
  52258. }
  52259. } else {
  52260. this.sendFrame(
  52261. Sender$1.frame(buf, {
  52262. fin: options.fin,
  52263. rsv1: false,
  52264. opcode,
  52265. mask: options.mask,
  52266. readOnly: toBuffer$1.readOnly
  52267. }),
  52268. cb
  52269. );
  52270. }
  52271. }
  52272. /**
  52273. * Dispatches a data message.
  52274. *
  52275. * @param {Buffer} data The message to send
  52276. * @param {Boolean} [compress=false] Specifies whether or not to compress
  52277. * `data`
  52278. * @param {Object} options Options object
  52279. * @param {Number} options.opcode The opcode
  52280. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  52281. * modified
  52282. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  52283. * FIN bit
  52284. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  52285. * `data`
  52286. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  52287. * RSV1 bit
  52288. * @param {Function} [cb] Callback
  52289. * @private
  52290. */
  52291. dispatch(data, compress, options, cb) {
  52292. if (!compress) {
  52293. this.sendFrame(Sender$1.frame(data, options), cb);
  52294. return;
  52295. }
  52296. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  52297. this._bufferedBytes += data.length;
  52298. this._deflating = true;
  52299. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  52300. if (this._socket.destroyed) {
  52301. const err = new Error(
  52302. 'The socket was closed while data was being compressed'
  52303. );
  52304. if (typeof cb === 'function') cb(err);
  52305. for (let i = 0; i < this._queue.length; i++) {
  52306. const callback = this._queue[i][4];
  52307. if (typeof callback === 'function') callback(err);
  52308. }
  52309. return;
  52310. }
  52311. this._bufferedBytes -= data.length;
  52312. this._deflating = false;
  52313. options.readOnly = false;
  52314. this.sendFrame(Sender$1.frame(buf, options), cb);
  52315. this.dequeue();
  52316. });
  52317. }
  52318. /**
  52319. * Executes queued send operations.
  52320. *
  52321. * @private
  52322. */
  52323. dequeue() {
  52324. while (!this._deflating && this._queue.length) {
  52325. const params = this._queue.shift();
  52326. this._bufferedBytes -= params[1].length;
  52327. Reflect.apply(params[0], this, params.slice(1));
  52328. }
  52329. }
  52330. /**
  52331. * Enqueues a send operation.
  52332. *
  52333. * @param {Array} params Send operation parameters.
  52334. * @private
  52335. */
  52336. enqueue(params) {
  52337. this._bufferedBytes += params[1].length;
  52338. this._queue.push(params);
  52339. }
  52340. /**
  52341. * Sends a frame.
  52342. *
  52343. * @param {Buffer[]} list The frame to send
  52344. * @param {Function} [cb] Callback
  52345. * @private
  52346. */
  52347. sendFrame(list, cb) {
  52348. if (list.length === 2) {
  52349. this._socket.cork();
  52350. this._socket.write(list[0]);
  52351. this._socket.write(list[1], cb);
  52352. this._socket.uncork();
  52353. } else {
  52354. this._socket.write(list[0], cb);
  52355. }
  52356. }
  52357. }
  52358. var sender = Sender$1;
  52359. /**
  52360. * Class representing an event.
  52361. *
  52362. * @private
  52363. */
  52364. class Event {
  52365. /**
  52366. * Create a new `Event`.
  52367. *
  52368. * @param {String} type The name of the event
  52369. * @param {Object} target A reference to the target to which the event was
  52370. * dispatched
  52371. */
  52372. constructor(type, target) {
  52373. this.target = target;
  52374. this.type = type;
  52375. }
  52376. }
  52377. /**
  52378. * Class representing a message event.
  52379. *
  52380. * @extends Event
  52381. * @private
  52382. */
  52383. class MessageEvent extends Event {
  52384. /**
  52385. * Create a new `MessageEvent`.
  52386. *
  52387. * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data
  52388. * @param {WebSocket} target A reference to the target to which the event was
  52389. * dispatched
  52390. */
  52391. constructor(data, target) {
  52392. super('message', target);
  52393. this.data = data;
  52394. }
  52395. }
  52396. /**
  52397. * Class representing a close event.
  52398. *
  52399. * @extends Event
  52400. * @private
  52401. */
  52402. class CloseEvent extends Event {
  52403. /**
  52404. * Create a new `CloseEvent`.
  52405. *
  52406. * @param {Number} code The status code explaining why the connection is being
  52407. * closed
  52408. * @param {String} reason A human-readable string explaining why the
  52409. * connection is closing
  52410. * @param {WebSocket} target A reference to the target to which the event was
  52411. * dispatched
  52412. */
  52413. constructor(code, reason, target) {
  52414. super('close', target);
  52415. this.wasClean = target._closeFrameReceived && target._closeFrameSent;
  52416. this.reason = reason;
  52417. this.code = code;
  52418. }
  52419. }
  52420. /**
  52421. * Class representing an open event.
  52422. *
  52423. * @extends Event
  52424. * @private
  52425. */
  52426. class OpenEvent extends Event {
  52427. /**
  52428. * Create a new `OpenEvent`.
  52429. *
  52430. * @param {WebSocket} target A reference to the target to which the event was
  52431. * dispatched
  52432. */
  52433. constructor(target) {
  52434. super('open', target);
  52435. }
  52436. }
  52437. /**
  52438. * Class representing an error event.
  52439. *
  52440. * @extends Event
  52441. * @private
  52442. */
  52443. class ErrorEvent extends Event {
  52444. /**
  52445. * Create a new `ErrorEvent`.
  52446. *
  52447. * @param {Object} error The error that generated this event
  52448. * @param {WebSocket} target A reference to the target to which the event was
  52449. * dispatched
  52450. */
  52451. constructor(error, target) {
  52452. super('error', target);
  52453. this.message = error.message;
  52454. this.error = error;
  52455. }
  52456. }
  52457. /**
  52458. * This provides methods for emulating the `EventTarget` interface. It's not
  52459. * meant to be used directly.
  52460. *
  52461. * @mixin
  52462. */
  52463. const EventTarget = {
  52464. /**
  52465. * Register an event listener.
  52466. *
  52467. * @param {String} type A string representing the event type to listen for
  52468. * @param {Function} listener The listener to add
  52469. * @param {Object} [options] An options object specifies characteristics about
  52470. * the event listener
  52471. * @param {Boolean} [options.once=false] A `Boolean`` indicating that the
  52472. * listener should be invoked at most once after being added. If `true`,
  52473. * the listener would be automatically removed when invoked.
  52474. * @public
  52475. */
  52476. addEventListener(type, listener, options) {
  52477. if (typeof listener !== 'function') return;
  52478. function onMessage(data) {
  52479. listener.call(this, new MessageEvent(data, this));
  52480. }
  52481. function onClose(code, message) {
  52482. listener.call(this, new CloseEvent(code, message, this));
  52483. }
  52484. function onError(error) {
  52485. listener.call(this, new ErrorEvent(error, this));
  52486. }
  52487. function onOpen() {
  52488. listener.call(this, new OpenEvent(this));
  52489. }
  52490. const method = options && options.once ? 'once' : 'on';
  52491. if (type === 'message') {
  52492. onMessage._listener = listener;
  52493. this[method](type, onMessage);
  52494. } else if (type === 'close') {
  52495. onClose._listener = listener;
  52496. this[method](type, onClose);
  52497. } else if (type === 'error') {
  52498. onError._listener = listener;
  52499. this[method](type, onError);
  52500. } else if (type === 'open') {
  52501. onOpen._listener = listener;
  52502. this[method](type, onOpen);
  52503. } else {
  52504. this[method](type, listener);
  52505. }
  52506. },
  52507. /**
  52508. * Remove an event listener.
  52509. *
  52510. * @param {String} type A string representing the event type to remove
  52511. * @param {Function} listener The listener to remove
  52512. * @public
  52513. */
  52514. removeEventListener(type, listener) {
  52515. const listeners = this.listeners(type);
  52516. for (let i = 0; i < listeners.length; i++) {
  52517. if (listeners[i] === listener || listeners[i]._listener === listener) {
  52518. this.removeListener(type, listeners[i]);
  52519. }
  52520. }
  52521. }
  52522. };
  52523. var eventTarget = EventTarget;
  52524. //
  52525. // Allowed token characters:
  52526. //
  52527. // '!', '#', '$', '%', '&', ''', '*', '+', '-',
  52528. // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
  52529. //
  52530. // tokenChars[32] === 0 // ' '
  52531. // tokenChars[33] === 1 // '!'
  52532. // tokenChars[34] === 0 // '"'
  52533. // ...
  52534. //
  52535. // prettier-ignore
  52536. const tokenChars = [
  52537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
  52538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
  52539. 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
  52540. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
  52541. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
  52542. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
  52543. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
  52544. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
  52545. ];
  52546. /**
  52547. * Adds an offer to the map of extension offers or a parameter to the map of
  52548. * parameters.
  52549. *
  52550. * @param {Object} dest The map of extension offers or parameters
  52551. * @param {String} name The extension or parameter name
  52552. * @param {(Object|Boolean|String)} elem The extension parameters or the
  52553. * parameter value
  52554. * @private
  52555. */
  52556. function push(dest, name, elem) {
  52557. if (dest[name] === undefined) dest[name] = [elem];
  52558. else dest[name].push(elem);
  52559. }
  52560. /**
  52561. * Parses the `Sec-WebSocket-Extensions` header into an object.
  52562. *
  52563. * @param {String} header The field value of the header
  52564. * @return {Object} The parsed object
  52565. * @public
  52566. */
  52567. function parse$7(header) {
  52568. const offers = Object.create(null);
  52569. if (header === undefined || header === '') return offers;
  52570. let params = Object.create(null);
  52571. let mustUnescape = false;
  52572. let isEscaping = false;
  52573. let inQuotes = false;
  52574. let extensionName;
  52575. let paramName;
  52576. let start = -1;
  52577. let end = -1;
  52578. let i = 0;
  52579. for (; i < header.length; i++) {
  52580. const code = header.charCodeAt(i);
  52581. if (extensionName === undefined) {
  52582. if (end === -1 && tokenChars[code] === 1) {
  52583. if (start === -1) start = i;
  52584. } else if (code === 0x20 /* ' ' */ || code === 0x09 /* '\t' */) {
  52585. if (end === -1 && start !== -1) end = i;
  52586. } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
  52587. if (start === -1) {
  52588. throw new SyntaxError(`Unexpected character at index ${i}`);
  52589. }
  52590. if (end === -1) end = i;
  52591. const name = header.slice(start, end);
  52592. if (code === 0x2c) {
  52593. push(offers, name, params);
  52594. params = Object.create(null);
  52595. } else {
  52596. extensionName = name;
  52597. }
  52598. start = end = -1;
  52599. } else {
  52600. throw new SyntaxError(`Unexpected character at index ${i}`);
  52601. }
  52602. } else if (paramName === undefined) {
  52603. if (end === -1 && tokenChars[code] === 1) {
  52604. if (start === -1) start = i;
  52605. } else if (code === 0x20 || code === 0x09) {
  52606. if (end === -1 && start !== -1) end = i;
  52607. } else if (code === 0x3b || code === 0x2c) {
  52608. if (start === -1) {
  52609. throw new SyntaxError(`Unexpected character at index ${i}`);
  52610. }
  52611. if (end === -1) end = i;
  52612. push(params, header.slice(start, end), true);
  52613. if (code === 0x2c) {
  52614. push(offers, extensionName, params);
  52615. params = Object.create(null);
  52616. extensionName = undefined;
  52617. }
  52618. start = end = -1;
  52619. } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
  52620. paramName = header.slice(start, i);
  52621. start = end = -1;
  52622. } else {
  52623. throw new SyntaxError(`Unexpected character at index ${i}`);
  52624. }
  52625. } else {
  52626. //
  52627. // The value of a quoted-string after unescaping must conform to the
  52628. // token ABNF, so only token characters are valid.
  52629. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
  52630. //
  52631. if (isEscaping) {
  52632. if (tokenChars[code] !== 1) {
  52633. throw new SyntaxError(`Unexpected character at index ${i}`);
  52634. }
  52635. if (start === -1) start = i;
  52636. else if (!mustUnescape) mustUnescape = true;
  52637. isEscaping = false;
  52638. } else if (inQuotes) {
  52639. if (tokenChars[code] === 1) {
  52640. if (start === -1) start = i;
  52641. } else if (code === 0x22 /* '"' */ && start !== -1) {
  52642. inQuotes = false;
  52643. end = i;
  52644. } else if (code === 0x5c /* '\' */) {
  52645. isEscaping = true;
  52646. } else {
  52647. throw new SyntaxError(`Unexpected character at index ${i}`);
  52648. }
  52649. } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
  52650. inQuotes = true;
  52651. } else if (end === -1 && tokenChars[code] === 1) {
  52652. if (start === -1) start = i;
  52653. } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
  52654. if (end === -1) end = i;
  52655. } else if (code === 0x3b || code === 0x2c) {
  52656. if (start === -1) {
  52657. throw new SyntaxError(`Unexpected character at index ${i}`);
  52658. }
  52659. if (end === -1) end = i;
  52660. let value = header.slice(start, end);
  52661. if (mustUnescape) {
  52662. value = value.replace(/\\/g, '');
  52663. mustUnescape = false;
  52664. }
  52665. push(params, paramName, value);
  52666. if (code === 0x2c) {
  52667. push(offers, extensionName, params);
  52668. params = Object.create(null);
  52669. extensionName = undefined;
  52670. }
  52671. paramName = undefined;
  52672. start = end = -1;
  52673. } else {
  52674. throw new SyntaxError(`Unexpected character at index ${i}`);
  52675. }
  52676. }
  52677. }
  52678. if (start === -1 || inQuotes) {
  52679. throw new SyntaxError('Unexpected end of input');
  52680. }
  52681. if (end === -1) end = i;
  52682. const token = header.slice(start, end);
  52683. if (extensionName === undefined) {
  52684. push(offers, token, params);
  52685. } else {
  52686. if (paramName === undefined) {
  52687. push(params, token, true);
  52688. } else if (mustUnescape) {
  52689. push(params, paramName, token.replace(/\\/g, ''));
  52690. } else {
  52691. push(params, paramName, token);
  52692. }
  52693. push(offers, extensionName, params);
  52694. }
  52695. return offers;
  52696. }
  52697. /**
  52698. * Builds the `Sec-WebSocket-Extensions` header field value.
  52699. *
  52700. * @param {Object} extensions The map of extensions and parameters to format
  52701. * @return {String} A string representing the given object
  52702. * @public
  52703. */
  52704. function format$2(extensions) {
  52705. return Object.keys(extensions)
  52706. .map((extension) => {
  52707. let configurations = extensions[extension];
  52708. if (!Array.isArray(configurations)) configurations = [configurations];
  52709. return configurations
  52710. .map((params) => {
  52711. return [extension]
  52712. .concat(
  52713. Object.keys(params).map((k) => {
  52714. let values = params[k];
  52715. if (!Array.isArray(values)) values = [values];
  52716. return values
  52717. .map((v) => (v === true ? k : `${k}=${v}`))
  52718. .join('; ');
  52719. })
  52720. )
  52721. .join('; ');
  52722. })
  52723. .join(', ');
  52724. })
  52725. .join(', ');
  52726. }
  52727. var extension = { format: format$2, parse: parse$7 };
  52728. const EventEmitter$1 = require$$0__default$6;
  52729. const https$2 = require$$1__default$3;
  52730. const http$3 = require$$1__default$1;
  52731. const net = require$$4__default$1;
  52732. const tls = require$$4__default$2;
  52733. const { randomBytes, createHash: createHash$1 } = require$$1__default$2;
  52734. const { URL: URL$2 } = require$$0__default$7;
  52735. const PerMessageDeflate$1 = permessageDeflate;
  52736. const Receiver = receiver;
  52737. const Sender = sender;
  52738. const {
  52739. BINARY_TYPES,
  52740. EMPTY_BUFFER,
  52741. GUID: GUID$1,
  52742. kStatusCode,
  52743. kWebSocket: kWebSocket$1,
  52744. NOOP
  52745. } = constants;
  52746. const { addEventListener, removeEventListener } = eventTarget;
  52747. const { format: format$1, parse: parse$6 } = extension;
  52748. const { toBuffer } = bufferUtil$1.exports;
  52749. const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
  52750. const protocolVersions = [8, 13];
  52751. const closeTimeout = 30 * 1000;
  52752. /**
  52753. * Class representing a WebSocket.
  52754. *
  52755. * @extends EventEmitter
  52756. */
  52757. class WebSocket$2 extends EventEmitter$1 {
  52758. /**
  52759. * Create a new `WebSocket`.
  52760. *
  52761. * @param {(String|URL)} address The URL to which to connect
  52762. * @param {(String|String[])} [protocols] The subprotocols
  52763. * @param {Object} [options] Connection options
  52764. */
  52765. constructor(address, protocols, options) {
  52766. super();
  52767. this._binaryType = BINARY_TYPES[0];
  52768. this._closeCode = 1006;
  52769. this._closeFrameReceived = false;
  52770. this._closeFrameSent = false;
  52771. this._closeMessage = '';
  52772. this._closeTimer = null;
  52773. this._extensions = {};
  52774. this._protocol = '';
  52775. this._readyState = WebSocket$2.CONNECTING;
  52776. this._receiver = null;
  52777. this._sender = null;
  52778. this._socket = null;
  52779. if (address !== null) {
  52780. this._bufferedAmount = 0;
  52781. this._isServer = false;
  52782. this._redirects = 0;
  52783. if (Array.isArray(protocols)) {
  52784. protocols = protocols.join(', ');
  52785. } else if (typeof protocols === 'object' && protocols !== null) {
  52786. options = protocols;
  52787. protocols = undefined;
  52788. }
  52789. initAsClient(this, address, protocols, options);
  52790. } else {
  52791. this._isServer = true;
  52792. }
  52793. }
  52794. /**
  52795. * This deviates from the WHATWG interface since ws doesn't support the
  52796. * required default "blob" type (instead we define a custom "nodebuffer"
  52797. * type).
  52798. *
  52799. * @type {String}
  52800. */
  52801. get binaryType() {
  52802. return this._binaryType;
  52803. }
  52804. set binaryType(type) {
  52805. if (!BINARY_TYPES.includes(type)) return;
  52806. this._binaryType = type;
  52807. //
  52808. // Allow to change `binaryType` on the fly.
  52809. //
  52810. if (this._receiver) this._receiver._binaryType = type;
  52811. }
  52812. /**
  52813. * @type {Number}
  52814. */
  52815. get bufferedAmount() {
  52816. if (!this._socket) return this._bufferedAmount;
  52817. return this._socket._writableState.length + this._sender._bufferedBytes;
  52818. }
  52819. /**
  52820. * @type {String}
  52821. */
  52822. get extensions() {
  52823. return Object.keys(this._extensions).join();
  52824. }
  52825. /**
  52826. * @type {Function}
  52827. */
  52828. /* istanbul ignore next */
  52829. get onclose() {
  52830. return undefined;
  52831. }
  52832. /* istanbul ignore next */
  52833. set onclose(listener) {}
  52834. /**
  52835. * @type {Function}
  52836. */
  52837. /* istanbul ignore next */
  52838. get onerror() {
  52839. return undefined;
  52840. }
  52841. /* istanbul ignore next */
  52842. set onerror(listener) {}
  52843. /**
  52844. * @type {Function}
  52845. */
  52846. /* istanbul ignore next */
  52847. get onopen() {
  52848. return undefined;
  52849. }
  52850. /* istanbul ignore next */
  52851. set onopen(listener) {}
  52852. /**
  52853. * @type {Function}
  52854. */
  52855. /* istanbul ignore next */
  52856. get onmessage() {
  52857. return undefined;
  52858. }
  52859. /* istanbul ignore next */
  52860. set onmessage(listener) {}
  52861. /**
  52862. * @type {String}
  52863. */
  52864. get protocol() {
  52865. return this._protocol;
  52866. }
  52867. /**
  52868. * @type {Number}
  52869. */
  52870. get readyState() {
  52871. return this._readyState;
  52872. }
  52873. /**
  52874. * @type {String}
  52875. */
  52876. get url() {
  52877. return this._url;
  52878. }
  52879. /**
  52880. * Set up the socket and the internal resources.
  52881. *
  52882. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  52883. * server and client
  52884. * @param {Buffer} head The first packet of the upgraded stream
  52885. * @param {Number} [maxPayload=0] The maximum allowed message size
  52886. * @private
  52887. */
  52888. setSocket(socket, head, maxPayload) {
  52889. const receiver = new Receiver(
  52890. this.binaryType,
  52891. this._extensions,
  52892. this._isServer,
  52893. maxPayload
  52894. );
  52895. this._sender = new Sender(socket, this._extensions);
  52896. this._receiver = receiver;
  52897. this._socket = socket;
  52898. receiver[kWebSocket$1] = this;
  52899. socket[kWebSocket$1] = this;
  52900. receiver.on('conclude', receiverOnConclude);
  52901. receiver.on('drain', receiverOnDrain);
  52902. receiver.on('error', receiverOnError);
  52903. receiver.on('message', receiverOnMessage);
  52904. receiver.on('ping', receiverOnPing);
  52905. receiver.on('pong', receiverOnPong);
  52906. socket.setTimeout(0);
  52907. socket.setNoDelay();
  52908. if (head.length > 0) socket.unshift(head);
  52909. socket.on('close', socketOnClose);
  52910. socket.on('data', socketOnData);
  52911. socket.on('end', socketOnEnd);
  52912. socket.on('error', socketOnError$1);
  52913. this._readyState = WebSocket$2.OPEN;
  52914. this.emit('open');
  52915. }
  52916. /**
  52917. * Emit the `'close'` event.
  52918. *
  52919. * @private
  52920. */
  52921. emitClose() {
  52922. if (!this._socket) {
  52923. this._readyState = WebSocket$2.CLOSED;
  52924. this.emit('close', this._closeCode, this._closeMessage);
  52925. return;
  52926. }
  52927. if (this._extensions[PerMessageDeflate$1.extensionName]) {
  52928. this._extensions[PerMessageDeflate$1.extensionName].cleanup();
  52929. }
  52930. this._receiver.removeAllListeners();
  52931. this._readyState = WebSocket$2.CLOSED;
  52932. this.emit('close', this._closeCode, this._closeMessage);
  52933. }
  52934. /**
  52935. * Start a closing handshake.
  52936. *
  52937. * +----------+ +-----------+ +----------+
  52938. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  52939. * | +----------+ +-----------+ +----------+ |
  52940. * +----------+ +-----------+ |
  52941. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  52942. * +----------+ +-----------+ |
  52943. * | | | +---+ |
  52944. * +------------------------+-->|fin| - - - -
  52945. * | +---+ | +---+
  52946. * - - - - -|fin|<---------------------+
  52947. * +---+
  52948. *
  52949. * @param {Number} [code] Status code explaining why the connection is closing
  52950. * @param {String} [data] A string explaining why the connection is closing
  52951. * @public
  52952. */
  52953. close(code, data) {
  52954. if (this.readyState === WebSocket$2.CLOSED) return;
  52955. if (this.readyState === WebSocket$2.CONNECTING) {
  52956. const msg = 'WebSocket was closed before the connection was established';
  52957. return abortHandshake$1(this, this._req, msg);
  52958. }
  52959. if (this.readyState === WebSocket$2.CLOSING) {
  52960. if (
  52961. this._closeFrameSent &&
  52962. (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
  52963. ) {
  52964. this._socket.end();
  52965. }
  52966. return;
  52967. }
  52968. this._readyState = WebSocket$2.CLOSING;
  52969. this._sender.close(code, data, !this._isServer, (err) => {
  52970. //
  52971. // This error is handled by the `'error'` listener on the socket. We only
  52972. // want to know if the close frame has been sent here.
  52973. //
  52974. if (err) return;
  52975. this._closeFrameSent = true;
  52976. if (
  52977. this._closeFrameReceived ||
  52978. this._receiver._writableState.errorEmitted
  52979. ) {
  52980. this._socket.end();
  52981. }
  52982. });
  52983. //
  52984. // Specify a timeout for the closing handshake to complete.
  52985. //
  52986. this._closeTimer = setTimeout(
  52987. this._socket.destroy.bind(this._socket),
  52988. closeTimeout
  52989. );
  52990. }
  52991. /**
  52992. * Send a ping.
  52993. *
  52994. * @param {*} [data] The data to send
  52995. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  52996. * @param {Function} [cb] Callback which is executed when the ping is sent
  52997. * @public
  52998. */
  52999. ping(data, mask, cb) {
  53000. if (this.readyState === WebSocket$2.CONNECTING) {
  53001. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  53002. }
  53003. if (typeof data === 'function') {
  53004. cb = data;
  53005. data = mask = undefined;
  53006. } else if (typeof mask === 'function') {
  53007. cb = mask;
  53008. mask = undefined;
  53009. }
  53010. if (typeof data === 'number') data = data.toString();
  53011. if (this.readyState !== WebSocket$2.OPEN) {
  53012. sendAfterClose(this, data, cb);
  53013. return;
  53014. }
  53015. if (mask === undefined) mask = !this._isServer;
  53016. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  53017. }
  53018. /**
  53019. * Send a pong.
  53020. *
  53021. * @param {*} [data] The data to send
  53022. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  53023. * @param {Function} [cb] Callback which is executed when the pong is sent
  53024. * @public
  53025. */
  53026. pong(data, mask, cb) {
  53027. if (this.readyState === WebSocket$2.CONNECTING) {
  53028. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  53029. }
  53030. if (typeof data === 'function') {
  53031. cb = data;
  53032. data = mask = undefined;
  53033. } else if (typeof mask === 'function') {
  53034. cb = mask;
  53035. mask = undefined;
  53036. }
  53037. if (typeof data === 'number') data = data.toString();
  53038. if (this.readyState !== WebSocket$2.OPEN) {
  53039. sendAfterClose(this, data, cb);
  53040. return;
  53041. }
  53042. if (mask === undefined) mask = !this._isServer;
  53043. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  53044. }
  53045. /**
  53046. * Send a data message.
  53047. *
  53048. * @param {*} data The message to send
  53049. * @param {Object} [options] Options object
  53050. * @param {Boolean} [options.compress] Specifies whether or not to compress
  53051. * `data`
  53052. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  53053. * text
  53054. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  53055. * last one
  53056. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  53057. * @param {Function} [cb] Callback which is executed when data is written out
  53058. * @public
  53059. */
  53060. send(data, options, cb) {
  53061. if (this.readyState === WebSocket$2.CONNECTING) {
  53062. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  53063. }
  53064. if (typeof options === 'function') {
  53065. cb = options;
  53066. options = {};
  53067. }
  53068. if (typeof data === 'number') data = data.toString();
  53069. if (this.readyState !== WebSocket$2.OPEN) {
  53070. sendAfterClose(this, data, cb);
  53071. return;
  53072. }
  53073. const opts = {
  53074. binary: typeof data !== 'string',
  53075. mask: !this._isServer,
  53076. compress: true,
  53077. fin: true,
  53078. ...options
  53079. };
  53080. if (!this._extensions[PerMessageDeflate$1.extensionName]) {
  53081. opts.compress = false;
  53082. }
  53083. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  53084. }
  53085. /**
  53086. * Forcibly close the connection.
  53087. *
  53088. * @public
  53089. */
  53090. terminate() {
  53091. if (this.readyState === WebSocket$2.CLOSED) return;
  53092. if (this.readyState === WebSocket$2.CONNECTING) {
  53093. const msg = 'WebSocket was closed before the connection was established';
  53094. return abortHandshake$1(this, this._req, msg);
  53095. }
  53096. if (this._socket) {
  53097. this._readyState = WebSocket$2.CLOSING;
  53098. this._socket.destroy();
  53099. }
  53100. }
  53101. }
  53102. /**
  53103. * @constant {Number} CONNECTING
  53104. * @memberof WebSocket
  53105. */
  53106. Object.defineProperty(WebSocket$2, 'CONNECTING', {
  53107. enumerable: true,
  53108. value: readyStates.indexOf('CONNECTING')
  53109. });
  53110. /**
  53111. * @constant {Number} CONNECTING
  53112. * @memberof WebSocket.prototype
  53113. */
  53114. Object.defineProperty(WebSocket$2.prototype, 'CONNECTING', {
  53115. enumerable: true,
  53116. value: readyStates.indexOf('CONNECTING')
  53117. });
  53118. /**
  53119. * @constant {Number} OPEN
  53120. * @memberof WebSocket
  53121. */
  53122. Object.defineProperty(WebSocket$2, 'OPEN', {
  53123. enumerable: true,
  53124. value: readyStates.indexOf('OPEN')
  53125. });
  53126. /**
  53127. * @constant {Number} OPEN
  53128. * @memberof WebSocket.prototype
  53129. */
  53130. Object.defineProperty(WebSocket$2.prototype, 'OPEN', {
  53131. enumerable: true,
  53132. value: readyStates.indexOf('OPEN')
  53133. });
  53134. /**
  53135. * @constant {Number} CLOSING
  53136. * @memberof WebSocket
  53137. */
  53138. Object.defineProperty(WebSocket$2, 'CLOSING', {
  53139. enumerable: true,
  53140. value: readyStates.indexOf('CLOSING')
  53141. });
  53142. /**
  53143. * @constant {Number} CLOSING
  53144. * @memberof WebSocket.prototype
  53145. */
  53146. Object.defineProperty(WebSocket$2.prototype, 'CLOSING', {
  53147. enumerable: true,
  53148. value: readyStates.indexOf('CLOSING')
  53149. });
  53150. /**
  53151. * @constant {Number} CLOSED
  53152. * @memberof WebSocket
  53153. */
  53154. Object.defineProperty(WebSocket$2, 'CLOSED', {
  53155. enumerable: true,
  53156. value: readyStates.indexOf('CLOSED')
  53157. });
  53158. /**
  53159. * @constant {Number} CLOSED
  53160. * @memberof WebSocket.prototype
  53161. */
  53162. Object.defineProperty(WebSocket$2.prototype, 'CLOSED', {
  53163. enumerable: true,
  53164. value: readyStates.indexOf('CLOSED')
  53165. });
  53166. [
  53167. 'binaryType',
  53168. 'bufferedAmount',
  53169. 'extensions',
  53170. 'protocol',
  53171. 'readyState',
  53172. 'url'
  53173. ].forEach((property) => {
  53174. Object.defineProperty(WebSocket$2.prototype, property, { enumerable: true });
  53175. });
  53176. //
  53177. // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
  53178. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
  53179. //
  53180. ['open', 'error', 'close', 'message'].forEach((method) => {
  53181. Object.defineProperty(WebSocket$2.prototype, `on${method}`, {
  53182. enumerable: true,
  53183. get() {
  53184. const listeners = this.listeners(method);
  53185. for (let i = 0; i < listeners.length; i++) {
  53186. if (listeners[i]._listener) return listeners[i]._listener;
  53187. }
  53188. return undefined;
  53189. },
  53190. set(listener) {
  53191. const listeners = this.listeners(method);
  53192. for (let i = 0; i < listeners.length; i++) {
  53193. //
  53194. // Remove only the listeners added via `addEventListener`.
  53195. //
  53196. if (listeners[i]._listener) this.removeListener(method, listeners[i]);
  53197. }
  53198. this.addEventListener(method, listener);
  53199. }
  53200. });
  53201. });
  53202. WebSocket$2.prototype.addEventListener = addEventListener;
  53203. WebSocket$2.prototype.removeEventListener = removeEventListener;
  53204. var websocket = WebSocket$2;
  53205. /**
  53206. * Initialize a WebSocket client.
  53207. *
  53208. * @param {WebSocket} websocket The client to initialize
  53209. * @param {(String|URL)} address The URL to which to connect
  53210. * @param {String} [protocols] The subprotocols
  53211. * @param {Object} [options] Connection options
  53212. * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
  53213. * permessage-deflate
  53214. * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
  53215. * handshake request
  53216. * @param {Number} [options.protocolVersion=13] Value of the
  53217. * `Sec-WebSocket-Version` header
  53218. * @param {String} [options.origin] Value of the `Origin` or
  53219. * `Sec-WebSocket-Origin` header
  53220. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  53221. * size
  53222. * @param {Boolean} [options.followRedirects=false] Whether or not to follow
  53223. * redirects
  53224. * @param {Number} [options.maxRedirects=10] The maximum number of redirects
  53225. * allowed
  53226. * @private
  53227. */
  53228. function initAsClient(websocket, address, protocols, options) {
  53229. const opts = {
  53230. protocolVersion: protocolVersions[1],
  53231. maxPayload: 100 * 1024 * 1024,
  53232. perMessageDeflate: true,
  53233. followRedirects: false,
  53234. maxRedirects: 10,
  53235. ...options,
  53236. createConnection: undefined,
  53237. socketPath: undefined,
  53238. hostname: undefined,
  53239. protocol: undefined,
  53240. timeout: undefined,
  53241. method: undefined,
  53242. host: undefined,
  53243. path: undefined,
  53244. port: undefined
  53245. };
  53246. if (!protocolVersions.includes(opts.protocolVersion)) {
  53247. throw new RangeError(
  53248. `Unsupported protocol version: ${opts.protocolVersion} ` +
  53249. `(supported versions: ${protocolVersions.join(', ')})`
  53250. );
  53251. }
  53252. let parsedUrl;
  53253. if (address instanceof URL$2) {
  53254. parsedUrl = address;
  53255. websocket._url = address.href;
  53256. } else {
  53257. parsedUrl = new URL$2(address);
  53258. websocket._url = address;
  53259. }
  53260. const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
  53261. if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
  53262. throw new Error(`Invalid URL: ${websocket.url}`);
  53263. }
  53264. const isSecure =
  53265. parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
  53266. const defaultPort = isSecure ? 443 : 80;
  53267. const key = randomBytes(16).toString('base64');
  53268. const get = isSecure ? https$2.get : http$3.get;
  53269. let perMessageDeflate;
  53270. opts.createConnection = isSecure ? tlsConnect : netConnect;
  53271. opts.defaultPort = opts.defaultPort || defaultPort;
  53272. opts.port = parsedUrl.port || defaultPort;
  53273. opts.host = parsedUrl.hostname.startsWith('[')
  53274. ? parsedUrl.hostname.slice(1, -1)
  53275. : parsedUrl.hostname;
  53276. opts.headers = {
  53277. 'Sec-WebSocket-Version': opts.protocolVersion,
  53278. 'Sec-WebSocket-Key': key,
  53279. Connection: 'Upgrade',
  53280. Upgrade: 'websocket',
  53281. ...opts.headers
  53282. };
  53283. opts.path = parsedUrl.pathname + parsedUrl.search;
  53284. opts.timeout = opts.handshakeTimeout;
  53285. if (opts.perMessageDeflate) {
  53286. perMessageDeflate = new PerMessageDeflate$1(
  53287. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  53288. false,
  53289. opts.maxPayload
  53290. );
  53291. opts.headers['Sec-WebSocket-Extensions'] = format$1({
  53292. [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
  53293. });
  53294. }
  53295. if (protocols) {
  53296. opts.headers['Sec-WebSocket-Protocol'] = protocols;
  53297. }
  53298. if (opts.origin) {
  53299. if (opts.protocolVersion < 13) {
  53300. opts.headers['Sec-WebSocket-Origin'] = opts.origin;
  53301. } else {
  53302. opts.headers.Origin = opts.origin;
  53303. }
  53304. }
  53305. if (parsedUrl.username || parsedUrl.password) {
  53306. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  53307. }
  53308. if (isUnixSocket) {
  53309. const parts = opts.path.split(':');
  53310. opts.socketPath = parts[0];
  53311. opts.path = parts[1];
  53312. }
  53313. let req = (websocket._req = get(opts));
  53314. if (opts.timeout) {
  53315. req.on('timeout', () => {
  53316. abortHandshake$1(websocket, req, 'Opening handshake has timed out');
  53317. });
  53318. }
  53319. req.on('error', (err) => {
  53320. if (req === null || req.aborted) return;
  53321. req = websocket._req = null;
  53322. websocket._readyState = WebSocket$2.CLOSING;
  53323. websocket.emit('error', err);
  53324. websocket.emitClose();
  53325. });
  53326. req.on('response', (res) => {
  53327. const location = res.headers.location;
  53328. const statusCode = res.statusCode;
  53329. if (
  53330. location &&
  53331. opts.followRedirects &&
  53332. statusCode >= 300 &&
  53333. statusCode < 400
  53334. ) {
  53335. if (++websocket._redirects > opts.maxRedirects) {
  53336. abortHandshake$1(websocket, req, 'Maximum redirects exceeded');
  53337. return;
  53338. }
  53339. req.abort();
  53340. const addr = new URL$2(location, address);
  53341. initAsClient(websocket, addr, protocols, options);
  53342. } else if (!websocket.emit('unexpected-response', req, res)) {
  53343. abortHandshake$1(
  53344. websocket,
  53345. req,
  53346. `Unexpected server response: ${res.statusCode}`
  53347. );
  53348. }
  53349. });
  53350. req.on('upgrade', (res, socket, head) => {
  53351. websocket.emit('upgrade', res);
  53352. //
  53353. // The user may have closed the connection from a listener of the `upgrade`
  53354. // event.
  53355. //
  53356. if (websocket.readyState !== WebSocket$2.CONNECTING) return;
  53357. req = websocket._req = null;
  53358. const digest = createHash$1('sha1')
  53359. .update(key + GUID$1)
  53360. .digest('base64');
  53361. if (res.headers['sec-websocket-accept'] !== digest) {
  53362. abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  53363. return;
  53364. }
  53365. const serverProt = res.headers['sec-websocket-protocol'];
  53366. const protList = (protocols || '').split(/, */);
  53367. let protError;
  53368. if (!protocols && serverProt) {
  53369. protError = 'Server sent a subprotocol but none was requested';
  53370. } else if (protocols && !serverProt) {
  53371. protError = 'Server sent no subprotocol';
  53372. } else if (serverProt && !protList.includes(serverProt)) {
  53373. protError = 'Server sent an invalid subprotocol';
  53374. }
  53375. if (protError) {
  53376. abortHandshake$1(websocket, socket, protError);
  53377. return;
  53378. }
  53379. if (serverProt) websocket._protocol = serverProt;
  53380. const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
  53381. if (secWebSocketExtensions !== undefined) {
  53382. if (!perMessageDeflate) {
  53383. const message =
  53384. 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
  53385. 'was requested';
  53386. abortHandshake$1(websocket, socket, message);
  53387. return;
  53388. }
  53389. let extensions;
  53390. try {
  53391. extensions = parse$6(secWebSocketExtensions);
  53392. } catch (err) {
  53393. const message = 'Invalid Sec-WebSocket-Extensions header';
  53394. abortHandshake$1(websocket, socket, message);
  53395. return;
  53396. }
  53397. const extensionNames = Object.keys(extensions);
  53398. if (extensionNames.length) {
  53399. if (
  53400. extensionNames.length !== 1 ||
  53401. extensionNames[0] !== PerMessageDeflate$1.extensionName
  53402. ) {
  53403. const message =
  53404. 'Server indicated an extension that was not requested';
  53405. abortHandshake$1(websocket, socket, message);
  53406. return;
  53407. }
  53408. try {
  53409. perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]);
  53410. } catch (err) {
  53411. const message = 'Invalid Sec-WebSocket-Extensions header';
  53412. abortHandshake$1(websocket, socket, message);
  53413. return;
  53414. }
  53415. websocket._extensions[PerMessageDeflate$1.extensionName] =
  53416. perMessageDeflate;
  53417. }
  53418. }
  53419. websocket.setSocket(socket, head, opts.maxPayload);
  53420. });
  53421. }
  53422. /**
  53423. * Create a `net.Socket` and initiate a connection.
  53424. *
  53425. * @param {Object} options Connection options
  53426. * @return {net.Socket} The newly created socket used to start the connection
  53427. * @private
  53428. */
  53429. function netConnect(options) {
  53430. options.path = options.socketPath;
  53431. return net.connect(options);
  53432. }
  53433. /**
  53434. * Create a `tls.TLSSocket` and initiate a connection.
  53435. *
  53436. * @param {Object} options Connection options
  53437. * @return {tls.TLSSocket} The newly created socket used to start the connection
  53438. * @private
  53439. */
  53440. function tlsConnect(options) {
  53441. options.path = undefined;
  53442. if (!options.servername && options.servername !== '') {
  53443. options.servername = net.isIP(options.host) ? '' : options.host;
  53444. }
  53445. return tls.connect(options);
  53446. }
  53447. /**
  53448. * Abort the handshake and emit an error.
  53449. *
  53450. * @param {WebSocket} websocket The WebSocket instance
  53451. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  53452. * abort or the socket to destroy
  53453. * @param {String} message The error message
  53454. * @private
  53455. */
  53456. function abortHandshake$1(websocket, stream, message) {
  53457. websocket._readyState = WebSocket$2.CLOSING;
  53458. const err = new Error(message);
  53459. Error.captureStackTrace(err, abortHandshake$1);
  53460. if (stream.setHeader) {
  53461. stream.abort();
  53462. if (stream.socket && !stream.socket.destroyed) {
  53463. //
  53464. // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
  53465. // called after the request completed. See
  53466. // https://github.com/websockets/ws/issues/1869.
  53467. //
  53468. stream.socket.destroy();
  53469. }
  53470. stream.once('abort', websocket.emitClose.bind(websocket));
  53471. websocket.emit('error', err);
  53472. } else {
  53473. stream.destroy(err);
  53474. stream.once('error', websocket.emit.bind(websocket, 'error'));
  53475. stream.once('close', websocket.emitClose.bind(websocket));
  53476. }
  53477. }
  53478. /**
  53479. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  53480. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  53481. *
  53482. * @param {WebSocket} websocket The WebSocket instance
  53483. * @param {*} [data] The data to send
  53484. * @param {Function} [cb] Callback
  53485. * @private
  53486. */
  53487. function sendAfterClose(websocket, data, cb) {
  53488. if (data) {
  53489. const length = toBuffer(data).length;
  53490. //
  53491. // The `_bufferedAmount` property is used only when the peer is a client and
  53492. // the opening handshake fails. Under these circumstances, in fact, the
  53493. // `setSocket()` method is not called, so the `_socket` and `_sender`
  53494. // properties are set to `null`.
  53495. //
  53496. if (websocket._socket) websocket._sender._bufferedBytes += length;
  53497. else websocket._bufferedAmount += length;
  53498. }
  53499. if (cb) {
  53500. const err = new Error(
  53501. `WebSocket is not open: readyState ${websocket.readyState} ` +
  53502. `(${readyStates[websocket.readyState]})`
  53503. );
  53504. cb(err);
  53505. }
  53506. }
  53507. /**
  53508. * The listener of the `Receiver` `'conclude'` event.
  53509. *
  53510. * @param {Number} code The status code
  53511. * @param {String} reason The reason for closing
  53512. * @private
  53513. */
  53514. function receiverOnConclude(code, reason) {
  53515. const websocket = this[kWebSocket$1];
  53516. websocket._socket.removeListener('data', socketOnData);
  53517. websocket._socket.resume();
  53518. websocket._closeFrameReceived = true;
  53519. websocket._closeMessage = reason;
  53520. websocket._closeCode = code;
  53521. if (code === 1005) websocket.close();
  53522. else websocket.close(code, reason);
  53523. }
  53524. /**
  53525. * The listener of the `Receiver` `'drain'` event.
  53526. *
  53527. * @private
  53528. */
  53529. function receiverOnDrain() {
  53530. this[kWebSocket$1]._socket.resume();
  53531. }
  53532. /**
  53533. * The listener of the `Receiver` `'error'` event.
  53534. *
  53535. * @param {(RangeError|Error)} err The emitted error
  53536. * @private
  53537. */
  53538. function receiverOnError(err) {
  53539. const websocket = this[kWebSocket$1];
  53540. websocket._socket.removeListener('data', socketOnData);
  53541. websocket._socket.resume();
  53542. websocket.close(err[kStatusCode]);
  53543. websocket.emit('error', err);
  53544. }
  53545. /**
  53546. * The listener of the `Receiver` `'finish'` event.
  53547. *
  53548. * @private
  53549. */
  53550. function receiverOnFinish() {
  53551. this[kWebSocket$1].emitClose();
  53552. }
  53553. /**
  53554. * The listener of the `Receiver` `'message'` event.
  53555. *
  53556. * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
  53557. * @private
  53558. */
  53559. function receiverOnMessage(data) {
  53560. this[kWebSocket$1].emit('message', data);
  53561. }
  53562. /**
  53563. * The listener of the `Receiver` `'ping'` event.
  53564. *
  53565. * @param {Buffer} data The data included in the ping frame
  53566. * @private
  53567. */
  53568. function receiverOnPing(data) {
  53569. const websocket = this[kWebSocket$1];
  53570. websocket.pong(data, !websocket._isServer, NOOP);
  53571. websocket.emit('ping', data);
  53572. }
  53573. /**
  53574. * The listener of the `Receiver` `'pong'` event.
  53575. *
  53576. * @param {Buffer} data The data included in the pong frame
  53577. * @private
  53578. */
  53579. function receiverOnPong(data) {
  53580. this[kWebSocket$1].emit('pong', data);
  53581. }
  53582. /**
  53583. * The listener of the `net.Socket` `'close'` event.
  53584. *
  53585. * @private
  53586. */
  53587. function socketOnClose() {
  53588. const websocket = this[kWebSocket$1];
  53589. this.removeListener('close', socketOnClose);
  53590. this.removeListener('end', socketOnEnd);
  53591. websocket._readyState = WebSocket$2.CLOSING;
  53592. //
  53593. // The close frame might not have been received or the `'end'` event emitted,
  53594. // for example, if the socket was destroyed due to an error. Ensure that the
  53595. // `receiver` stream is closed after writing any remaining buffered data to
  53596. // it. If the readable side of the socket is in flowing mode then there is no
  53597. // buffered data as everything has been already written and `readable.read()`
  53598. // will return `null`. If instead, the socket is paused, any possible buffered
  53599. // data will be read as a single chunk and emitted synchronously in a single
  53600. // `'data'` event.
  53601. //
  53602. websocket._socket.read();
  53603. websocket._receiver.end();
  53604. this.removeListener('data', socketOnData);
  53605. this[kWebSocket$1] = undefined;
  53606. clearTimeout(websocket._closeTimer);
  53607. if (
  53608. websocket._receiver._writableState.finished ||
  53609. websocket._receiver._writableState.errorEmitted
  53610. ) {
  53611. websocket.emitClose();
  53612. } else {
  53613. websocket._receiver.on('error', receiverOnFinish);
  53614. websocket._receiver.on('finish', receiverOnFinish);
  53615. }
  53616. }
  53617. /**
  53618. * The listener of the `net.Socket` `'data'` event.
  53619. *
  53620. * @param {Buffer} chunk A chunk of data
  53621. * @private
  53622. */
  53623. function socketOnData(chunk) {
  53624. if (!this[kWebSocket$1]._receiver.write(chunk)) {
  53625. this.pause();
  53626. }
  53627. }
  53628. /**
  53629. * The listener of the `net.Socket` `'end'` event.
  53630. *
  53631. * @private
  53632. */
  53633. function socketOnEnd() {
  53634. const websocket = this[kWebSocket$1];
  53635. websocket._readyState = WebSocket$2.CLOSING;
  53636. websocket._receiver.end();
  53637. this.end();
  53638. }
  53639. /**
  53640. * The listener of the `net.Socket` `'error'` event.
  53641. *
  53642. * @private
  53643. */
  53644. function socketOnError$1() {
  53645. const websocket = this[kWebSocket$1];
  53646. this.removeListener('error', socketOnError$1);
  53647. this.on('error', NOOP);
  53648. if (websocket) {
  53649. websocket._readyState = WebSocket$2.CLOSING;
  53650. this.destroy();
  53651. }
  53652. }
  53653. const { Duplex } = require$$0__default$2;
  53654. /**
  53655. * Emits the `'close'` event on a stream.
  53656. *
  53657. * @param {Duplex} stream The stream.
  53658. * @private
  53659. */
  53660. function emitClose$1(stream) {
  53661. stream.emit('close');
  53662. }
  53663. /**
  53664. * The listener of the `'end'` event.
  53665. *
  53666. * @private
  53667. */
  53668. function duplexOnEnd() {
  53669. if (!this.destroyed && this._writableState.finished) {
  53670. this.destroy();
  53671. }
  53672. }
  53673. /**
  53674. * The listener of the `'error'` event.
  53675. *
  53676. * @param {Error} err The error
  53677. * @private
  53678. */
  53679. function duplexOnError(err) {
  53680. this.removeListener('error', duplexOnError);
  53681. this.destroy();
  53682. if (this.listenerCount('error') === 0) {
  53683. // Do not suppress the throwing behavior.
  53684. this.emit('error', err);
  53685. }
  53686. }
  53687. /**
  53688. * Wraps a `WebSocket` in a duplex stream.
  53689. *
  53690. * @param {WebSocket} ws The `WebSocket` to wrap
  53691. * @param {Object} [options] The options for the `Duplex` constructor
  53692. * @return {Duplex} The duplex stream
  53693. * @public
  53694. */
  53695. function createWebSocketStream(ws, options) {
  53696. let resumeOnReceiverDrain = true;
  53697. let terminateOnDestroy = true;
  53698. function receiverOnDrain() {
  53699. if (resumeOnReceiverDrain) ws._socket.resume();
  53700. }
  53701. if (ws.readyState === ws.CONNECTING) {
  53702. ws.once('open', function open() {
  53703. ws._receiver.removeAllListeners('drain');
  53704. ws._receiver.on('drain', receiverOnDrain);
  53705. });
  53706. } else {
  53707. ws._receiver.removeAllListeners('drain');
  53708. ws._receiver.on('drain', receiverOnDrain);
  53709. }
  53710. const duplex = new Duplex({
  53711. ...options,
  53712. autoDestroy: false,
  53713. emitClose: false,
  53714. objectMode: false,
  53715. writableObjectMode: false
  53716. });
  53717. ws.on('message', function message(msg) {
  53718. if (!duplex.push(msg)) {
  53719. resumeOnReceiverDrain = false;
  53720. ws._socket.pause();
  53721. }
  53722. });
  53723. ws.once('error', function error(err) {
  53724. if (duplex.destroyed) return;
  53725. // Prevent `ws.terminate()` from being called by `duplex._destroy()`.
  53726. //
  53727. // - If the `'error'` event is emitted before the `'open'` event, then
  53728. // `ws.terminate()` is a noop as no socket is assigned.
  53729. // - Otherwise, the error is re-emitted by the listener of the `'error'`
  53730. // event of the `Receiver` object. The listener already closes the
  53731. // connection by calling `ws.close()`. This allows a close frame to be
  53732. // sent to the other peer. If `ws.terminate()` is called right after this,
  53733. // then the close frame might not be sent.
  53734. terminateOnDestroy = false;
  53735. duplex.destroy(err);
  53736. });
  53737. ws.once('close', function close() {
  53738. if (duplex.destroyed) return;
  53739. duplex.push(null);
  53740. });
  53741. duplex._destroy = function (err, callback) {
  53742. if (ws.readyState === ws.CLOSED) {
  53743. callback(err);
  53744. process.nextTick(emitClose$1, duplex);
  53745. return;
  53746. }
  53747. let called = false;
  53748. ws.once('error', function error(err) {
  53749. called = true;
  53750. callback(err);
  53751. });
  53752. ws.once('close', function close() {
  53753. if (!called) callback(err);
  53754. process.nextTick(emitClose$1, duplex);
  53755. });
  53756. if (terminateOnDestroy) ws.terminate();
  53757. };
  53758. duplex._final = function (callback) {
  53759. if (ws.readyState === ws.CONNECTING) {
  53760. ws.once('open', function open() {
  53761. duplex._final(callback);
  53762. });
  53763. return;
  53764. }
  53765. // If the value of the `_socket` property is `null` it means that `ws` is a
  53766. // client websocket and the handshake failed. In fact, when this happens, a
  53767. // socket is never assigned to the websocket. Wait for the `'error'` event
  53768. // that will be emitted by the websocket.
  53769. if (ws._socket === null) return;
  53770. if (ws._socket._writableState.finished) {
  53771. callback();
  53772. if (duplex._readableState.endEmitted) duplex.destroy();
  53773. } else {
  53774. ws._socket.once('finish', function finish() {
  53775. // `duplex` is not destroyed here because the `'end'` event will be
  53776. // emitted on `duplex` after this `'finish'` event. The EOF signaling
  53777. // `null` chunk is, in fact, pushed when the websocket emits `'close'`.
  53778. callback();
  53779. });
  53780. ws.close();
  53781. }
  53782. };
  53783. duplex._read = function () {
  53784. if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) {
  53785. resumeOnReceiverDrain = true;
  53786. if (!ws._receiver._writableState.needDrain) ws._socket.resume();
  53787. }
  53788. };
  53789. duplex._write = function (chunk, encoding, callback) {
  53790. if (ws.readyState === ws.CONNECTING) {
  53791. ws.once('open', function open() {
  53792. duplex._write(chunk, encoding, callback);
  53793. });
  53794. return;
  53795. }
  53796. ws.send(chunk, callback);
  53797. };
  53798. duplex.on('end', duplexOnEnd);
  53799. duplex.on('error', duplexOnError);
  53800. return duplex;
  53801. }
  53802. var stream$2 = createWebSocketStream;
  53803. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */
  53804. const EventEmitter = require$$0__default$6;
  53805. const http$2 = require$$1__default$1;
  53806. const { createHash } = require$$1__default$2;
  53807. const PerMessageDeflate = permessageDeflate;
  53808. const WebSocket$1 = websocket;
  53809. const { format, parse: parse$5 } = extension;
  53810. const { GUID, kWebSocket } = constants;
  53811. const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  53812. const RUNNING = 0;
  53813. const CLOSING = 1;
  53814. const CLOSED = 2;
  53815. /**
  53816. * Class representing a WebSocket server.
  53817. *
  53818. * @extends EventEmitter
  53819. */
  53820. class WebSocketServer extends EventEmitter {
  53821. /**
  53822. * Create a `WebSocketServer` instance.
  53823. *
  53824. * @param {Object} options Configuration options
  53825. * @param {Number} [options.backlog=511] The maximum length of the queue of
  53826. * pending connections
  53827. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  53828. * track clients
  53829. * @param {Function} [options.handleProtocols] A hook to handle protocols
  53830. * @param {String} [options.host] The hostname where to bind the server
  53831. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  53832. * size
  53833. * @param {Boolean} [options.noServer=false] Enable no server mode
  53834. * @param {String} [options.path] Accept only connections matching this path
  53835. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  53836. * permessage-deflate
  53837. * @param {Number} [options.port] The port where to bind the server
  53838. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  53839. * server to use
  53840. * @param {Function} [options.verifyClient] A hook to reject connections
  53841. * @param {Function} [callback] A listener for the `listening` event
  53842. */
  53843. constructor(options, callback) {
  53844. super();
  53845. options = {
  53846. maxPayload: 100 * 1024 * 1024,
  53847. perMessageDeflate: false,
  53848. handleProtocols: null,
  53849. clientTracking: true,
  53850. verifyClient: null,
  53851. noServer: false,
  53852. backlog: null, // use default (511 as implemented in net.js)
  53853. server: null,
  53854. host: null,
  53855. path: null,
  53856. port: null,
  53857. ...options
  53858. };
  53859. if (
  53860. (options.port == null && !options.server && !options.noServer) ||
  53861. (options.port != null && (options.server || options.noServer)) ||
  53862. (options.server && options.noServer)
  53863. ) {
  53864. throw new TypeError(
  53865. 'One and only one of the "port", "server", or "noServer" options ' +
  53866. 'must be specified'
  53867. );
  53868. }
  53869. if (options.port != null) {
  53870. this._server = http$2.createServer((req, res) => {
  53871. const body = http$2.STATUS_CODES[426];
  53872. res.writeHead(426, {
  53873. 'Content-Length': body.length,
  53874. 'Content-Type': 'text/plain'
  53875. });
  53876. res.end(body);
  53877. });
  53878. this._server.listen(
  53879. options.port,
  53880. options.host,
  53881. options.backlog,
  53882. callback
  53883. );
  53884. } else if (options.server) {
  53885. this._server = options.server;
  53886. }
  53887. if (this._server) {
  53888. const emitConnection = this.emit.bind(this, 'connection');
  53889. this._removeListeners = addListeners(this._server, {
  53890. listening: this.emit.bind(this, 'listening'),
  53891. error: this.emit.bind(this, 'error'),
  53892. upgrade: (req, socket, head) => {
  53893. this.handleUpgrade(req, socket, head, emitConnection);
  53894. }
  53895. });
  53896. }
  53897. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  53898. if (options.clientTracking) this.clients = new Set();
  53899. this.options = options;
  53900. this._state = RUNNING;
  53901. }
  53902. /**
  53903. * Returns the bound address, the address family name, and port of the server
  53904. * as reported by the operating system if listening on an IP socket.
  53905. * If the server is listening on a pipe or UNIX domain socket, the name is
  53906. * returned as a string.
  53907. *
  53908. * @return {(Object|String|null)} The address of the server
  53909. * @public
  53910. */
  53911. address() {
  53912. if (this.options.noServer) {
  53913. throw new Error('The server is operating in "noServer" mode');
  53914. }
  53915. if (!this._server) return null;
  53916. return this._server.address();
  53917. }
  53918. /**
  53919. * Close the server.
  53920. *
  53921. * @param {Function} [cb] Callback
  53922. * @public
  53923. */
  53924. close(cb) {
  53925. if (cb) this.once('close', cb);
  53926. if (this._state === CLOSED) {
  53927. process.nextTick(emitClose, this);
  53928. return;
  53929. }
  53930. if (this._state === CLOSING) return;
  53931. this._state = CLOSING;
  53932. //
  53933. // Terminate all associated clients.
  53934. //
  53935. if (this.clients) {
  53936. for (const client of this.clients) client.terminate();
  53937. }
  53938. const server = this._server;
  53939. if (server) {
  53940. this._removeListeners();
  53941. this._removeListeners = this._server = null;
  53942. //
  53943. // Close the http server if it was internally created.
  53944. //
  53945. if (this.options.port != null) {
  53946. server.close(emitClose.bind(undefined, this));
  53947. return;
  53948. }
  53949. }
  53950. process.nextTick(emitClose, this);
  53951. }
  53952. /**
  53953. * See if a given request should be handled by this server instance.
  53954. *
  53955. * @param {http.IncomingMessage} req Request object to inspect
  53956. * @return {Boolean} `true` if the request is valid, else `false`
  53957. * @public
  53958. */
  53959. shouldHandle(req) {
  53960. if (this.options.path) {
  53961. const index = req.url.indexOf('?');
  53962. const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
  53963. if (pathname !== this.options.path) return false;
  53964. }
  53965. return true;
  53966. }
  53967. /**
  53968. * Handle a HTTP Upgrade request.
  53969. *
  53970. * @param {http.IncomingMessage} req The request object
  53971. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  53972. * server and client
  53973. * @param {Buffer} head The first packet of the upgraded stream
  53974. * @param {Function} cb Callback
  53975. * @public
  53976. */
  53977. handleUpgrade(req, socket, head, cb) {
  53978. socket.on('error', socketOnError);
  53979. const key =
  53980. req.headers['sec-websocket-key'] !== undefined
  53981. ? req.headers['sec-websocket-key'].trim()
  53982. : false;
  53983. const version = +req.headers['sec-websocket-version'];
  53984. const extensions = {};
  53985. if (
  53986. req.method !== 'GET' ||
  53987. req.headers.upgrade.toLowerCase() !== 'websocket' ||
  53988. !key ||
  53989. !keyRegex.test(key) ||
  53990. (version !== 8 && version !== 13) ||
  53991. !this.shouldHandle(req)
  53992. ) {
  53993. return abortHandshake(socket, 400);
  53994. }
  53995. if (this.options.perMessageDeflate) {
  53996. const perMessageDeflate = new PerMessageDeflate(
  53997. this.options.perMessageDeflate,
  53998. true,
  53999. this.options.maxPayload
  54000. );
  54001. try {
  54002. const offers = parse$5(req.headers['sec-websocket-extensions']);
  54003. if (offers[PerMessageDeflate.extensionName]) {
  54004. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  54005. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  54006. }
  54007. } catch (err) {
  54008. return abortHandshake(socket, 400);
  54009. }
  54010. }
  54011. //
  54012. // Optionally call external client verification handler.
  54013. //
  54014. if (this.options.verifyClient) {
  54015. const info = {
  54016. origin:
  54017. req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
  54018. secure: !!(req.socket.authorized || req.socket.encrypted),
  54019. req
  54020. };
  54021. if (this.options.verifyClient.length === 2) {
  54022. this.options.verifyClient(info, (verified, code, message, headers) => {
  54023. if (!verified) {
  54024. return abortHandshake(socket, code || 401, message, headers);
  54025. }
  54026. this.completeUpgrade(key, extensions, req, socket, head, cb);
  54027. });
  54028. return;
  54029. }
  54030. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  54031. }
  54032. this.completeUpgrade(key, extensions, req, socket, head, cb);
  54033. }
  54034. /**
  54035. * Upgrade the connection to WebSocket.
  54036. *
  54037. * @param {String} key The value of the `Sec-WebSocket-Key` header
  54038. * @param {Object} extensions The accepted extensions
  54039. * @param {http.IncomingMessage} req The request object
  54040. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  54041. * server and client
  54042. * @param {Buffer} head The first packet of the upgraded stream
  54043. * @param {Function} cb Callback
  54044. * @throws {Error} If called more than once with the same socket
  54045. * @private
  54046. */
  54047. completeUpgrade(key, extensions, req, socket, head, cb) {
  54048. //
  54049. // Destroy the socket if the client has already sent a FIN packet.
  54050. //
  54051. if (!socket.readable || !socket.writable) return socket.destroy();
  54052. if (socket[kWebSocket]) {
  54053. throw new Error(
  54054. 'server.handleUpgrade() was called more than once with the same ' +
  54055. 'socket, possibly due to a misconfiguration'
  54056. );
  54057. }
  54058. if (this._state > RUNNING) return abortHandshake(socket, 503);
  54059. const digest = createHash('sha1')
  54060. .update(key + GUID)
  54061. .digest('base64');
  54062. const headers = [
  54063. 'HTTP/1.1 101 Switching Protocols',
  54064. 'Upgrade: websocket',
  54065. 'Connection: Upgrade',
  54066. `Sec-WebSocket-Accept: ${digest}`
  54067. ];
  54068. const ws = new WebSocket$1(null);
  54069. let protocol = req.headers['sec-websocket-protocol'];
  54070. if (protocol) {
  54071. protocol = protocol.split(',').map(trim);
  54072. //
  54073. // Optionally call external protocol selection handler.
  54074. //
  54075. if (this.options.handleProtocols) {
  54076. protocol = this.options.handleProtocols(protocol, req);
  54077. } else {
  54078. protocol = protocol[0];
  54079. }
  54080. if (protocol) {
  54081. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  54082. ws._protocol = protocol;
  54083. }
  54084. }
  54085. if (extensions[PerMessageDeflate.extensionName]) {
  54086. const params = extensions[PerMessageDeflate.extensionName].params;
  54087. const value = format({
  54088. [PerMessageDeflate.extensionName]: [params]
  54089. });
  54090. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  54091. ws._extensions = extensions;
  54092. }
  54093. //
  54094. // Allow external modification/inspection of handshake headers.
  54095. //
  54096. this.emit('headers', headers, req);
  54097. socket.write(headers.concat('\r\n').join('\r\n'));
  54098. socket.removeListener('error', socketOnError);
  54099. ws.setSocket(socket, head, this.options.maxPayload);
  54100. if (this.clients) {
  54101. this.clients.add(ws);
  54102. ws.on('close', () => this.clients.delete(ws));
  54103. }
  54104. cb(ws, req);
  54105. }
  54106. }
  54107. var websocketServer = WebSocketServer;
  54108. /**
  54109. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  54110. * pairs.
  54111. *
  54112. * @param {EventEmitter} server The event emitter
  54113. * @param {Object.<String, Function>} map The listeners to add
  54114. * @return {Function} A function that will remove the added listeners when
  54115. * called
  54116. * @private
  54117. */
  54118. function addListeners(server, map) {
  54119. for (const event of Object.keys(map)) server.on(event, map[event]);
  54120. return function removeListeners() {
  54121. for (const event of Object.keys(map)) {
  54122. server.removeListener(event, map[event]);
  54123. }
  54124. };
  54125. }
  54126. /**
  54127. * Emit a `'close'` event on an `EventEmitter`.
  54128. *
  54129. * @param {EventEmitter} server The event emitter
  54130. * @private
  54131. */
  54132. function emitClose(server) {
  54133. server._state = CLOSED;
  54134. server.emit('close');
  54135. }
  54136. /**
  54137. * Handle premature socket errors.
  54138. *
  54139. * @private
  54140. */
  54141. function socketOnError() {
  54142. this.destroy();
  54143. }
  54144. /**
  54145. * Close the connection when preconditions are not fulfilled.
  54146. *
  54147. * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
  54148. * @param {Number} code The HTTP response status code
  54149. * @param {String} [message] The HTTP response body
  54150. * @param {Object} [headers] Additional HTTP response headers
  54151. * @private
  54152. */
  54153. function abortHandshake(socket, code, message, headers) {
  54154. if (socket.writable) {
  54155. message = message || http$2.STATUS_CODES[code];
  54156. headers = {
  54157. Connection: 'close',
  54158. 'Content-Type': 'text/html',
  54159. 'Content-Length': Buffer.byteLength(message),
  54160. ...headers
  54161. };
  54162. socket.write(
  54163. `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` +
  54164. Object.keys(headers)
  54165. .map((h) => `${h}: ${headers[h]}`)
  54166. .join('\r\n') +
  54167. '\r\n\r\n' +
  54168. message
  54169. );
  54170. }
  54171. socket.removeListener('error', socketOnError);
  54172. socket.destroy();
  54173. }
  54174. /**
  54175. * Remove whitespace characters from both ends of a string.
  54176. *
  54177. * @param {String} str The string
  54178. * @return {String} A new string representing `str` stripped of whitespace
  54179. * characters from both its beginning and end
  54180. * @private
  54181. */
  54182. function trim(str) {
  54183. return str.trim();
  54184. }
  54185. const WebSocket = websocket;
  54186. WebSocket.createWebSocketStream = stream$2;
  54187. WebSocket.Server = websocketServer;
  54188. WebSocket.Receiver = receiver;
  54189. WebSocket.Sender = sender;
  54190. var ws = WebSocket;
  54191. const HMR_HEADER = 'vite-hmr';
  54192. function createWebSocketServer(server, config, httpsOptions) {
  54193. let wss;
  54194. let httpsServer = undefined;
  54195. const hmr = isObject$3(config.server.hmr) && config.server.hmr;
  54196. const wsServer = (hmr && hmr.server) || server;
  54197. if (wsServer) {
  54198. wss = new ws.Server({ noServer: true });
  54199. wsServer.on('upgrade', (req, socket, head) => {
  54200. if (req.headers['sec-websocket-protocol'] === HMR_HEADER) {
  54201. wss.handleUpgrade(req, socket, head, (ws) => {
  54202. wss.emit('connection', ws, req);
  54203. });
  54204. }
  54205. });
  54206. }
  54207. else {
  54208. const websocketServerOptions = {};
  54209. const port = (hmr && hmr.port) || 24678;
  54210. if (httpsOptions) {
  54211. // if we're serving the middlewares over https, the ws library doesn't support automatically creating an https server, so we need to do it ourselves
  54212. // create an inline https server and mount the websocket server to it
  54213. httpsServer = require$$1$4.createServer(httpsOptions, (req, res) => {
  54214. const statusCode = 426;
  54215. const body = require$$1$3.STATUS_CODES[statusCode];
  54216. if (!body)
  54217. throw new Error(`No body text found for the ${statusCode} status code`);
  54218. res.writeHead(statusCode, {
  54219. 'Content-Length': body.length,
  54220. 'Content-Type': 'text/plain'
  54221. });
  54222. res.end(body);
  54223. });
  54224. httpsServer.listen(port);
  54225. websocketServerOptions.server = httpsServer;
  54226. }
  54227. else {
  54228. // we don't need to serve over https, just let ws handle its own server
  54229. websocketServerOptions.port = port;
  54230. }
  54231. // vite dev server in middleware mode
  54232. wss = new ws.Server(websocketServerOptions);
  54233. }
  54234. wss.on('connection', (socket) => {
  54235. socket.send(JSON.stringify({ type: 'connected' }));
  54236. if (bufferedError) {
  54237. socket.send(JSON.stringify(bufferedError));
  54238. bufferedError = null;
  54239. }
  54240. });
  54241. wss.on('error', (e) => {
  54242. if (e.code !== 'EADDRINUSE') {
  54243. config.logger.error(source.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  54244. }
  54245. });
  54246. // On page reloads, if a file fails to compile and returns 500, the server
  54247. // sends the error payload before the client connection is established.
  54248. // If we have no open clients, buffer the error and send it to the next
  54249. // connected client.
  54250. let bufferedError = null;
  54251. return {
  54252. send(payload) {
  54253. if (payload.type === 'error' && !wss.clients.size) {
  54254. bufferedError = payload;
  54255. return;
  54256. }
  54257. const stringified = JSON.stringify(payload);
  54258. wss.clients.forEach((client) => {
  54259. if (client.readyState === ws.OPEN) {
  54260. client.send(stringified);
  54261. }
  54262. });
  54263. },
  54264. close() {
  54265. return new Promise((resolve, reject) => {
  54266. wss.close((err) => {
  54267. if (err) {
  54268. reject(err);
  54269. }
  54270. else {
  54271. if (httpsServer) {
  54272. httpsServer.close((err) => {
  54273. if (err) {
  54274. reject(err);
  54275. }
  54276. else {
  54277. resolve();
  54278. }
  54279. });
  54280. }
  54281. else {
  54282. resolve();
  54283. }
  54284. }
  54285. });
  54286. });
  54287. }
  54288. };
  54289. }
  54290. // this middleware is only active when (config.base !== '/')
  54291. function baseMiddleware({ config }) {
  54292. const base = config.base;
  54293. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  54294. return function viteBaseMiddleware(req, res, next) {
  54295. var _a;
  54296. const url = req.url;
  54297. const parsed = require$$0$a.parse(url);
  54298. const path = parsed.pathname || '/';
  54299. if (path.startsWith(base)) {
  54300. // rewrite url to remove base.. this ensures that other middleware does
  54301. // not need to consider base being prepended or not
  54302. req.url = url.replace(base, '/');
  54303. return next();
  54304. }
  54305. // skip redirect and error fallback on middleware mode, #4057
  54306. if (config.server.middlewareMode) {
  54307. return next();
  54308. }
  54309. if (path === '/' || path === '/index.html') {
  54310. // redirect root visit to based url
  54311. res.writeHead(302, {
  54312. Location: base
  54313. });
  54314. res.end();
  54315. return;
  54316. }
  54317. else if ((_a = req.headers.accept) === null || _a === void 0 ? void 0 : _a.includes('text/html')) {
  54318. // non-based page visit
  54319. const redirectPath = base + url.slice(1);
  54320. res.writeHead(404, {
  54321. 'Content-Type': 'text/html'
  54322. });
  54323. res.end(`The server is configured with a public base URL of ${base} - ` +
  54324. `did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
  54325. return;
  54326. }
  54327. next();
  54328. };
  54329. }
  54330. var httpProxy$2 = {exports: {}};
  54331. var eventemitter3 = {exports: {}};
  54332. (function (module) {
  54333. var has = Object.prototype.hasOwnProperty
  54334. , prefix = '~';
  54335. /**
  54336. * Constructor to create a storage for our `EE` objects.
  54337. * An `Events` instance is a plain object whose properties are event names.
  54338. *
  54339. * @constructor
  54340. * @private
  54341. */
  54342. function Events() {}
  54343. //
  54344. // We try to not inherit from `Object.prototype`. In some engines creating an
  54345. // instance in this way is faster than calling `Object.create(null)` directly.
  54346. // If `Object.create(null)` is not supported we prefix the event names with a
  54347. // character to make sure that the built-in object properties are not
  54348. // overridden or used as an attack vector.
  54349. //
  54350. if (Object.create) {
  54351. Events.prototype = Object.create(null);
  54352. //
  54353. // This hack is needed because the `__proto__` property is still inherited in
  54354. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  54355. //
  54356. if (!new Events().__proto__) prefix = false;
  54357. }
  54358. /**
  54359. * Representation of a single event listener.
  54360. *
  54361. * @param {Function} fn The listener function.
  54362. * @param {*} context The context to invoke the listener with.
  54363. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  54364. * @constructor
  54365. * @private
  54366. */
  54367. function EE(fn, context, once) {
  54368. this.fn = fn;
  54369. this.context = context;
  54370. this.once = once || false;
  54371. }
  54372. /**
  54373. * Add a listener for a given event.
  54374. *
  54375. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  54376. * @param {(String|Symbol)} event The event name.
  54377. * @param {Function} fn The listener function.
  54378. * @param {*} context The context to invoke the listener with.
  54379. * @param {Boolean} once Specify if the listener is a one-time listener.
  54380. * @returns {EventEmitter}
  54381. * @private
  54382. */
  54383. function addListener(emitter, event, fn, context, once) {
  54384. if (typeof fn !== 'function') {
  54385. throw new TypeError('The listener must be a function');
  54386. }
  54387. var listener = new EE(fn, context || emitter, once)
  54388. , evt = prefix ? prefix + event : event;
  54389. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  54390. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  54391. else emitter._events[evt] = [emitter._events[evt], listener];
  54392. return emitter;
  54393. }
  54394. /**
  54395. * Clear event by name.
  54396. *
  54397. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  54398. * @param {(String|Symbol)} evt The Event name.
  54399. * @private
  54400. */
  54401. function clearEvent(emitter, evt) {
  54402. if (--emitter._eventsCount === 0) emitter._events = new Events();
  54403. else delete emitter._events[evt];
  54404. }
  54405. /**
  54406. * Minimal `EventEmitter` interface that is molded against the Node.js
  54407. * `EventEmitter` interface.
  54408. *
  54409. * @constructor
  54410. * @public
  54411. */
  54412. function EventEmitter() {
  54413. this._events = new Events();
  54414. this._eventsCount = 0;
  54415. }
  54416. /**
  54417. * Return an array listing the events for which the emitter has registered
  54418. * listeners.
  54419. *
  54420. * @returns {Array}
  54421. * @public
  54422. */
  54423. EventEmitter.prototype.eventNames = function eventNames() {
  54424. var names = []
  54425. , events
  54426. , name;
  54427. if (this._eventsCount === 0) return names;
  54428. for (name in (events = this._events)) {
  54429. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  54430. }
  54431. if (Object.getOwnPropertySymbols) {
  54432. return names.concat(Object.getOwnPropertySymbols(events));
  54433. }
  54434. return names;
  54435. };
  54436. /**
  54437. * Return the listeners registered for a given event.
  54438. *
  54439. * @param {(String|Symbol)} event The event name.
  54440. * @returns {Array} The registered listeners.
  54441. * @public
  54442. */
  54443. EventEmitter.prototype.listeners = function listeners(event) {
  54444. var evt = prefix ? prefix + event : event
  54445. , handlers = this._events[evt];
  54446. if (!handlers) return [];
  54447. if (handlers.fn) return [handlers.fn];
  54448. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  54449. ee[i] = handlers[i].fn;
  54450. }
  54451. return ee;
  54452. };
  54453. /**
  54454. * Return the number of listeners listening to a given event.
  54455. *
  54456. * @param {(String|Symbol)} event The event name.
  54457. * @returns {Number} The number of listeners.
  54458. * @public
  54459. */
  54460. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  54461. var evt = prefix ? prefix + event : event
  54462. , listeners = this._events[evt];
  54463. if (!listeners) return 0;
  54464. if (listeners.fn) return 1;
  54465. return listeners.length;
  54466. };
  54467. /**
  54468. * Calls each of the listeners registered for a given event.
  54469. *
  54470. * @param {(String|Symbol)} event The event name.
  54471. * @returns {Boolean} `true` if the event had listeners, else `false`.
  54472. * @public
  54473. */
  54474. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  54475. var evt = prefix ? prefix + event : event;
  54476. if (!this._events[evt]) return false;
  54477. var listeners = this._events[evt]
  54478. , len = arguments.length
  54479. , args
  54480. , i;
  54481. if (listeners.fn) {
  54482. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  54483. switch (len) {
  54484. case 1: return listeners.fn.call(listeners.context), true;
  54485. case 2: return listeners.fn.call(listeners.context, a1), true;
  54486. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  54487. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  54488. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  54489. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  54490. }
  54491. for (i = 1, args = new Array(len -1); i < len; i++) {
  54492. args[i - 1] = arguments[i];
  54493. }
  54494. listeners.fn.apply(listeners.context, args);
  54495. } else {
  54496. var length = listeners.length
  54497. , j;
  54498. for (i = 0; i < length; i++) {
  54499. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  54500. switch (len) {
  54501. case 1: listeners[i].fn.call(listeners[i].context); break;
  54502. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  54503. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  54504. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  54505. default:
  54506. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  54507. args[j - 1] = arguments[j];
  54508. }
  54509. listeners[i].fn.apply(listeners[i].context, args);
  54510. }
  54511. }
  54512. }
  54513. return true;
  54514. };
  54515. /**
  54516. * Add a listener for a given event.
  54517. *
  54518. * @param {(String|Symbol)} event The event name.
  54519. * @param {Function} fn The listener function.
  54520. * @param {*} [context=this] The context to invoke the listener with.
  54521. * @returns {EventEmitter} `this`.
  54522. * @public
  54523. */
  54524. EventEmitter.prototype.on = function on(event, fn, context) {
  54525. return addListener(this, event, fn, context, false);
  54526. };
  54527. /**
  54528. * Add a one-time listener for a given event.
  54529. *
  54530. * @param {(String|Symbol)} event The event name.
  54531. * @param {Function} fn The listener function.
  54532. * @param {*} [context=this] The context to invoke the listener with.
  54533. * @returns {EventEmitter} `this`.
  54534. * @public
  54535. */
  54536. EventEmitter.prototype.once = function once(event, fn, context) {
  54537. return addListener(this, event, fn, context, true);
  54538. };
  54539. /**
  54540. * Remove the listeners of a given event.
  54541. *
  54542. * @param {(String|Symbol)} event The event name.
  54543. * @param {Function} fn Only remove the listeners that match this function.
  54544. * @param {*} context Only remove the listeners that have this context.
  54545. * @param {Boolean} once Only remove one-time listeners.
  54546. * @returns {EventEmitter} `this`.
  54547. * @public
  54548. */
  54549. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  54550. var evt = prefix ? prefix + event : event;
  54551. if (!this._events[evt]) return this;
  54552. if (!fn) {
  54553. clearEvent(this, evt);
  54554. return this;
  54555. }
  54556. var listeners = this._events[evt];
  54557. if (listeners.fn) {
  54558. if (
  54559. listeners.fn === fn &&
  54560. (!once || listeners.once) &&
  54561. (!context || listeners.context === context)
  54562. ) {
  54563. clearEvent(this, evt);
  54564. }
  54565. } else {
  54566. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  54567. if (
  54568. listeners[i].fn !== fn ||
  54569. (once && !listeners[i].once) ||
  54570. (context && listeners[i].context !== context)
  54571. ) {
  54572. events.push(listeners[i]);
  54573. }
  54574. }
  54575. //
  54576. // Reset the array, or remove it completely if we have no more listeners.
  54577. //
  54578. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  54579. else clearEvent(this, evt);
  54580. }
  54581. return this;
  54582. };
  54583. /**
  54584. * Remove all listeners, or those of the specified event.
  54585. *
  54586. * @param {(String|Symbol)} [event] The event name.
  54587. * @returns {EventEmitter} `this`.
  54588. * @public
  54589. */
  54590. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  54591. var evt;
  54592. if (event) {
  54593. evt = prefix ? prefix + event : event;
  54594. if (this._events[evt]) clearEvent(this, evt);
  54595. } else {
  54596. this._events = new Events();
  54597. this._eventsCount = 0;
  54598. }
  54599. return this;
  54600. };
  54601. //
  54602. // Alias methods names because people roll like that.
  54603. //
  54604. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  54605. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  54606. //
  54607. // Expose the prefix.
  54608. //
  54609. EventEmitter.prefixed = prefix;
  54610. //
  54611. // Allow `EventEmitter` to be imported as module namespace.
  54612. //
  54613. EventEmitter.EventEmitter = EventEmitter;
  54614. //
  54615. // Expose the module.
  54616. //
  54617. {
  54618. module.exports = EventEmitter;
  54619. }
  54620. }(eventemitter3));
  54621. var common$3 = {};
  54622. /**
  54623. * Check if we're required to add a port number.
  54624. *
  54625. * @see https://url.spec.whatwg.org/#default-port
  54626. * @param {Number|String} port Port number we need to check
  54627. * @param {String} protocol Protocol we need to check against.
  54628. * @returns {Boolean} Is it a default port for the given protocol
  54629. * @api private
  54630. */
  54631. var requiresPort = function required(port, protocol) {
  54632. protocol = protocol.split(':')[0];
  54633. port = +port;
  54634. if (!port) return false;
  54635. switch (protocol) {
  54636. case 'http':
  54637. case 'ws':
  54638. return port !== 80;
  54639. case 'https':
  54640. case 'wss':
  54641. return port !== 443;
  54642. case 'ftp':
  54643. return port !== 21;
  54644. case 'gopher':
  54645. return port !== 70;
  54646. case 'file':
  54647. return false;
  54648. }
  54649. return port !== 0;
  54650. };
  54651. (function (exports) {
  54652. var common = exports,
  54653. url = require$$0__default$7,
  54654. extend = require$$0__default$3._extend,
  54655. required = requiresPort;
  54656. var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
  54657. isSSL = /^https|wss/;
  54658. /**
  54659. * Simple Regex for testing if protocol is https
  54660. */
  54661. common.isSSL = isSSL;
  54662. /**
  54663. * Copies the right headers from `options` and `req` to
  54664. * `outgoing` which is then used to fire the proxied
  54665. * request.
  54666. *
  54667. * Examples:
  54668. *
  54669. * common.setupOutgoing(outgoing, options, req)
  54670. * // => { host: ..., hostname: ...}
  54671. *
  54672. * @param {Object} Outgoing Base object to be filled with required properties
  54673. * @param {Object} Options Config object passed to the proxy
  54674. * @param {ClientRequest} Req Request Object
  54675. * @param {String} Forward String to select forward or target
  54676. * @return {Object} Outgoing Object with all required properties set
  54677. *
  54678. * @api private
  54679. */
  54680. common.setupOutgoing = function(outgoing, options, req, forward) {
  54681. outgoing.port = options[forward || 'target'].port ||
  54682. (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80);
  54683. ['host', 'hostname', 'socketPath', 'pfx', 'key',
  54684. 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach(
  54685. function(e) { outgoing[e] = options[forward || 'target'][e]; }
  54686. );
  54687. outgoing.method = options.method || req.method;
  54688. outgoing.headers = extend({}, req.headers);
  54689. if (options.headers){
  54690. extend(outgoing.headers, options.headers);
  54691. }
  54692. if (options.auth) {
  54693. outgoing.auth = options.auth;
  54694. }
  54695. if (options.ca) {
  54696. outgoing.ca = options.ca;
  54697. }
  54698. if (isSSL.test(options[forward || 'target'].protocol)) {
  54699. outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure;
  54700. }
  54701. outgoing.agent = options.agent || false;
  54702. outgoing.localAddress = options.localAddress;
  54703. //
  54704. // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do
  54705. // as node core doesn't handle this COMPLETELY properly yet.
  54706. //
  54707. if (!outgoing.agent) {
  54708. outgoing.headers = outgoing.headers || {};
  54709. if (typeof outgoing.headers.connection !== 'string'
  54710. || !upgradeHeader.test(outgoing.headers.connection)
  54711. ) { outgoing.headers.connection = 'close'; }
  54712. }
  54713. // the final path is target path + relative path requested by user:
  54714. var target = options[forward || 'target'];
  54715. var targetPath = target && options.prependPath !== false
  54716. ? (target.path || '')
  54717. : '';
  54718. //
  54719. // Remark: Can we somehow not use url.parse as a perf optimization?
  54720. //
  54721. var outgoingPath = !options.toProxy
  54722. ? (url.parse(req.url).path || '')
  54723. : req.url;
  54724. //
  54725. // Remark: ignorePath will just straight up ignore whatever the request's
  54726. // path is. This can be labeled as FOOT-GUN material if you do not know what
  54727. // you are doing and are using conflicting options.
  54728. //
  54729. outgoingPath = !options.ignorePath ? outgoingPath : '';
  54730. outgoing.path = common.urlJoin(targetPath, outgoingPath);
  54731. if (options.changeOrigin) {
  54732. outgoing.headers.host =
  54733. required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host)
  54734. ? outgoing.host + ':' + outgoing.port
  54735. : outgoing.host;
  54736. }
  54737. return outgoing;
  54738. };
  54739. /**
  54740. * Set the proper configuration for sockets,
  54741. * set no delay and set keep alive, also set
  54742. * the timeout to 0.
  54743. *
  54744. * Examples:
  54745. *
  54746. * common.setupSocket(socket)
  54747. * // => Socket
  54748. *
  54749. * @param {Socket} Socket instance to setup
  54750. * @return {Socket} Return the configured socket.
  54751. *
  54752. * @api private
  54753. */
  54754. common.setupSocket = function(socket) {
  54755. socket.setTimeout(0);
  54756. socket.setNoDelay(true);
  54757. socket.setKeepAlive(true, 0);
  54758. return socket;
  54759. };
  54760. /**
  54761. * Get the port number from the host. Or guess it based on the connection type.
  54762. *
  54763. * @param {Request} req Incoming HTTP request.
  54764. *
  54765. * @return {String} The port number.
  54766. *
  54767. * @api private
  54768. */
  54769. common.getPort = function(req) {
  54770. var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : '';
  54771. return res ?
  54772. res[1] :
  54773. common.hasEncryptedConnection(req) ? '443' : '80';
  54774. };
  54775. /**
  54776. * Check if the request has an encrypted connection.
  54777. *
  54778. * @param {Request} req Incoming HTTP request.
  54779. *
  54780. * @return {Boolean} Whether the connection is encrypted or not.
  54781. *
  54782. * @api private
  54783. */
  54784. common.hasEncryptedConnection = function(req) {
  54785. return Boolean(req.connection.encrypted || req.connection.pair);
  54786. };
  54787. /**
  54788. * OS-agnostic join (doesn't break on URLs like path.join does on Windows)>
  54789. *
  54790. * @return {String} The generated path.
  54791. *
  54792. * @api private
  54793. */
  54794. common.urlJoin = function() {
  54795. //
  54796. // We do not want to mess with the query string. All we want to touch is the path.
  54797. //
  54798. var args = Array.prototype.slice.call(arguments),
  54799. lastIndex = args.length - 1,
  54800. last = args[lastIndex],
  54801. lastSegs = last.split('?'),
  54802. retSegs;
  54803. args[lastIndex] = lastSegs.shift();
  54804. //
  54805. // Join all strings, but remove empty strings so we don't get extra slashes from
  54806. // joining e.g. ['', 'am']
  54807. //
  54808. retSegs = [
  54809. args.filter(Boolean).join('/')
  54810. .replace(/\/+/g, '/')
  54811. .replace('http:/', 'http://')
  54812. .replace('https:/', 'https://')
  54813. ];
  54814. // Only join the query string if it exists so we don't have trailing a '?'
  54815. // on every request
  54816. // Handle case where there could be multiple ? in the URL.
  54817. retSegs.push.apply(retSegs, lastSegs);
  54818. return retSegs.join('?')
  54819. };
  54820. /**
  54821. * Rewrites or removes the domain of a cookie header
  54822. *
  54823. * @param {String|Array} Header
  54824. * @param {Object} Config, mapping of domain to rewritten domain.
  54825. * '*' key to match any domain, null value to remove the domain.
  54826. *
  54827. * @api private
  54828. */
  54829. common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {
  54830. if (Array.isArray(header)) {
  54831. return header.map(function (headerElement) {
  54832. return rewriteCookieProperty(headerElement, config, property);
  54833. });
  54834. }
  54835. return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) {
  54836. var newValue;
  54837. if (previousValue in config) {
  54838. newValue = config[previousValue];
  54839. } else if ('*' in config) {
  54840. newValue = config['*'];
  54841. } else {
  54842. //no match, return previous value
  54843. return match;
  54844. }
  54845. if (newValue) {
  54846. //replace value
  54847. return prefix + newValue;
  54848. } else {
  54849. //remove value
  54850. return '';
  54851. }
  54852. });
  54853. };
  54854. /**
  54855. * Check the host and see if it potentially has a port in it (keep it simple)
  54856. *
  54857. * @returns {Boolean} Whether we have one or not
  54858. *
  54859. * @api private
  54860. */
  54861. function hasPort(host) {
  54862. return !!~host.indexOf(':');
  54863. }}(common$3));
  54864. var url$2 = require$$0__default$7,
  54865. common$2 = common$3;
  54866. var redirectRegex = /^201|30(1|2|7|8)$/;
  54867. /*!
  54868. * Array of passes.
  54869. *
  54870. * A `pass` is just a function that is executed on `req, res, options`
  54871. * so that you can easily add new checks while still keeping the base
  54872. * flexible.
  54873. */
  54874. var webOutgoing = { // <--
  54875. /**
  54876. * If is a HTTP 1.0 request, remove chunk headers
  54877. *
  54878. * @param {ClientRequest} Req Request object
  54879. * @param {IncomingMessage} Res Response object
  54880. * @param {proxyResponse} Res Response object from the proxy request
  54881. *
  54882. * @api private
  54883. */
  54884. removeChunked: function removeChunked(req, res, proxyRes) {
  54885. if (req.httpVersion === '1.0') {
  54886. delete proxyRes.headers['transfer-encoding'];
  54887. }
  54888. },
  54889. /**
  54890. * If is a HTTP 1.0 request, set the correct connection header
  54891. * or if connection header not present, then use `keep-alive`
  54892. *
  54893. * @param {ClientRequest} Req Request object
  54894. * @param {IncomingMessage} Res Response object
  54895. * @param {proxyResponse} Res Response object from the proxy request
  54896. *
  54897. * @api private
  54898. */
  54899. setConnection: function setConnection(req, res, proxyRes) {
  54900. if (req.httpVersion === '1.0') {
  54901. proxyRes.headers.connection = req.headers.connection || 'close';
  54902. } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {
  54903. proxyRes.headers.connection = req.headers.connection || 'keep-alive';
  54904. }
  54905. },
  54906. setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {
  54907. if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
  54908. && proxyRes.headers['location']
  54909. && redirectRegex.test(proxyRes.statusCode)) {
  54910. var target = url$2.parse(options.target);
  54911. var u = url$2.parse(proxyRes.headers['location']);
  54912. // make sure the redirected host matches the target host before rewriting
  54913. if (target.host != u.host) {
  54914. return;
  54915. }
  54916. if (options.hostRewrite) {
  54917. u.host = options.hostRewrite;
  54918. } else if (options.autoRewrite) {
  54919. u.host = req.headers['host'];
  54920. }
  54921. if (options.protocolRewrite) {
  54922. u.protocol = options.protocolRewrite;
  54923. }
  54924. proxyRes.headers['location'] = u.format();
  54925. }
  54926. },
  54927. /**
  54928. * Copy headers from proxyResponse to response
  54929. * set each header in response object.
  54930. *
  54931. * @param {ClientRequest} Req Request object
  54932. * @param {IncomingMessage} Res Response object
  54933. * @param {proxyResponse} Res Response object from the proxy request
  54934. * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
  54935. *
  54936. * @api private
  54937. */
  54938. writeHeaders: function writeHeaders(req, res, proxyRes, options) {
  54939. var rewriteCookieDomainConfig = options.cookieDomainRewrite,
  54940. rewriteCookiePathConfig = options.cookiePathRewrite,
  54941. preserveHeaderKeyCase = options.preserveHeaderKeyCase,
  54942. rawHeaderKeyMap,
  54943. setHeader = function(key, header) {
  54944. if (header == undefined) return;
  54945. if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
  54946. header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');
  54947. }
  54948. if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {
  54949. header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');
  54950. }
  54951. res.setHeader(String(key).trim(), header);
  54952. };
  54953. if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''
  54954. rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
  54955. }
  54956. if (typeof rewriteCookiePathConfig === 'string') { //also test for ''
  54957. rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };
  54958. }
  54959. // message.rawHeaders is added in: v0.11.6
  54960. // https://nodejs.org/api/http.html#http_message_rawheaders
  54961. if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
  54962. rawHeaderKeyMap = {};
  54963. for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
  54964. var key = proxyRes.rawHeaders[i];
  54965. rawHeaderKeyMap[key.toLowerCase()] = key;
  54966. }
  54967. }
  54968. Object.keys(proxyRes.headers).forEach(function(key) {
  54969. var header = proxyRes.headers[key];
  54970. if (preserveHeaderKeyCase && rawHeaderKeyMap) {
  54971. key = rawHeaderKeyMap[key] || key;
  54972. }
  54973. setHeader(key, header);
  54974. });
  54975. },
  54976. /**
  54977. * Set the statusCode from the proxyResponse
  54978. *
  54979. * @param {ClientRequest} Req Request object
  54980. * @param {IncomingMessage} Res Response object
  54981. * @param {proxyResponse} Res Response object from the proxy request
  54982. *
  54983. * @api private
  54984. */
  54985. writeStatusCode: function writeStatusCode(req, res, proxyRes) {
  54986. // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
  54987. if(proxyRes.statusMessage) {
  54988. res.statusCode = proxyRes.statusCode;
  54989. res.statusMessage = proxyRes.statusMessage;
  54990. } else {
  54991. res.statusCode = proxyRes.statusCode;
  54992. }
  54993. }
  54994. };
  54995. var followRedirects$1 = {exports: {}};
  54996. var debug$5;
  54997. var debug_1 = function () {
  54998. if (!debug$5) {
  54999. try {
  55000. /* eslint global-require: off */
  55001. debug$5 = src$3.exports("follow-redirects");
  55002. }
  55003. catch (error) { /* */ }
  55004. if (typeof debug$5 !== "function") {
  55005. debug$5 = function () { /* */ };
  55006. }
  55007. }
  55008. debug$5.apply(null, arguments);
  55009. };
  55010. var url$1 = require$$0__default$7;
  55011. var URL$1 = url$1.URL;
  55012. var http$1 = require$$1__default$1;
  55013. var https$1 = require$$1__default$3;
  55014. var Writable = require$$0__default$2.Writable;
  55015. var assert$1 = require$$6__default;
  55016. var debug$4 = debug_1;
  55017. // Create handlers that pass events from native requests
  55018. var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
  55019. var eventHandlers = Object.create(null);
  55020. events.forEach(function (event) {
  55021. eventHandlers[event] = function (arg1, arg2, arg3) {
  55022. this._redirectable.emit(event, arg1, arg2, arg3);
  55023. };
  55024. });
  55025. // Error types with codes
  55026. var RedirectionError = createErrorType(
  55027. "ERR_FR_REDIRECTION_FAILURE",
  55028. ""
  55029. );
  55030. var TooManyRedirectsError = createErrorType(
  55031. "ERR_FR_TOO_MANY_REDIRECTS",
  55032. "Maximum number of redirects exceeded"
  55033. );
  55034. var MaxBodyLengthExceededError = createErrorType(
  55035. "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
  55036. "Request body larger than maxBodyLength limit"
  55037. );
  55038. var WriteAfterEndError = createErrorType(
  55039. "ERR_STREAM_WRITE_AFTER_END",
  55040. "write after end"
  55041. );
  55042. // An HTTP(S) request that can be redirected
  55043. function RedirectableRequest(options, responseCallback) {
  55044. // Initialize the request
  55045. Writable.call(this);
  55046. this._sanitizeOptions(options);
  55047. this._options = options;
  55048. this._ended = false;
  55049. this._ending = false;
  55050. this._redirectCount = 0;
  55051. this._redirects = [];
  55052. this._requestBodyLength = 0;
  55053. this._requestBodyBuffers = [];
  55054. // Attach a callback if passed
  55055. if (responseCallback) {
  55056. this.on("response", responseCallback);
  55057. }
  55058. // React to responses of native requests
  55059. var self = this;
  55060. this._onNativeResponse = function (response) {
  55061. self._processResponse(response);
  55062. };
  55063. // Perform the first request
  55064. this._performRequest();
  55065. }
  55066. RedirectableRequest.prototype = Object.create(Writable.prototype);
  55067. RedirectableRequest.prototype.abort = function () {
  55068. abortRequest(this._currentRequest);
  55069. this.emit("abort");
  55070. };
  55071. // Writes buffered data to the current native request
  55072. RedirectableRequest.prototype.write = function (data, encoding, callback) {
  55073. // Writing is not allowed if end has been called
  55074. if (this._ending) {
  55075. throw new WriteAfterEndError();
  55076. }
  55077. // Validate input and shift parameters if necessary
  55078. if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
  55079. throw new TypeError("data should be a string, Buffer or Uint8Array");
  55080. }
  55081. if (typeof encoding === "function") {
  55082. callback = encoding;
  55083. encoding = null;
  55084. }
  55085. // Ignore empty buffers, since writing them doesn't invoke the callback
  55086. // https://github.com/nodejs/node/issues/22066
  55087. if (data.length === 0) {
  55088. if (callback) {
  55089. callback();
  55090. }
  55091. return;
  55092. }
  55093. // Only write when we don't exceed the maximum body length
  55094. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  55095. this._requestBodyLength += data.length;
  55096. this._requestBodyBuffers.push({ data: data, encoding: encoding });
  55097. this._currentRequest.write(data, encoding, callback);
  55098. }
  55099. // Error when we exceed the maximum body length
  55100. else {
  55101. this.emit("error", new MaxBodyLengthExceededError());
  55102. this.abort();
  55103. }
  55104. };
  55105. // Ends the current native request
  55106. RedirectableRequest.prototype.end = function (data, encoding, callback) {
  55107. // Shift parameters if necessary
  55108. if (typeof data === "function") {
  55109. callback = data;
  55110. data = encoding = null;
  55111. }
  55112. else if (typeof encoding === "function") {
  55113. callback = encoding;
  55114. encoding = null;
  55115. }
  55116. // Write data if needed and end
  55117. if (!data) {
  55118. this._ended = this._ending = true;
  55119. this._currentRequest.end(null, null, callback);
  55120. }
  55121. else {
  55122. var self = this;
  55123. var currentRequest = this._currentRequest;
  55124. this.write(data, encoding, function () {
  55125. self._ended = true;
  55126. currentRequest.end(null, null, callback);
  55127. });
  55128. this._ending = true;
  55129. }
  55130. };
  55131. // Sets a header value on the current native request
  55132. RedirectableRequest.prototype.setHeader = function (name, value) {
  55133. this._options.headers[name] = value;
  55134. this._currentRequest.setHeader(name, value);
  55135. };
  55136. // Clears a header value on the current native request
  55137. RedirectableRequest.prototype.removeHeader = function (name) {
  55138. delete this._options.headers[name];
  55139. this._currentRequest.removeHeader(name);
  55140. };
  55141. // Global timeout for all underlying requests
  55142. RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
  55143. var self = this;
  55144. if (callback) {
  55145. this.on("timeout", callback);
  55146. }
  55147. function destroyOnTimeout(socket) {
  55148. socket.setTimeout(msecs);
  55149. socket.removeListener("timeout", socket.destroy);
  55150. socket.addListener("timeout", socket.destroy);
  55151. }
  55152. // Sets up a timer to trigger a timeout event
  55153. function startTimer(socket) {
  55154. if (self._timeout) {
  55155. clearTimeout(self._timeout);
  55156. }
  55157. self._timeout = setTimeout(function () {
  55158. self.emit("timeout");
  55159. clearTimer();
  55160. }, msecs);
  55161. destroyOnTimeout(socket);
  55162. }
  55163. // Prevent a timeout from triggering
  55164. function clearTimer() {
  55165. clearTimeout(this._timeout);
  55166. if (callback) {
  55167. self.removeListener("timeout", callback);
  55168. }
  55169. if (!this.socket) {
  55170. self._currentRequest.removeListener("socket", startTimer);
  55171. }
  55172. }
  55173. // Start the timer when the socket is opened
  55174. if (this.socket) {
  55175. startTimer(this.socket);
  55176. }
  55177. else {
  55178. this._currentRequest.once("socket", startTimer);
  55179. }
  55180. this.on("socket", destroyOnTimeout);
  55181. this.once("response", clearTimer);
  55182. this.once("error", clearTimer);
  55183. return this;
  55184. };
  55185. // Proxy all other public ClientRequest methods
  55186. [
  55187. "flushHeaders", "getHeader",
  55188. "setNoDelay", "setSocketKeepAlive",
  55189. ].forEach(function (method) {
  55190. RedirectableRequest.prototype[method] = function (a, b) {
  55191. return this._currentRequest[method](a, b);
  55192. };
  55193. });
  55194. // Proxy all public ClientRequest properties
  55195. ["aborted", "connection", "socket"].forEach(function (property) {
  55196. Object.defineProperty(RedirectableRequest.prototype, property, {
  55197. get: function () { return this._currentRequest[property]; },
  55198. });
  55199. });
  55200. RedirectableRequest.prototype._sanitizeOptions = function (options) {
  55201. // Ensure headers are always present
  55202. if (!options.headers) {
  55203. options.headers = {};
  55204. }
  55205. // Since http.request treats host as an alias of hostname,
  55206. // but the url module interprets host as hostname plus port,
  55207. // eliminate the host property to avoid confusion.
  55208. if (options.host) {
  55209. // Use hostname if set, because it has precedence
  55210. if (!options.hostname) {
  55211. options.hostname = options.host;
  55212. }
  55213. delete options.host;
  55214. }
  55215. // Complete the URL object when necessary
  55216. if (!options.pathname && options.path) {
  55217. var searchPos = options.path.indexOf("?");
  55218. if (searchPos < 0) {
  55219. options.pathname = options.path;
  55220. }
  55221. else {
  55222. options.pathname = options.path.substring(0, searchPos);
  55223. options.search = options.path.substring(searchPos);
  55224. }
  55225. }
  55226. };
  55227. // Executes the next native request (initial or redirect)
  55228. RedirectableRequest.prototype._performRequest = function () {
  55229. // Load the native protocol
  55230. var protocol = this._options.protocol;
  55231. var nativeProtocol = this._options.nativeProtocols[protocol];
  55232. if (!nativeProtocol) {
  55233. this.emit("error", new TypeError("Unsupported protocol " + protocol));
  55234. return;
  55235. }
  55236. // If specified, use the agent corresponding to the protocol
  55237. // (HTTP and HTTPS use different types of agents)
  55238. if (this._options.agents) {
  55239. var scheme = protocol.substr(0, protocol.length - 1);
  55240. this._options.agent = this._options.agents[scheme];
  55241. }
  55242. // Create the native request
  55243. var request = this._currentRequest =
  55244. nativeProtocol.request(this._options, this._onNativeResponse);
  55245. this._currentUrl = url$1.format(this._options);
  55246. // Set up event handlers
  55247. request._redirectable = this;
  55248. for (var e = 0; e < events.length; e++) {
  55249. request.on(events[e], eventHandlers[events[e]]);
  55250. }
  55251. // End a redirected request
  55252. // (The first request must be ended explicitly with RedirectableRequest#end)
  55253. if (this._isRedirect) {
  55254. // Write the request entity and end.
  55255. var i = 0;
  55256. var self = this;
  55257. var buffers = this._requestBodyBuffers;
  55258. (function writeNext(error) {
  55259. // Only write if this request has not been redirected yet
  55260. /* istanbul ignore else */
  55261. if (request === self._currentRequest) {
  55262. // Report any write errors
  55263. /* istanbul ignore if */
  55264. if (error) {
  55265. self.emit("error", error);
  55266. }
  55267. // Write the next buffer if there are still left
  55268. else if (i < buffers.length) {
  55269. var buffer = buffers[i++];
  55270. /* istanbul ignore else */
  55271. if (!request.finished) {
  55272. request.write(buffer.data, buffer.encoding, writeNext);
  55273. }
  55274. }
  55275. // End the request if `end` has been called on us
  55276. else if (self._ended) {
  55277. request.end();
  55278. }
  55279. }
  55280. }());
  55281. }
  55282. };
  55283. // Processes a response from the current native request
  55284. RedirectableRequest.prototype._processResponse = function (response) {
  55285. // Store the redirected response
  55286. var statusCode = response.statusCode;
  55287. if (this._options.trackRedirects) {
  55288. this._redirects.push({
  55289. url: this._currentUrl,
  55290. headers: response.headers,
  55291. statusCode: statusCode,
  55292. });
  55293. }
  55294. // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
  55295. // that further action needs to be taken by the user agent in order to
  55296. // fulfill the request. If a Location header field is provided,
  55297. // the user agent MAY automatically redirect its request to the URI
  55298. // referenced by the Location field value,
  55299. // even if the specific status code is not understood.
  55300. var location = response.headers.location;
  55301. if (location && this._options.followRedirects !== false &&
  55302. statusCode >= 300 && statusCode < 400) {
  55303. // Abort the current request
  55304. abortRequest(this._currentRequest);
  55305. // Discard the remainder of the response to avoid waiting for data
  55306. response.destroy();
  55307. // RFC7231§6.4: A client SHOULD detect and intervene
  55308. // in cyclical redirections (i.e., "infinite" redirection loops).
  55309. if (++this._redirectCount > this._options.maxRedirects) {
  55310. this.emit("error", new TooManyRedirectsError());
  55311. return;
  55312. }
  55313. // RFC7231§6.4: Automatic redirection needs to done with
  55314. // care for methods not known to be safe, […]
  55315. // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
  55316. // the request method from POST to GET for the subsequent request.
  55317. if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
  55318. // RFC7231§6.4.4: The 303 (See Other) status code indicates that
  55319. // the server is redirecting the user agent to a different resource […]
  55320. // A user agent can perform a retrieval request targeting that URI
  55321. // (a GET or HEAD request if using HTTP) […]
  55322. (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
  55323. this._options.method = "GET";
  55324. // Drop a possible entity and headers related to it
  55325. this._requestBodyBuffers = [];
  55326. removeMatchingHeaders(/^content-/i, this._options.headers);
  55327. }
  55328. // Drop the Host header, as the redirect might lead to a different host
  55329. var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) ||
  55330. url$1.parse(this._currentUrl).hostname;
  55331. // Create the redirected request
  55332. var redirectUrl = url$1.resolve(this._currentUrl, location);
  55333. debug$4("redirecting to", redirectUrl);
  55334. this._isRedirect = true;
  55335. var redirectUrlParts = url$1.parse(redirectUrl);
  55336. Object.assign(this._options, redirectUrlParts);
  55337. // Drop the Authorization header if redirecting to another host
  55338. if (redirectUrlParts.hostname !== previousHostName) {
  55339. removeMatchingHeaders(/^authorization$/i, this._options.headers);
  55340. }
  55341. // Evaluate the beforeRedirect callback
  55342. if (typeof this._options.beforeRedirect === "function") {
  55343. var responseDetails = { headers: response.headers };
  55344. try {
  55345. this._options.beforeRedirect.call(null, this._options, responseDetails);
  55346. }
  55347. catch (err) {
  55348. this.emit("error", err);
  55349. return;
  55350. }
  55351. this._sanitizeOptions(this._options);
  55352. }
  55353. // Perform the redirected request
  55354. try {
  55355. this._performRequest();
  55356. }
  55357. catch (cause) {
  55358. var error = new RedirectionError("Redirected request failed: " + cause.message);
  55359. error.cause = cause;
  55360. this.emit("error", error);
  55361. }
  55362. }
  55363. else {
  55364. // The response is not a redirect; return it as-is
  55365. response.responseUrl = this._currentUrl;
  55366. response.redirects = this._redirects;
  55367. this.emit("response", response);
  55368. // Clean up
  55369. this._requestBodyBuffers = [];
  55370. }
  55371. };
  55372. // Wraps the key/value object of protocols with redirect functionality
  55373. function wrap(protocols) {
  55374. // Default settings
  55375. var exports = {
  55376. maxRedirects: 21,
  55377. maxBodyLength: 10 * 1024 * 1024,
  55378. };
  55379. // Wrap each protocol
  55380. var nativeProtocols = {};
  55381. Object.keys(protocols).forEach(function (scheme) {
  55382. var protocol = scheme + ":";
  55383. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  55384. var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
  55385. // Executes a request, following redirects
  55386. function request(input, options, callback) {
  55387. // Parse parameters
  55388. if (typeof input === "string") {
  55389. var urlStr = input;
  55390. try {
  55391. input = urlToOptions(new URL$1(urlStr));
  55392. }
  55393. catch (err) {
  55394. /* istanbul ignore next */
  55395. input = url$1.parse(urlStr);
  55396. }
  55397. }
  55398. else if (URL$1 && (input instanceof URL$1)) {
  55399. input = urlToOptions(input);
  55400. }
  55401. else {
  55402. callback = options;
  55403. options = input;
  55404. input = { protocol: protocol };
  55405. }
  55406. if (typeof options === "function") {
  55407. callback = options;
  55408. options = null;
  55409. }
  55410. // Set defaults
  55411. options = Object.assign({
  55412. maxRedirects: exports.maxRedirects,
  55413. maxBodyLength: exports.maxBodyLength,
  55414. }, input, options);
  55415. options.nativeProtocols = nativeProtocols;
  55416. assert$1.equal(options.protocol, protocol, "protocol mismatch");
  55417. debug$4("options", options);
  55418. return new RedirectableRequest(options, callback);
  55419. }
  55420. // Executes a GET request, following redirects
  55421. function get(input, options, callback) {
  55422. var wrappedRequest = wrappedProtocol.request(input, options, callback);
  55423. wrappedRequest.end();
  55424. return wrappedRequest;
  55425. }
  55426. // Expose the properties on the wrapped protocol
  55427. Object.defineProperties(wrappedProtocol, {
  55428. request: { value: request, configurable: true, enumerable: true, writable: true },
  55429. get: { value: get, configurable: true, enumerable: true, writable: true },
  55430. });
  55431. });
  55432. return exports;
  55433. }
  55434. /* istanbul ignore next */
  55435. function noop$2() { /* empty */ }
  55436. // from https://github.com/nodejs/node/blob/master/lib/internal/url.js
  55437. function urlToOptions(urlObject) {
  55438. var options = {
  55439. protocol: urlObject.protocol,
  55440. hostname: urlObject.hostname.startsWith("[") ?
  55441. /* istanbul ignore next */
  55442. urlObject.hostname.slice(1, -1) :
  55443. urlObject.hostname,
  55444. hash: urlObject.hash,
  55445. search: urlObject.search,
  55446. pathname: urlObject.pathname,
  55447. path: urlObject.pathname + urlObject.search,
  55448. href: urlObject.href,
  55449. };
  55450. if (urlObject.port !== "") {
  55451. options.port = Number(urlObject.port);
  55452. }
  55453. return options;
  55454. }
  55455. function removeMatchingHeaders(regex, headers) {
  55456. var lastValue;
  55457. for (var header in headers) {
  55458. if (regex.test(header)) {
  55459. lastValue = headers[header];
  55460. delete headers[header];
  55461. }
  55462. }
  55463. return lastValue;
  55464. }
  55465. function createErrorType(code, defaultMessage) {
  55466. function CustomError(message) {
  55467. Error.captureStackTrace(this, this.constructor);
  55468. this.message = message || defaultMessage;
  55469. }
  55470. CustomError.prototype = new Error();
  55471. CustomError.prototype.constructor = CustomError;
  55472. CustomError.prototype.name = "Error [" + code + "]";
  55473. CustomError.prototype.code = code;
  55474. return CustomError;
  55475. }
  55476. function abortRequest(request) {
  55477. for (var e = 0; e < events.length; e++) {
  55478. request.removeListener(events[e], eventHandlers[events[e]]);
  55479. }
  55480. request.on("error", noop$2);
  55481. request.abort();
  55482. }
  55483. // Exports
  55484. followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
  55485. followRedirects$1.exports.wrap = wrap;
  55486. var httpNative = require$$1__default$1,
  55487. httpsNative = require$$1__default$3,
  55488. web_o = webOutgoing,
  55489. common$1 = common$3,
  55490. followRedirects = followRedirects$1.exports;
  55491. web_o = Object.keys(web_o).map(function(pass) {
  55492. return web_o[pass];
  55493. });
  55494. var nativeAgents = { http: httpNative, https: httpsNative };
  55495. /*!
  55496. * Array of passes.
  55497. *
  55498. * A `pass` is just a function that is executed on `req, res, options`
  55499. * so that you can easily add new checks while still keeping the base
  55500. * flexible.
  55501. */
  55502. var webIncoming = {
  55503. /**
  55504. * Sets `content-length` to '0' if request is of DELETE type.
  55505. *
  55506. * @param {ClientRequest} Req Request object
  55507. * @param {IncomingMessage} Res Response object
  55508. * @param {Object} Options Config object passed to the proxy
  55509. *
  55510. * @api private
  55511. */
  55512. deleteLength: function deleteLength(req, res, options) {
  55513. if((req.method === 'DELETE' || req.method === 'OPTIONS')
  55514. && !req.headers['content-length']) {
  55515. req.headers['content-length'] = '0';
  55516. delete req.headers['transfer-encoding'];
  55517. }
  55518. },
  55519. /**
  55520. * Sets timeout in request socket if it was specified in options.
  55521. *
  55522. * @param {ClientRequest} Req Request object
  55523. * @param {IncomingMessage} Res Response object
  55524. * @param {Object} Options Config object passed to the proxy
  55525. *
  55526. * @api private
  55527. */
  55528. timeout: function timeout(req, res, options) {
  55529. if(options.timeout) {
  55530. req.socket.setTimeout(options.timeout);
  55531. }
  55532. },
  55533. /**
  55534. * Sets `x-forwarded-*` headers if specified in config.
  55535. *
  55536. * @param {ClientRequest} Req Request object
  55537. * @param {IncomingMessage} Res Response object
  55538. * @param {Object} Options Config object passed to the proxy
  55539. *
  55540. * @api private
  55541. */
  55542. XHeaders: function XHeaders(req, res, options) {
  55543. if(!options.xfwd) return;
  55544. var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req);
  55545. var values = {
  55546. for : req.connection.remoteAddress || req.socket.remoteAddress,
  55547. port : common$1.getPort(req),
  55548. proto: encrypted ? 'https' : 'http'
  55549. };
  55550. ['for', 'port', 'proto'].forEach(function(header) {
  55551. req.headers['x-forwarded-' + header] =
  55552. (req.headers['x-forwarded-' + header] || '') +
  55553. (req.headers['x-forwarded-' + header] ? ',' : '') +
  55554. values[header];
  55555. });
  55556. req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';
  55557. },
  55558. /**
  55559. * Does the actual proxying. If `forward` is enabled fires up
  55560. * a ForwardStream, same happens for ProxyStream. The request
  55561. * just dies otherwise.
  55562. *
  55563. * @param {ClientRequest} Req Request object
  55564. * @param {IncomingMessage} Res Response object
  55565. * @param {Object} Options Config object passed to the proxy
  55566. *
  55567. * @api private
  55568. */
  55569. stream: function stream(req, res, options, _, server, clb) {
  55570. // And we begin!
  55571. server.emit('start', req, res, options.target || options.forward);
  55572. var agents = options.followRedirects ? followRedirects : nativeAgents;
  55573. var http = agents.http;
  55574. var https = agents.https;
  55575. if(options.forward) {
  55576. // If forward enable, so just pipe the request
  55577. var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
  55578. common$1.setupOutgoing(options.ssl || {}, options, req, 'forward')
  55579. );
  55580. // error handler (e.g. ECONNRESET, ECONNREFUSED)
  55581. // Handle errors on incoming request as well as it makes sense to
  55582. var forwardError = createErrorHandler(forwardReq, options.forward);
  55583. req.on('error', forwardError);
  55584. forwardReq.on('error', forwardError);
  55585. (options.buffer || req).pipe(forwardReq);
  55586. if(!options.target) { return res.end(); }
  55587. }
  55588. // Request initalization
  55589. var proxyReq = (options.target.protocol === 'https:' ? https : http).request(
  55590. common$1.setupOutgoing(options.ssl || {}, options, req)
  55591. );
  55592. // Enable developers to modify the proxyReq before headers are sent
  55593. proxyReq.on('socket', function(socket) {
  55594. if(server && !proxyReq.getHeader('expect')) {
  55595. server.emit('proxyReq', proxyReq, req, res, options);
  55596. }
  55597. });
  55598. // allow outgoing socket to timeout so that we could
  55599. // show an error page at the initial request
  55600. if(options.proxyTimeout) {
  55601. proxyReq.setTimeout(options.proxyTimeout, function() {
  55602. proxyReq.abort();
  55603. });
  55604. }
  55605. // Ensure we abort proxy if request is aborted
  55606. req.on('aborted', function () {
  55607. proxyReq.abort();
  55608. });
  55609. // handle errors in proxy and incoming request, just like for forward proxy
  55610. var proxyError = createErrorHandler(proxyReq, options.target);
  55611. req.on('error', proxyError);
  55612. proxyReq.on('error', proxyError);
  55613. function createErrorHandler(proxyReq, url) {
  55614. return function proxyError(err) {
  55615. if (req.socket.destroyed && err.code === 'ECONNRESET') {
  55616. server.emit('econnreset', err, req, res, url);
  55617. return proxyReq.abort();
  55618. }
  55619. if (clb) {
  55620. clb(err, req, res, url);
  55621. } else {
  55622. server.emit('error', err, req, res, url);
  55623. }
  55624. }
  55625. }
  55626. (options.buffer || req).pipe(proxyReq);
  55627. proxyReq.on('response', function(proxyRes) {
  55628. if(server) { server.emit('proxyRes', proxyRes, req, res); }
  55629. if(!res.headersSent && !options.selfHandleResponse) {
  55630. for(var i=0; i < web_o.length; i++) {
  55631. if(web_o[i](req, res, proxyRes, options)) { break; }
  55632. }
  55633. }
  55634. if (!res.finished) {
  55635. // Allow us to listen when the proxy has completed
  55636. proxyRes.on('end', function () {
  55637. if (server) server.emit('end', req, res, proxyRes);
  55638. });
  55639. // We pipe to the response unless its expected to be handled by the user
  55640. if (!options.selfHandleResponse) proxyRes.pipe(res);
  55641. } else {
  55642. if (server) server.emit('end', req, res, proxyRes);
  55643. }
  55644. });
  55645. }
  55646. };
  55647. var http = require$$1__default$1,
  55648. https = require$$1__default$3,
  55649. common = common$3;
  55650. /*!
  55651. * Array of passes.
  55652. *
  55653. * A `pass` is just a function that is executed on `req, socket, options`
  55654. * so that you can easily add new checks while still keeping the base
  55655. * flexible.
  55656. */
  55657. /*
  55658. * Websockets Passes
  55659. *
  55660. */
  55661. var wsIncoming = {
  55662. /**
  55663. * WebSocket requests must have the `GET` method and
  55664. * the `upgrade:websocket` header
  55665. *
  55666. * @param {ClientRequest} Req Request object
  55667. * @param {Socket} Websocket
  55668. *
  55669. * @api private
  55670. */
  55671. checkMethodAndHeader : function checkMethodAndHeader(req, socket) {
  55672. if (req.method !== 'GET' || !req.headers.upgrade) {
  55673. socket.destroy();
  55674. return true;
  55675. }
  55676. if (req.headers.upgrade.toLowerCase() !== 'websocket') {
  55677. socket.destroy();
  55678. return true;
  55679. }
  55680. },
  55681. /**
  55682. * Sets `x-forwarded-*` headers if specified in config.
  55683. *
  55684. * @param {ClientRequest} Req Request object
  55685. * @param {Socket} Websocket
  55686. * @param {Object} Options Config object passed to the proxy
  55687. *
  55688. * @api private
  55689. */
  55690. XHeaders : function XHeaders(req, socket, options) {
  55691. if(!options.xfwd) return;
  55692. var values = {
  55693. for : req.connection.remoteAddress || req.socket.remoteAddress,
  55694. port : common.getPort(req),
  55695. proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws'
  55696. };
  55697. ['for', 'port', 'proto'].forEach(function(header) {
  55698. req.headers['x-forwarded-' + header] =
  55699. (req.headers['x-forwarded-' + header] || '') +
  55700. (req.headers['x-forwarded-' + header] ? ',' : '') +
  55701. values[header];
  55702. });
  55703. },
  55704. /**
  55705. * Does the actual proxying. Make the request and upgrade it
  55706. * send the Switching Protocols request and pipe the sockets.
  55707. *
  55708. * @param {ClientRequest} Req Request object
  55709. * @param {Socket} Websocket
  55710. * @param {Object} Options Config object passed to the proxy
  55711. *
  55712. * @api private
  55713. */
  55714. stream : function stream(req, socket, options, head, server, clb) {
  55715. var createHttpHeader = function(line, headers) {
  55716. return Object.keys(headers).reduce(function (head, key) {
  55717. var value = headers[key];
  55718. if (!Array.isArray(value)) {
  55719. head.push(key + ': ' + value);
  55720. return head;
  55721. }
  55722. for (var i = 0; i < value.length; i++) {
  55723. head.push(key + ': ' + value[i]);
  55724. }
  55725. return head;
  55726. }, [line])
  55727. .join('\r\n') + '\r\n\r\n';
  55728. };
  55729. common.setupSocket(socket);
  55730. if (head && head.length) socket.unshift(head);
  55731. var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request(
  55732. common.setupOutgoing(options.ssl || {}, options, req)
  55733. );
  55734. // Enable developers to modify the proxyReq before headers are sent
  55735. if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }
  55736. // Error Handler
  55737. proxyReq.on('error', onOutgoingError);
  55738. proxyReq.on('response', function (res) {
  55739. // if upgrade event isn't going to happen, close the socket
  55740. if (!res.upgrade) {
  55741. socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
  55742. res.pipe(socket);
  55743. }
  55744. });
  55745. proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
  55746. proxySocket.on('error', onOutgoingError);
  55747. // Allow us to listen when the websocket has completed
  55748. proxySocket.on('end', function () {
  55749. server.emit('close', proxyRes, proxySocket, proxyHead);
  55750. });
  55751. // The pipe below will end proxySocket if socket closes cleanly, but not
  55752. // if it errors (eg, vanishes from the net and starts returning
  55753. // EHOSTUNREACH). We need to do that explicitly.
  55754. socket.on('error', function () {
  55755. proxySocket.end();
  55756. });
  55757. common.setupSocket(proxySocket);
  55758. if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
  55759. //
  55760. // Remark: Handle writing the headers to the socket when switching protocols
  55761. // Also handles when a header is an array
  55762. //
  55763. socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
  55764. proxySocket.pipe(socket).pipe(proxySocket);
  55765. server.emit('open', proxySocket);
  55766. server.emit('proxySocket', proxySocket); //DEPRECATED.
  55767. });
  55768. return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
  55769. function onOutgoingError(err) {
  55770. if (clb) {
  55771. clb(err, req, socket);
  55772. } else {
  55773. server.emit('error', err, req, socket);
  55774. }
  55775. socket.end();
  55776. }
  55777. }
  55778. };
  55779. (function (module) {
  55780. var httpProxy = module.exports,
  55781. extend = require$$0__default$3._extend,
  55782. parse_url = require$$0__default$7.parse,
  55783. EE3 = eventemitter3.exports,
  55784. http = require$$1__default$1,
  55785. https = require$$1__default$3,
  55786. web = webIncoming,
  55787. ws = wsIncoming;
  55788. httpProxy.Server = ProxyServer;
  55789. /**
  55790. * Returns a function that creates the loader for
  55791. * either `ws` or `web`'s passes.
  55792. *
  55793. * Examples:
  55794. *
  55795. * httpProxy.createRightProxy('ws')
  55796. * // => [Function]
  55797. *
  55798. * @param {String} Type Either 'ws' or 'web'
  55799. * @return {Function} Loader Function that when called returns an iterator for the right passes
  55800. *
  55801. * @api private
  55802. */
  55803. function createRightProxy(type) {
  55804. return function(options) {
  55805. return function(req, res /*, [head], [opts] */) {
  55806. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  55807. args = [].slice.call(arguments),
  55808. cntr = args.length - 1,
  55809. head, cbl;
  55810. /* optional args parse begin */
  55811. if(typeof args[cntr] === 'function') {
  55812. cbl = args[cntr];
  55813. cntr--;
  55814. }
  55815. var requestOptions = options;
  55816. if(
  55817. !(args[cntr] instanceof Buffer) &&
  55818. args[cntr] !== res
  55819. ) {
  55820. //Copy global options
  55821. requestOptions = extend({}, options);
  55822. //Overwrite with request options
  55823. extend(requestOptions, args[cntr]);
  55824. cntr--;
  55825. }
  55826. if(args[cntr] instanceof Buffer) {
  55827. head = args[cntr];
  55828. }
  55829. /* optional args parse end */
  55830. ['target', 'forward'].forEach(function(e) {
  55831. if (typeof requestOptions[e] === 'string')
  55832. requestOptions[e] = parse_url(requestOptions[e]);
  55833. });
  55834. if (!requestOptions.target && !requestOptions.forward) {
  55835. return this.emit('error', new Error('Must provide a proper URL as target'));
  55836. }
  55837. for(var i=0; i < passes.length; i++) {
  55838. /**
  55839. * Call of passes functions
  55840. * pass(req, res, options, head)
  55841. *
  55842. * In WebSockets case the `res` variable
  55843. * refer to the connection socket
  55844. * pass(req, socket, options, head)
  55845. */
  55846. if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop
  55847. break;
  55848. }
  55849. }
  55850. };
  55851. };
  55852. }
  55853. httpProxy.createRightProxy = createRightProxy;
  55854. function ProxyServer(options) {
  55855. EE3.call(this);
  55856. options = options || {};
  55857. options.prependPath = options.prependPath === false ? false : true;
  55858. this.web = this.proxyRequest = createRightProxy('web')(options);
  55859. this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
  55860. this.options = options;
  55861. this.webPasses = Object.keys(web).map(function(pass) {
  55862. return web[pass];
  55863. });
  55864. this.wsPasses = Object.keys(ws).map(function(pass) {
  55865. return ws[pass];
  55866. });
  55867. this.on('error', this.onError, this);
  55868. }
  55869. require$$0__default$3.inherits(ProxyServer, EE3);
  55870. ProxyServer.prototype.onError = function (err) {
  55871. //
  55872. // Remark: Replicate node core behavior using EE3
  55873. // so we force people to handle their own errors
  55874. //
  55875. if(this.listeners('error').length === 1) {
  55876. throw err;
  55877. }
  55878. };
  55879. ProxyServer.prototype.listen = function(port, hostname) {
  55880. var self = this,
  55881. closure = function(req, res) { self.web(req, res); };
  55882. this._server = this.options.ssl ?
  55883. https.createServer(this.options.ssl, closure) :
  55884. http.createServer(closure);
  55885. if(this.options.ws) {
  55886. this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); });
  55887. }
  55888. this._server.listen(port, hostname);
  55889. return this;
  55890. };
  55891. ProxyServer.prototype.close = function(callback) {
  55892. var self = this;
  55893. if (this._server) {
  55894. this._server.close(done);
  55895. }
  55896. // Wrap callback to nullify server after all open connections are closed.
  55897. function done() {
  55898. self._server = null;
  55899. if (callback) {
  55900. callback.apply(null, arguments);
  55901. }
  55902. }};
  55903. ProxyServer.prototype.before = function(type, passName, callback) {
  55904. if (type !== 'ws' && type !== 'web') {
  55905. throw new Error('type must be `web` or `ws`');
  55906. }
  55907. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  55908. i = false;
  55909. passes.forEach(function(v, idx) {
  55910. if(v.name === passName) i = idx;
  55911. });
  55912. if(i === false) throw new Error('No such pass');
  55913. passes.splice(i, 0, callback);
  55914. };
  55915. ProxyServer.prototype.after = function(type, passName, callback) {
  55916. if (type !== 'ws' && type !== 'web') {
  55917. throw new Error('type must be `web` or `ws`');
  55918. }
  55919. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  55920. i = false;
  55921. passes.forEach(function(v, idx) {
  55922. if(v.name === passName) i = idx;
  55923. });
  55924. if(i === false) throw new Error('No such pass');
  55925. passes.splice(i++, 0, callback);
  55926. };
  55927. }(httpProxy$2));
  55928. // Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!)
  55929. var ProxyServer = httpProxy$2.exports.Server;
  55930. /**
  55931. * Creates the proxy server.
  55932. *
  55933. * Examples:
  55934. *
  55935. * httpProxy.createProxyServer({ .. }, 8000)
  55936. * // => '{ web: [Function], ws: [Function] ... }'
  55937. *
  55938. * @param {Object} Options Config object passed to the proxy
  55939. *
  55940. * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
  55941. *
  55942. * @api public
  55943. */
  55944. function createProxyServer(options) {
  55945. /*
  55946. * `options` is needed and it must have the following layout:
  55947. *
  55948. * {
  55949. * target : <url string to be parsed with the url module>
  55950. * forward: <url string to be parsed with the url module>
  55951. * agent : <object to be passed to http(s).request>
  55952. * ssl : <object to be passed to https.createServer()>
  55953. * ws : <true/false, if you want to proxy websockets>
  55954. * xfwd : <true/false, adds x-forward headers>
  55955. * secure : <true/false, verify SSL certificate>
  55956. * toProxy: <true/false, explicitly specify if we are proxying to another proxy>
  55957. * prependPath: <true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
  55958. * ignorePath: <true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
  55959. * localAddress : <Local interface string to bind for outgoing connections>
  55960. * changeOrigin: <true/false, Default: false - changes the origin of the host header to the target URL>
  55961. * preserveHeaderKeyCase: <true/false, Default: false - specify whether you want to keep letter case of response header key >
  55962. * auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
  55963. * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.
  55964. * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
  55965. * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
  55966. * }
  55967. *
  55968. * NOTE: `options.ws` and `options.ssl` are optional.
  55969. * `options.target and `options.forward` cannot be
  55970. * both missing
  55971. * }
  55972. */
  55973. return new ProxyServer(options);
  55974. }
  55975. ProxyServer.createProxyServer = createProxyServer;
  55976. ProxyServer.createServer = createProxyServer;
  55977. ProxyServer.createProxy = createProxyServer;
  55978. /**
  55979. * Export the proxy "Server" as the main export.
  55980. */
  55981. var httpProxy$1 = ProxyServer;
  55982. /*!
  55983. * Caron dimonio, con occhi di bragia
  55984. * loro accennando, tutte le raccoglie;
  55985. * batte col remo qualunque s’adagia
  55986. *
  55987. * Charon the demon, with the eyes of glede,
  55988. * Beckoning to them, collects them all together,
  55989. * Beats with his oar whoever lags behind
  55990. *
  55991. * Dante - The Divine Comedy (Canto III)
  55992. */
  55993. var httpProxy = httpProxy$1;
  55994. const debug$3 = createDebugger('vite:proxy');
  55995. function proxyMiddleware(httpServer, config) {
  55996. const options = config.server.proxy;
  55997. // lazy require only when proxy is used
  55998. const proxies = {};
  55999. Object.keys(options).forEach((context) => {
  56000. let opts = options[context];
  56001. if (typeof opts === 'string') {
  56002. opts = { target: opts, changeOrigin: true };
  56003. }
  56004. const proxy = httpProxy.createProxyServer(opts);
  56005. proxy.on('error', (err) => {
  56006. config.logger.error(`${source.red(`http proxy error:`)}\n${err.stack}`, {
  56007. timestamp: true,
  56008. error: err
  56009. });
  56010. });
  56011. if (opts.configure) {
  56012. opts.configure(proxy, opts);
  56013. }
  56014. // clone before saving because http-proxy mutates the options
  56015. proxies[context] = [proxy, { ...opts }];
  56016. });
  56017. if (httpServer) {
  56018. httpServer.on('upgrade', (req, socket, head) => {
  56019. var _a;
  56020. const url = req.url;
  56021. for (const context in proxies) {
  56022. if (url.startsWith(context)) {
  56023. const [proxy, opts] = proxies[context];
  56024. if ((opts.ws || ((_a = opts.target) === null || _a === void 0 ? void 0 : _a.toString().startsWith('ws:'))) &&
  56025. req.headers['sec-websocket-protocol'] !== HMR_HEADER) {
  56026. if (opts.rewrite) {
  56027. req.url = opts.rewrite(url);
  56028. }
  56029. proxy.ws(req, socket, head);
  56030. }
  56031. }
  56032. }
  56033. });
  56034. }
  56035. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  56036. return function viteProxyMiddleware(req, res, next) {
  56037. const url = req.url;
  56038. for (const context in proxies) {
  56039. if ((context.startsWith('^') && new RegExp(context).test(url)) ||
  56040. url.startsWith(context)) {
  56041. const [proxy, opts] = proxies[context];
  56042. const options = {};
  56043. if (opts.bypass) {
  56044. const bypassResult = opts.bypass(req, res, opts);
  56045. if (typeof bypassResult === 'string') {
  56046. req.url = bypassResult;
  56047. debug$3(`bypass: ${req.url} -> ${bypassResult}`);
  56048. return next();
  56049. }
  56050. else if (isObject$3(bypassResult)) {
  56051. Object.assign(options, bypassResult);
  56052. debug$3(`bypass: ${req.url} use modified options: %O`, options);
  56053. return next();
  56054. }
  56055. else if (bypassResult === false) {
  56056. debug$3(`bypass: ${req.url} -> 404`);
  56057. return res.end(404);
  56058. }
  56059. }
  56060. debug$3(`${req.url} -> ${opts.target || opts.forward}`);
  56061. if (opts.rewrite) {
  56062. req.url = opts.rewrite(req.url);
  56063. }
  56064. proxy.web(req, res, options);
  56065. return;
  56066. }
  56067. }
  56068. next();
  56069. };
  56070. }
  56071. /*!
  56072. * etag
  56073. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  56074. * MIT Licensed
  56075. */
  56076. /**
  56077. * Module exports.
  56078. * @public
  56079. */
  56080. var etag_1 = etag;
  56081. /**
  56082. * Module dependencies.
  56083. * @private
  56084. */
  56085. var crypto = require$$1__default$2;
  56086. var Stats = fs__default.Stats;
  56087. /**
  56088. * Module variables.
  56089. * @private
  56090. */
  56091. var toString = Object.prototype.toString;
  56092. /**
  56093. * Generate an entity tag.
  56094. *
  56095. * @param {Buffer|string} entity
  56096. * @return {string}
  56097. * @private
  56098. */
  56099. function entitytag (entity) {
  56100. if (entity.length === 0) {
  56101. // fast-path empty
  56102. return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
  56103. }
  56104. // compute hash of entity
  56105. var hash = crypto
  56106. .createHash('sha1')
  56107. .update(entity, 'utf8')
  56108. .digest('base64')
  56109. .substring(0, 27);
  56110. // compute length of entity
  56111. var len = typeof entity === 'string'
  56112. ? Buffer.byteLength(entity, 'utf8')
  56113. : entity.length;
  56114. return '"' + len.toString(16) + '-' + hash + '"'
  56115. }
  56116. /**
  56117. * Create a simple ETag.
  56118. *
  56119. * @param {string|Buffer|Stats} entity
  56120. * @param {object} [options]
  56121. * @param {boolean} [options.weak]
  56122. * @return {String}
  56123. * @public
  56124. */
  56125. function etag (entity, options) {
  56126. if (entity == null) {
  56127. throw new TypeError('argument entity is required')
  56128. }
  56129. // support fs.Stats object
  56130. var isStats = isstats(entity);
  56131. var weak = options && typeof options.weak === 'boolean'
  56132. ? options.weak
  56133. : isStats;
  56134. // validate argument
  56135. if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
  56136. throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
  56137. }
  56138. // generate entity tag
  56139. var tag = isStats
  56140. ? stattag(entity)
  56141. : entitytag(entity);
  56142. return weak
  56143. ? 'W/' + tag
  56144. : tag
  56145. }
  56146. /**
  56147. * Determine if object is a Stats object.
  56148. *
  56149. * @param {object} obj
  56150. * @return {boolean}
  56151. * @api private
  56152. */
  56153. function isstats (obj) {
  56154. // genuine fs.Stats
  56155. if (typeof Stats === 'function' && obj instanceof Stats) {
  56156. return true
  56157. }
  56158. // quack quack
  56159. return obj && typeof obj === 'object' &&
  56160. 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&
  56161. 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&
  56162. 'ino' in obj && typeof obj.ino === 'number' &&
  56163. 'size' in obj && typeof obj.size === 'number'
  56164. }
  56165. /**
  56166. * Generate a tag for a stat.
  56167. *
  56168. * @param {object} stat
  56169. * @return {string}
  56170. * @private
  56171. */
  56172. function stattag (stat) {
  56173. var mtime = stat.mtime.getTime().toString(16);
  56174. var size = stat.size.toString(16);
  56175. return '"' + size + '-' + mtime + '"'
  56176. }
  56177. const isDebug$4 = process.env.DEBUG;
  56178. const alias$1 = {
  56179. js: 'application/javascript',
  56180. css: 'text/css',
  56181. html: 'text/html',
  56182. json: 'application/json'
  56183. };
  56184. function send$1(req, res, content, type, etag = etag_1(content, { weak: true }), cacheControl = 'no-cache', map) {
  56185. if (req.headers['if-none-match'] === etag) {
  56186. res.statusCode = 304;
  56187. return res.end();
  56188. }
  56189. res.setHeader('Content-Type', alias$1[type] || type);
  56190. res.setHeader('Cache-Control', cacheControl);
  56191. res.setHeader('Etag', etag);
  56192. // inject source map reference
  56193. if (map && map.mappings) {
  56194. if (isDebug$4) {
  56195. content += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
  56196. }
  56197. content += genSourceMapString(map);
  56198. }
  56199. res.statusCode = 200;
  56200. return res.end(content);
  56201. }
  56202. function genSourceMapString(map) {
  56203. if (typeof map !== 'string') {
  56204. map = JSON.stringify(map);
  56205. }
  56206. return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(map).toString('base64')}`;
  56207. }
  56208. var convertSourceMap = {};
  56209. var safeBuffer = {exports: {}};
  56210. /* eslint-disable node/no-deprecated-api */
  56211. (function (module, exports) {
  56212. var buffer = require$$0__default$8;
  56213. var Buffer = buffer.Buffer;
  56214. // alternative to using Object.keys for old browsers
  56215. function copyProps (src, dst) {
  56216. for (var key in src) {
  56217. dst[key] = src[key];
  56218. }
  56219. }
  56220. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  56221. module.exports = buffer;
  56222. } else {
  56223. // Copy properties from require('buffer')
  56224. copyProps(buffer, exports);
  56225. exports.Buffer = SafeBuffer;
  56226. }
  56227. function SafeBuffer (arg, encodingOrOffset, length) {
  56228. return Buffer(arg, encodingOrOffset, length)
  56229. }
  56230. // Copy static methods from Buffer
  56231. copyProps(Buffer, SafeBuffer);
  56232. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  56233. if (typeof arg === 'number') {
  56234. throw new TypeError('Argument must not be a number')
  56235. }
  56236. return Buffer(arg, encodingOrOffset, length)
  56237. };
  56238. SafeBuffer.alloc = function (size, fill, encoding) {
  56239. if (typeof size !== 'number') {
  56240. throw new TypeError('Argument must be a number')
  56241. }
  56242. var buf = Buffer(size);
  56243. if (fill !== undefined) {
  56244. if (typeof encoding === 'string') {
  56245. buf.fill(fill, encoding);
  56246. } else {
  56247. buf.fill(fill);
  56248. }
  56249. } else {
  56250. buf.fill(0);
  56251. }
  56252. return buf
  56253. };
  56254. SafeBuffer.allocUnsafe = function (size) {
  56255. if (typeof size !== 'number') {
  56256. throw new TypeError('Argument must be a number')
  56257. }
  56258. return Buffer(size)
  56259. };
  56260. SafeBuffer.allocUnsafeSlow = function (size) {
  56261. if (typeof size !== 'number') {
  56262. throw new TypeError('Argument must be a number')
  56263. }
  56264. return buffer.SlowBuffer(size)
  56265. };
  56266. }(safeBuffer, safeBuffer.exports));
  56267. (function (exports) {
  56268. var fs = fs__default;
  56269. var path = path__default;
  56270. var SafeBuffer = safeBuffer.exports;
  56271. Object.defineProperty(exports, 'commentRegex', {
  56272. get: function getCommentRegex () {
  56273. return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg;
  56274. }
  56275. });
  56276. Object.defineProperty(exports, 'mapFileCommentRegex', {
  56277. get: function getMapFileCommentRegex () {
  56278. // Matches sourceMappingURL in either // or /* comment styles.
  56279. return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg;
  56280. }
  56281. });
  56282. function decodeBase64(base64) {
  56283. return (SafeBuffer.Buffer.from(base64, 'base64') || "").toString();
  56284. }
  56285. function stripComment(sm) {
  56286. return sm.split(',').pop();
  56287. }
  56288. function readFromFileMap(sm, dir) {
  56289. // NOTE: this will only work on the server since it attempts to read the map file
  56290. var r = exports.mapFileCommentRegex.exec(sm);
  56291. // for some odd reason //# .. captures in 1 and /* .. */ in 2
  56292. var filename = r[1] || r[2];
  56293. var filepath = path.resolve(dir, filename);
  56294. try {
  56295. return fs.readFileSync(filepath, 'utf8');
  56296. } catch (e) {
  56297. throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e);
  56298. }
  56299. }
  56300. function Converter (sm, opts) {
  56301. opts = opts || {};
  56302. if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir);
  56303. if (opts.hasComment) sm = stripComment(sm);
  56304. if (opts.isEncoded) sm = decodeBase64(sm);
  56305. if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm);
  56306. this.sourcemap = sm;
  56307. }
  56308. Converter.prototype.toJSON = function (space) {
  56309. return JSON.stringify(this.sourcemap, null, space);
  56310. };
  56311. Converter.prototype.toBase64 = function () {
  56312. var json = this.toJSON();
  56313. return (SafeBuffer.Buffer.from(json, 'utf8') || "").toString('base64');
  56314. };
  56315. Converter.prototype.toComment = function (options) {
  56316. var base64 = this.toBase64();
  56317. var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
  56318. return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  56319. };
  56320. // returns copy instead of original
  56321. Converter.prototype.toObject = function () {
  56322. return JSON.parse(this.toJSON());
  56323. };
  56324. Converter.prototype.addProperty = function (key, value) {
  56325. if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
  56326. return this.setProperty(key, value);
  56327. };
  56328. Converter.prototype.setProperty = function (key, value) {
  56329. this.sourcemap[key] = value;
  56330. return this;
  56331. };
  56332. Converter.prototype.getProperty = function (key) {
  56333. return this.sourcemap[key];
  56334. };
  56335. exports.fromObject = function (obj) {
  56336. return new Converter(obj);
  56337. };
  56338. exports.fromJSON = function (json) {
  56339. return new Converter(json, { isJSON: true });
  56340. };
  56341. exports.fromBase64 = function (base64) {
  56342. return new Converter(base64, { isEncoded: true });
  56343. };
  56344. exports.fromComment = function (comment) {
  56345. comment = comment
  56346. .replace(/^\/\*/g, '//')
  56347. .replace(/\*\/$/g, '');
  56348. return new Converter(comment, { isEncoded: true, hasComment: true });
  56349. };
  56350. exports.fromMapFileComment = function (comment, dir) {
  56351. return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true });
  56352. };
  56353. // Finds last sourcemap comment in file or returns null if none was found
  56354. exports.fromSource = function (content) {
  56355. var m = content.match(exports.commentRegex);
  56356. return m ? exports.fromComment(m.pop()) : null;
  56357. };
  56358. // Finds last sourcemap comment in file or returns null if none was found
  56359. exports.fromMapFileSource = function (content, dir) {
  56360. var m = content.match(exports.mapFileCommentRegex);
  56361. return m ? exports.fromMapFileComment(m.pop(), dir) : null;
  56362. };
  56363. exports.removeComments = function (src) {
  56364. return src.replace(exports.commentRegex, '');
  56365. };
  56366. exports.removeMapFileComments = function (src) {
  56367. return src.replace(exports.mapFileCommentRegex, '');
  56368. };
  56369. exports.generateMapFileComment = function (file, options) {
  56370. var data = 'sourceMappingURL=' + file;
  56371. return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  56372. };
  56373. }(convertSourceMap));
  56374. /**
  56375. *
  56376. * @param {Node} param
  56377. * @returns {string[]}
  56378. */
  56379. function extract_names(param) {
  56380. return extract_identifiers(param).map(node => node.name);
  56381. }
  56382. /**
  56383. *
  56384. * @param {Node} param
  56385. * @param {Identifier[]} nodes
  56386. * @returns {Identifier[]}
  56387. */
  56388. function extract_identifiers(param, nodes = []) {
  56389. switch (param.type) {
  56390. case 'Identifier':
  56391. nodes.push(param);
  56392. break;
  56393. case 'MemberExpression':
  56394. let object = param;
  56395. while (object.type === 'MemberExpression') {
  56396. object = /** @type {any} */ (object.object);
  56397. }
  56398. nodes.push(/** @type {any} */ (object));
  56399. break;
  56400. case 'ObjectPattern':
  56401. /**
  56402. *
  56403. * @param {Property | RestElement} prop
  56404. */
  56405. const handle_prop = (prop) => {
  56406. if (prop.type === 'RestElement') {
  56407. extract_identifiers(prop.argument, nodes);
  56408. } else {
  56409. extract_identifiers(prop.value, nodes);
  56410. }
  56411. };
  56412. param.properties.forEach(handle_prop);
  56413. break;
  56414. case 'ArrayPattern':
  56415. /**
  56416. *
  56417. * @param {Node} element
  56418. */
  56419. const handle_element = (element) => {
  56420. if (element) extract_identifiers(element, nodes);
  56421. };
  56422. param.elements.forEach(handle_element);
  56423. break;
  56424. case 'RestElement':
  56425. extract_identifiers(param.argument, nodes);
  56426. break;
  56427. case 'AssignmentPattern':
  56428. extract_identifiers(param.left, nodes);
  56429. break;
  56430. }
  56431. return nodes;
  56432. }
  56433. const ssrModuleExportsKey = `__vite_ssr_exports__`;
  56434. const ssrImportKey = `__vite_ssr_import__`;
  56435. const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
  56436. const ssrExportAllKey = `__vite_ssr_exportAll__`;
  56437. const ssrImportMetaKey = `__vite_ssr_import_meta__`;
  56438. async function ssrTransform(code, inMap, url) {
  56439. const s = new MagicString(code);
  56440. const ast = parser.parse(code, {
  56441. sourceType: 'module',
  56442. ecmaVersion: 2021,
  56443. locations: true
  56444. });
  56445. let uid = 0;
  56446. const deps = new Set();
  56447. const idToImportMap = new Map();
  56448. const declaredConst = new Set();
  56449. function defineImport(node, source) {
  56450. deps.add(source);
  56451. const importId = `__vite_ssr_import_${uid++}__`;
  56452. s.appendLeft(node.start, `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n`);
  56453. return importId;
  56454. }
  56455. function defineExport(position, name, local = name) {
  56456. s.appendRight(position, `\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` +
  56457. `{ enumerable: true, configurable: true, get(){ return ${local} }});`);
  56458. }
  56459. // 1. check all import statements and record id -> importName map
  56460. for (const node of ast.body) {
  56461. // import foo from 'foo' --> foo -> __import_foo__.default
  56462. // import { baz } from 'foo' --> baz -> __import_foo__.baz
  56463. // import * as ok from 'foo' --> ok -> __import_foo__
  56464. if (node.type === 'ImportDeclaration') {
  56465. const importId = defineImport(node, node.source.value);
  56466. for (const spec of node.specifiers) {
  56467. if (spec.type === 'ImportSpecifier') {
  56468. idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
  56469. }
  56470. else if (spec.type === 'ImportDefaultSpecifier') {
  56471. idToImportMap.set(spec.local.name, `${importId}.default`);
  56472. }
  56473. else {
  56474. // namespace specifier
  56475. idToImportMap.set(spec.local.name, importId);
  56476. }
  56477. }
  56478. s.remove(node.start, node.end);
  56479. }
  56480. }
  56481. // 2. check all export statements and define exports
  56482. for (const node of ast.body) {
  56483. // named exports
  56484. if (node.type === 'ExportNamedDeclaration') {
  56485. if (node.declaration) {
  56486. if (node.declaration.type === 'FunctionDeclaration' ||
  56487. node.declaration.type === 'ClassDeclaration') {
  56488. // export function foo() {}
  56489. defineExport(node.end, node.declaration.id.name);
  56490. }
  56491. else {
  56492. // export const foo = 1, bar = 2
  56493. for (const declaration of node.declaration.declarations) {
  56494. const names = extract_names(declaration.id);
  56495. for (const name of names) {
  56496. defineExport(node.end, name);
  56497. }
  56498. }
  56499. }
  56500. s.remove(node.start, node.declaration.start);
  56501. }
  56502. else {
  56503. s.remove(node.start, node.end);
  56504. if (node.source) {
  56505. // export { foo, bar } from './foo'
  56506. const importId = defineImport(node, node.source.value);
  56507. for (const spec of node.specifiers) {
  56508. defineExport(node.end, spec.exported.name, `${importId}.${spec.local.name}`);
  56509. }
  56510. }
  56511. else {
  56512. // export { foo, bar }
  56513. for (const spec of node.specifiers) {
  56514. const local = spec.local.name;
  56515. const binding = idToImportMap.get(local);
  56516. defineExport(node.end, spec.exported.name, binding || local);
  56517. }
  56518. }
  56519. }
  56520. }
  56521. // default export
  56522. if (node.type === 'ExportDefaultDeclaration') {
  56523. if ('id' in node.declaration && node.declaration.id) {
  56524. // named hoistable/class exports
  56525. // export default function foo() {}
  56526. // export default class A {}
  56527. const { name } = node.declaration.id;
  56528. s.remove(node.start, node.start + 15 /* 'export default '.length */);
  56529. s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` +
  56530. `{ enumerable: true, value: ${name} });`);
  56531. }
  56532. else {
  56533. // anonymous default exports
  56534. s.overwrite(node.start, node.start + 14 /* 'export default'.length */, `${ssrModuleExportsKey}.default =`);
  56535. }
  56536. }
  56537. // export * from './foo'
  56538. if (node.type === 'ExportAllDeclaration') {
  56539. if (node.exported) {
  56540. const importId = defineImport(node, node.source.value);
  56541. s.remove(node.start, node.end);
  56542. defineExport(node.end, node.exported.name, `${importId}`);
  56543. }
  56544. else {
  56545. const importId = defineImport(node, node.source.value);
  56546. s.remove(node.start, node.end);
  56547. s.appendLeft(node.end, `${ssrExportAllKey}(${importId});`);
  56548. }
  56549. }
  56550. }
  56551. // 3. convert references to import bindings & import.meta references
  56552. walk(ast, {
  56553. onIdentifier(id, parent, parentStack) {
  56554. const binding = idToImportMap.get(id.name);
  56555. if (!binding) {
  56556. return;
  56557. }
  56558. if (isStaticProperty(parent) && parent.shorthand) {
  56559. // let binding used in a property shorthand
  56560. // { foo } -> { foo: __import_x__.foo }
  56561. // skip for destructuring patterns
  56562. if (!parent.inPattern ||
  56563. isInDestructuringAssignment(parent, parentStack)) {
  56564. s.appendLeft(id.end, `: ${binding}`);
  56565. }
  56566. }
  56567. else if (parent.type === 'ClassDeclaration' &&
  56568. id === parent.superClass) {
  56569. if (!declaredConst.has(id.name)) {
  56570. declaredConst.add(id.name);
  56571. // locate the top-most node containing the class declaration
  56572. const topNode = parentStack[1];
  56573. s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
  56574. }
  56575. }
  56576. else {
  56577. s.overwrite(id.start, id.end, binding);
  56578. }
  56579. },
  56580. onImportMeta(node) {
  56581. s.overwrite(node.start, node.end, ssrImportMetaKey);
  56582. },
  56583. onDynamicImport(node) {
  56584. s.overwrite(node.start, node.start + 6, ssrDynamicImportKey);
  56585. }
  56586. });
  56587. let map = s.generateMap({ hires: true });
  56588. if (inMap && inMap.mappings && inMap.sources.length > 0) {
  56589. map = combineSourcemaps(url, [
  56590. {
  56591. ...map,
  56592. sources: inMap.sources,
  56593. sourcesContent: inMap.sourcesContent
  56594. },
  56595. inMap
  56596. ]);
  56597. }
  56598. else {
  56599. map.sources = [url];
  56600. map.sourcesContent = [code];
  56601. }
  56602. return {
  56603. code: s.toString(),
  56604. map,
  56605. deps: [...deps]
  56606. };
  56607. }
  56608. /**
  56609. * Same logic from \@vue/compiler-core & \@vue/compiler-sfc
  56610. * Except this is using acorn AST
  56611. */
  56612. function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
  56613. const parentStack = [];
  56614. const scope = Object.create(null);
  56615. const scopeMap = new WeakMap();
  56616. const setScope = (node, name) => {
  56617. let scopeIds = scopeMap.get(node);
  56618. if (scopeIds && scopeIds.has(name)) {
  56619. return;
  56620. }
  56621. if (name in scope) {
  56622. scope[name]++;
  56623. }
  56624. else {
  56625. scope[name] = 1;
  56626. }
  56627. if (!scopeIds) {
  56628. scopeIds = new Set();
  56629. scopeMap.set(node, scopeIds);
  56630. }
  56631. scopeIds.add(name);
  56632. };
  56633. walk$1(root, {
  56634. enter(node, parent) {
  56635. if (node.type === 'ImportDeclaration') {
  56636. return this.skip();
  56637. }
  56638. parent && parentStack.push(parent);
  56639. if (node.type === 'MetaProperty' && node.meta.name === 'import') {
  56640. onImportMeta(node);
  56641. }
  56642. else if (node.type === 'ImportExpression') {
  56643. onDynamicImport(node);
  56644. }
  56645. if (node.type === 'Identifier') {
  56646. if (!scope[node.name] && isRefIdentifier(node, parent, parentStack)) {
  56647. onIdentifier(node, parent, parentStack);
  56648. }
  56649. }
  56650. else if (isFunction(node)) {
  56651. // walk function expressions and add its arguments to known identifiers
  56652. // so that we don't prefix them
  56653. node.params.forEach((p) => walk$1(p, {
  56654. enter(child, parent) {
  56655. if (child.type === 'Identifier' &&
  56656. // do not record as scope variable if is a destructuring key
  56657. !isStaticPropertyKey(child, parent) &&
  56658. // do not record if this is a default value
  56659. // assignment of a destructuring variable
  56660. !(parent &&
  56661. parent.type === 'AssignmentPattern' &&
  56662. parent.right === child)) {
  56663. setScope(node, child.name);
  56664. }
  56665. }
  56666. }));
  56667. }
  56668. else if (node.type === 'Property' && parent.type === 'ObjectPattern') {
  56669. node.inPattern = true;
  56670. }
  56671. else if (node.type === 'VariableDeclarator') {
  56672. const parentFunction = findParentFunction(parentStack);
  56673. if (parentFunction) {
  56674. if (node.id.type === 'ObjectPattern') {
  56675. node.id.properties.forEach((property) => {
  56676. if (property.type === 'RestElement') {
  56677. setScope(parentFunction, property.argument.name);
  56678. }
  56679. else {
  56680. setScope(parentFunction, property.value.name);
  56681. }
  56682. });
  56683. }
  56684. else {
  56685. setScope(parentFunction, node.id.name);
  56686. }
  56687. }
  56688. }
  56689. },
  56690. leave(node, parent) {
  56691. parent && parentStack.pop();
  56692. const scopeIds = scopeMap.get(node);
  56693. if (scopeIds) {
  56694. scopeIds.forEach((id) => {
  56695. scope[id]--;
  56696. if (scope[id] === 0) {
  56697. delete scope[id];
  56698. }
  56699. });
  56700. }
  56701. }
  56702. });
  56703. }
  56704. function isRefIdentifier(id, parent, parentStack) {
  56705. // declaration id
  56706. if (parent.type === 'CatchClause' ||
  56707. ((parent.type === 'VariableDeclarator' ||
  56708. parent.type === 'ClassDeclaration') &&
  56709. parent.id === id)) {
  56710. return false;
  56711. }
  56712. if (isFunction(parent)) {
  56713. // function declaration/expression id
  56714. if (parent.id === id) {
  56715. return false;
  56716. }
  56717. // params list
  56718. if (parent.params.includes(id)) {
  56719. return false;
  56720. }
  56721. }
  56722. // class method name
  56723. if (parent.type === 'MethodDefinition') {
  56724. return false;
  56725. }
  56726. // property key
  56727. // this also covers object destructuring pattern
  56728. if (isStaticPropertyKey(id, parent) || parent.inPattern) {
  56729. return false;
  56730. }
  56731. // non-assignment array destructuring pattern
  56732. if (parent.type === 'ArrayPattern' &&
  56733. !isInDestructuringAssignment(parent, parentStack)) {
  56734. return false;
  56735. }
  56736. // member expression property
  56737. if (parent.type === 'MemberExpression' &&
  56738. parent.property === id &&
  56739. !parent.computed) {
  56740. return false;
  56741. }
  56742. if (parent.type === 'ExportSpecifier') {
  56743. return false;
  56744. }
  56745. // is a special keyword but parsed as identifier
  56746. if (id.name === 'arguments') {
  56747. return false;
  56748. }
  56749. return true;
  56750. }
  56751. const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed;
  56752. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  56753. function isFunction(node) {
  56754. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  56755. }
  56756. function findParentFunction(parentStack) {
  56757. for (let i = parentStack.length - 1; i >= 0; i--) {
  56758. const node = parentStack[i];
  56759. if (isFunction(node)) {
  56760. return node;
  56761. }
  56762. }
  56763. }
  56764. function isInDestructuringAssignment(parent, parentStack) {
  56765. if (parent &&
  56766. (parent.type === 'Property' || parent.type === 'ArrayPattern')) {
  56767. let i = parentStack.length;
  56768. while (i--) {
  56769. const p = parentStack[i];
  56770. if (p.type === 'AssignmentExpression') {
  56771. return true;
  56772. }
  56773. else if (p.type !== 'Property' && !p.type.endsWith('Pattern')) {
  56774. break;
  56775. }
  56776. }
  56777. }
  56778. return false;
  56779. }
  56780. const isDebug$3 = !!process.env.DEBUG;
  56781. const debug$2 = createDebugger('vite:sourcemap', {
  56782. onlyWhenFocused: true
  56783. });
  56784. async function injectSourcesContent(map, file, logger) {
  56785. let sourceRoot;
  56786. try {
  56787. // The source root is undefined for virtual modules and permission errors.
  56788. sourceRoot = await fs$v.promises.realpath(path__default.resolve(path__default.dirname(file), map.sourceRoot || ''));
  56789. }
  56790. catch { }
  56791. const missingSources = [];
  56792. map.sourcesContent = await Promise.all(map.sources.map((sourcePath) => {
  56793. if (sourcePath) {
  56794. sourcePath = decodeURI(sourcePath);
  56795. if (sourceRoot) {
  56796. sourcePath = path__default.resolve(sourceRoot, sourcePath);
  56797. }
  56798. return fs$v.promises.readFile(sourcePath, 'utf-8').catch(() => {
  56799. missingSources.push(sourcePath);
  56800. return null;
  56801. });
  56802. }
  56803. return null;
  56804. }));
  56805. // Use this command…
  56806. // DEBUG="vite:sourcemap" vite build
  56807. // …to log the missing sources.
  56808. if (missingSources.length) {
  56809. logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
  56810. isDebug$3 && debug$2(`Missing sources:\n ` + missingSources.join(`\n `));
  56811. }
  56812. }
  56813. /**
  56814. * @typedef ParsedURL
  56815. * @type {import('.').ParsedURL}
  56816. */
  56817. /**
  56818. * @typedef Request
  56819. * @property {string} url
  56820. * @property {ParsedURL} _parsedUrl
  56821. */
  56822. /**
  56823. * @param {Request} req
  56824. * @returns {ParsedURL|void}
  56825. */
  56826. function parse$4(req) {
  56827. let raw = req.url;
  56828. if (raw == null) return;
  56829. let prev = req._parsedUrl;
  56830. if (prev && prev.raw === raw) return prev;
  56831. let pathname=raw, search='', query;
  56832. if (raw.length > 1) {
  56833. let idx = raw.indexOf('?', 1);
  56834. if (idx !== -1) {
  56835. search = raw.substring(idx);
  56836. pathname = raw.substring(0, idx);
  56837. if (search.length > 1) {
  56838. query = qs__namespace.parse(search.substring(1));
  56839. }
  56840. }
  56841. }
  56842. return req._parsedUrl = { pathname, search, query, raw };
  56843. }
  56844. function list(dir, callback, pre='') {
  56845. dir = path$w.resolve('.', dir);
  56846. let arr = fs$v.readdirSync(dir);
  56847. let i=0, abs, stats;
  56848. for (; i < arr.length; i++) {
  56849. abs = path$w.join(dir, arr[i]);
  56850. stats = fs$v.statSync(abs);
  56851. stats.isDirectory()
  56852. ? list(abs, callback, path$w.join(pre, arr[i]))
  56853. : callback(path$w.join(pre, arr[i]), abs, stats);
  56854. }
  56855. }
  56856. const noop$1 = () => {};
  56857. function isMatch(uri, arr) {
  56858. for (let i=0; i < arr.length; i++) {
  56859. if (arr[i].test(uri)) return true;
  56860. }
  56861. }
  56862. function toAssume(uri, extns) {
  56863. let i=0, x, len=uri.length - 1;
  56864. if (uri.charCodeAt(len) === 47) {
  56865. uri = uri.substring(0, len);
  56866. }
  56867. let arr=[], tmp=`${uri}/index`;
  56868. for (; i < extns.length; i++) {
  56869. x = extns[i] ? `.${extns[i]}` : '';
  56870. if (uri) arr.push(uri + x);
  56871. arr.push(tmp + x);
  56872. }
  56873. return arr;
  56874. }
  56875. function viaCache(cache, uri, extns) {
  56876. let i=0, data, arr=toAssume(uri, extns);
  56877. for (; i < arr.length; i++) {
  56878. if (data = cache[arr[i]]) return data;
  56879. }
  56880. }
  56881. function viaLocal(dir, isEtag, uri, extns) {
  56882. let i=0, arr=toAssume(uri, extns);
  56883. let abs, stats, name, headers;
  56884. for (; i < arr.length; i++) {
  56885. abs = path$w.normalize(path$w.join(dir, name=arr[i]));
  56886. if (abs.startsWith(dir) && fs__namespace.existsSync(abs)) {
  56887. stats = fs__namespace.statSync(abs);
  56888. if (stats.isDirectory()) continue;
  56889. headers = toHeaders(name, stats, isEtag);
  56890. headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
  56891. return { abs, stats, headers };
  56892. }
  56893. }
  56894. }
  56895. function is404(req, res) {
  56896. return (res.statusCode=404,res.end());
  56897. }
  56898. function send(req, res, file, stats, headers) {
  56899. let code=200, tmp, opts={};
  56900. headers = { ...headers };
  56901. for (let key in headers) {
  56902. tmp = res.getHeader(key);
  56903. if (tmp) headers[key] = tmp;
  56904. }
  56905. if (tmp = res.getHeader('content-type')) {
  56906. headers['Content-Type'] = tmp;
  56907. }
  56908. if (req.headers.range) {
  56909. code = 206;
  56910. let [x, y] = req.headers.range.replace('bytes=', '').split('-');
  56911. let end = opts.end = parseInt(y, 10) || stats.size - 1;
  56912. let start = opts.start = parseInt(x, 10) || 0;
  56913. if (start >= stats.size || end >= stats.size) {
  56914. res.setHeader('Content-Range', `bytes */${stats.size}`);
  56915. res.statusCode = 416;
  56916. return res.end();
  56917. }
  56918. headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
  56919. headers['Content-Length'] = (end - start + 1);
  56920. headers['Accept-Ranges'] = 'bytes';
  56921. }
  56922. res.writeHead(code, headers);
  56923. fs__namespace.createReadStream(file, opts).pipe(res);
  56924. }
  56925. function isEncoding(name, type, headers) {
  56926. headers['Content-Encoding'] = type;
  56927. headers['Content-Type'] = lite.getType(name.replace(/\.([^.]*)$/, '')) || '';
  56928. }
  56929. function toHeaders(name, stats, isEtag) {
  56930. let headers = {
  56931. 'Content-Length': stats.size,
  56932. 'Content-Type': lite.getType(name) || '',
  56933. 'Last-Modified': stats.mtime.toUTCString(),
  56934. };
  56935. if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  56936. if (/\.br$/.test(name)) isEncoding(name, 'br', headers);
  56937. if (/\.gz$/.test(name)) isEncoding(name, 'gzip', headers);
  56938. return headers;
  56939. }
  56940. function sirv (dir, opts={}) {
  56941. dir = path$w.resolve(dir || '.');
  56942. let isNotFound = opts.onNoMatch || is404;
  56943. let setHeaders = opts.setHeaders || noop$1;
  56944. let extensions = opts.extensions || ['html', 'htm'];
  56945. let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
  56946. let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
  56947. const FILES = {};
  56948. let fallback = '/';
  56949. let isEtag = !!opts.etag;
  56950. let isSPA = !!opts.single;
  56951. if (typeof opts.single === 'string') {
  56952. let idx = opts.single.lastIndexOf('.');
  56953. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  56954. }
  56955. let ignores = [];
  56956. if (opts.ignores !== false) {
  56957. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
  56958. if (opts.dotfiles) ignores.push(/\/\.\w/);
  56959. else ignores.push(/\/\.well-known/);
  56960. [].concat(opts.ignores || []).forEach(x => {
  56961. ignores.push(new RegExp(x, 'i'));
  56962. });
  56963. }
  56964. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  56965. if (cc && opts.immutable) cc += ',immutable';
  56966. else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
  56967. if (!opts.dev) {
  56968. list(dir, (name, abs, stats) => {
  56969. if (/\.well-known[\\+\/]/.test(name)) ; // keep
  56970. else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  56971. let headers = toHeaders(name, stats, isEtag);
  56972. if (cc) headers['Cache-Control'] = cc;
  56973. FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
  56974. });
  56975. }
  56976. let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
  56977. return function (req, res, next) {
  56978. let extns = [''];
  56979. let pathname = parse$4(req).pathname;
  56980. let val = req.headers['accept-encoding'] || '';
  56981. if (gzips && val.includes('gzip')) extns.unshift(...gzips);
  56982. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  56983. extns.push(...extensions); // [...br, ...gz, orig, ...exts]
  56984. if (pathname.indexOf('%') !== -1) {
  56985. try { pathname = decodeURIComponent(pathname); }
  56986. catch (err) { /* malform uri */ }
  56987. }
  56988. let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
  56989. if (!data) return next ? next() : isNotFound(req, res);
  56990. if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
  56991. res.writeHead(304);
  56992. return res.end();
  56993. }
  56994. if (gzips || brots) {
  56995. res.setHeader('Vary', 'Accept-Encoding');
  56996. }
  56997. setHeaders(res, pathname, data.stats);
  56998. send(req, res, data.abs, data.stats, data.headers);
  56999. };
  57000. }
  57001. const sirvOptions = {
  57002. dev: true,
  57003. etag: true,
  57004. extensions: [],
  57005. setHeaders(res, pathname) {
  57006. // Matches js, jsx, ts, tsx.
  57007. // The reason this is done, is that the .ts file extension is reserved
  57008. // for the MIME type video/mp2t. In almost all cases, we can expect
  57009. // these files to be TypeScript files, and for Vite to serve them with
  57010. // this Content-Type.
  57011. if (/\.[tj]sx?$/.test(pathname)) {
  57012. res.setHeader('Content-Type', 'application/javascript');
  57013. }
  57014. }
  57015. };
  57016. function servePublicMiddleware(dir) {
  57017. const serve = sirv(dir, sirvOptions);
  57018. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  57019. return function viteServePublicMiddleware(req, res, next) {
  57020. // skip import request and internal requests `/@fs/ /@vite-client` etc...
  57021. if (isImportRequest(req.url) || isInternalRequest(req.url)) {
  57022. return next();
  57023. }
  57024. serve(req, res, next);
  57025. };
  57026. }
  57027. function serveStaticMiddleware(dir, config) {
  57028. const serve = sirv(dir, sirvOptions);
  57029. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  57030. return function viteServeStaticMiddleware(req, res, next) {
  57031. // only serve the file if it's not an html request
  57032. // so that html requests can fallthrough to our html middleware for
  57033. // special processing
  57034. // also skip internal requests `/@fs/ /@vite-client` etc...
  57035. if (path__default.extname(cleanUrl(req.url)) === '.html' ||
  57036. isInternalRequest(req.url)) {
  57037. return next();
  57038. }
  57039. const url = decodeURI(req.url);
  57040. // apply aliases to static requests as well
  57041. let redirected;
  57042. for (const { find, replacement } of config.resolve.alias) {
  57043. const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
  57044. if (matches) {
  57045. redirected = url.replace(find, replacement);
  57046. break;
  57047. }
  57048. }
  57049. if (redirected) {
  57050. // dir is pre-normalized to posix style
  57051. if (redirected.startsWith(dir)) {
  57052. redirected = redirected.slice(dir.length);
  57053. }
  57054. req.url = redirected;
  57055. }
  57056. serve(req, res, next);
  57057. };
  57058. }
  57059. function serveRawFsMiddleware(server) {
  57060. const serveFromRoot = sirv('/', sirvOptions);
  57061. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  57062. return function viteServeRawFsMiddleware(req, res, next) {
  57063. let url = req.url;
  57064. // In some cases (e.g. linked monorepos) files outside of root will
  57065. // reference assets that are also out of served root. In such cases
  57066. // the paths are rewritten to `/@fs/` prefixed paths and must be served by
  57067. // searching based from fs root.
  57068. if (url.startsWith(FS_PREFIX)) {
  57069. // restrict files outside of `fs.allow`
  57070. ensureServingAccess(slash$3(path__default.resolve(fsPathFromId(url))), server);
  57071. url = url.slice(FS_PREFIX.length);
  57072. if (isWindows$4)
  57073. url = url.replace(/^[A-Z]:/i, '');
  57074. req.url = url;
  57075. serveFromRoot(req, res, next);
  57076. }
  57077. else {
  57078. next();
  57079. }
  57080. };
  57081. }
  57082. function isFileServingAllowed(url, server) {
  57083. // explicitly disabled
  57084. if (server.config.server.fs.strict === false)
  57085. return true;
  57086. const file = ensureLeadingSlash(normalizePath$4(cleanUrl(url)));
  57087. if (server.moduleGraph.safeModulesPath.has(file))
  57088. return true;
  57089. if (server.config.server.fs.allow.some((i) => file.startsWith(i + '/')))
  57090. return true;
  57091. if (!server.config.server.fs.strict) {
  57092. server.config.logger.warnOnce(`Unrestricted file system access to "${url}"`);
  57093. server.config.logger.warnOnce(`For security concerns, accessing files outside of serving allow list will ` +
  57094. `be restricted by default in the future version of Vite. ` +
  57095. `Refer to https://vitejs.dev/config/#server-fs-allow for more details.`);
  57096. return true;
  57097. }
  57098. return false;
  57099. }
  57100. function ensureServingAccess(url, server) {
  57101. if (!isFileServingAllowed(url, server)) {
  57102. const allow = server.config.server.fs.allow;
  57103. throw new AccessRestrictedError(`The request url "${url}" is outside of Vite serving allow list:
  57104. ${allow.map((i) => `- ${i}`).join('\n')}
  57105. Refer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.`);
  57106. }
  57107. }
  57108. const debugLoad = createDebugger('vite:load');
  57109. const debugTransform = createDebugger('vite:transform');
  57110. const debugCache$1 = createDebugger('vite:cache');
  57111. const isDebug$2 = !!process.env.DEBUG;
  57112. async function transformRequest(url, server, options = {}) {
  57113. var _a, _b;
  57114. const { config, pluginContainer, moduleGraph, watcher } = server;
  57115. url = removeTimestampQuery(url);
  57116. const { root, logger } = config;
  57117. const prettyUrl = isDebug$2 ? prettifyUrl(url, root) : '';
  57118. const ssr = !!options.ssr;
  57119. // check if we have a fresh cache
  57120. const module = await moduleGraph.getModuleByUrl(url);
  57121. const cached = module && (ssr ? module.ssrTransformResult : module.transformResult);
  57122. if (cached) {
  57123. isDebug$2 && debugCache$1(`[memory] ${prettyUrl}`);
  57124. return cached;
  57125. }
  57126. // resolve
  57127. const id = ((_a = (await pluginContainer.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url;
  57128. const file = cleanUrl(id);
  57129. let code = null;
  57130. let map = null;
  57131. // load
  57132. const loadStart = isDebug$2 ? Date.now() : 0;
  57133. const loadResult = await pluginContainer.load(id, ssr);
  57134. if (loadResult == null) {
  57135. // if this is an html request and there is no load result, skip ahead to
  57136. // SPA fallback.
  57137. if (options.html && !id.endsWith('.html')) {
  57138. return null;
  57139. }
  57140. // try fallback loading it from fs as string
  57141. // if the file is a binary, there should be a plugin that already loaded it
  57142. // as string
  57143. // only try the fallback if access is allowed, skip for out of root url
  57144. // like /service-worker.js or /api/users
  57145. if (options.ssr || isFileServingAllowed(file, server)) {
  57146. try {
  57147. code = await fs$v.promises.readFile(file, 'utf-8');
  57148. isDebug$2 && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
  57149. }
  57150. catch (e) {
  57151. if (e.code !== 'ENOENT') {
  57152. throw e;
  57153. }
  57154. }
  57155. }
  57156. if (code) {
  57157. try {
  57158. map = (_b = (convertSourceMap.fromSource(code) ||
  57159. convertSourceMap.fromMapFileSource(code, path__default.dirname(file)))) === null || _b === void 0 ? void 0 : _b.toObject();
  57160. }
  57161. catch (e) {
  57162. logger.warn(`Failed to load source map for ${url}.`, {
  57163. timestamp: true
  57164. });
  57165. }
  57166. }
  57167. }
  57168. else {
  57169. isDebug$2 && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
  57170. if (isObject$3(loadResult)) {
  57171. code = loadResult.code;
  57172. map = loadResult.map;
  57173. }
  57174. else {
  57175. code = loadResult;
  57176. }
  57177. }
  57178. if (code == null) {
  57179. if (checkPublicFile(url, config)) {
  57180. throw new Error(`Failed to load url ${url} (resolved id: ${id}). ` +
  57181. `This file is in /public and will be copied as-is during build without ` +
  57182. `going through the plugin transforms, and therefore should not be ` +
  57183. `imported from source code. It can only be referenced via HTML tags.`);
  57184. }
  57185. else {
  57186. return null;
  57187. }
  57188. }
  57189. // ensure module in graph after successful load
  57190. const mod = await moduleGraph.ensureEntryFromUrl(url);
  57191. ensureWatchedFile(watcher, mod.file, root);
  57192. // transform
  57193. const transformStart = isDebug$2 ? Date.now() : 0;
  57194. const transformResult = await pluginContainer.transform(code, id, map, ssr);
  57195. if (transformResult == null ||
  57196. (isObject$3(transformResult) && transformResult.code == null)) {
  57197. // no transform applied, keep code as-is
  57198. isDebug$2 &&
  57199. debugTransform(timeFrom(transformStart) + source.dim(` [skipped] ${prettyUrl}`));
  57200. }
  57201. else {
  57202. isDebug$2 && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`);
  57203. code = transformResult.code;
  57204. map = transformResult.map;
  57205. }
  57206. if (map && mod.file) {
  57207. map = (typeof map === 'string' ? JSON.parse(map) : map);
  57208. if (map.mappings && !map.sourcesContent) {
  57209. await injectSourcesContent(map, mod.file, logger);
  57210. }
  57211. }
  57212. if (ssr) {
  57213. return (mod.ssrTransformResult = await ssrTransform(code, map, url));
  57214. }
  57215. else {
  57216. return (mod.transformResult = {
  57217. code,
  57218. map,
  57219. etag: etag_1(code, { weak: true })
  57220. });
  57221. }
  57222. }
  57223. /**
  57224. * Time (ms) Vite has to full-reload the page before returning
  57225. * an empty response.
  57226. */
  57227. const NEW_DEPENDENCY_BUILD_TIMEOUT = 1000;
  57228. const debugCache = createDebugger('vite:cache');
  57229. const isDebug$1 = !!process.env.DEBUG;
  57230. const knownIgnoreList = new Set(['/', '/favicon.ico']);
  57231. function transformMiddleware(server) {
  57232. const { config: { root, logger, cacheDir }, moduleGraph } = server;
  57233. // determine the url prefix of files inside cache directory
  57234. let cacheDirPrefix;
  57235. if (cacheDir) {
  57236. const cacheDirRelative = normalizePath$4(path__default.relative(root, cacheDir));
  57237. if (cacheDirRelative.startsWith('../')) {
  57238. // if the cache directory is outside root, the url prefix would be something
  57239. // like '/@fs/absolute/path/to/node_modules/.vite'
  57240. cacheDirPrefix = `/@fs/${normalizePath$4(cacheDir).replace(/^\//, '')}`;
  57241. }
  57242. else {
  57243. // if the cache directory is inside root, the url prefix would be something
  57244. // like '/node_modules/.vite'
  57245. cacheDirPrefix = `/${cacheDirRelative}`;
  57246. }
  57247. }
  57248. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  57249. return async function viteTransformMiddleware(req, res, next) {
  57250. var _a, _b, _c, _d, _e, _f, _g, _h;
  57251. if (req.method !== 'GET' || knownIgnoreList.has(req.url)) {
  57252. return next();
  57253. }
  57254. if (server._pendingReload &&
  57255. // always allow vite client requests so that it can trigger page reload
  57256. !((_a = req.url) === null || _a === void 0 ? void 0 : _a.startsWith(CLIENT_PUBLIC_PATH)) &&
  57257. !((_b = req.url) === null || _b === void 0 ? void 0 : _b.includes('vite/dist/client'))) {
  57258. // missing dep pending reload, hold request until reload happens
  57259. server._pendingReload.then(() =>
  57260. // If the refresh has not happened after timeout, Vite considers
  57261. // something unexpected has happened. In this case, Vite
  57262. // returns an empty response that will error.
  57263. setTimeout(() => {
  57264. // Don't do anything if response has already been sent
  57265. if (res.writableEnded)
  57266. return;
  57267. // status code request timeout
  57268. res.statusCode = 408;
  57269. res.end(`<h1>[vite] Something unexpected happened while optimizing "${req.url}"<h1>` +
  57270. `<p>The current page should have reloaded by now</p>`);
  57271. }, NEW_DEPENDENCY_BUILD_TIMEOUT));
  57272. return;
  57273. }
  57274. let url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, '\0');
  57275. const withoutQuery = cleanUrl(url);
  57276. try {
  57277. const isSourceMap = withoutQuery.endsWith('.map');
  57278. // since we generate source map references, handle those requests here
  57279. if (isSourceMap) {
  57280. const originalUrl = url.replace(/\.map($|\?)/, '$1');
  57281. const map = (_d = (_c = (await moduleGraph.getModuleByUrl(originalUrl))) === null || _c === void 0 ? void 0 : _c.transformResult) === null || _d === void 0 ? void 0 : _d.map;
  57282. if (map) {
  57283. return send$1(req, res, JSON.stringify(map), 'json');
  57284. }
  57285. else {
  57286. return next();
  57287. }
  57288. }
  57289. const publicPath = normalizePath$4(server.config.publicDir).slice(server.config.root.length) + '/';
  57290. // warn explicit public paths
  57291. if (url.startsWith(publicPath)) {
  57292. logger.warn(source.yellow(`files in the public directory are served at the root path.\n` +
  57293. `Instead of ${source.cyan(url)}, use ${source.cyan(url.replace(publicPath, '/'))}.`));
  57294. }
  57295. if (isJSRequest(url) ||
  57296. isImportRequest(url) ||
  57297. isCSSRequest(url) ||
  57298. isHTMLProxy(url)) {
  57299. // strip ?import
  57300. url = removeImportQuery(url);
  57301. // Strip valid id prefix. This is prepended to resolved Ids that are
  57302. // not valid browser import specifiers by the importAnalysis plugin.
  57303. url = unwrapId$1(url);
  57304. // for CSS, we need to differentiate between normal CSS requests and
  57305. // imports
  57306. if (isCSSRequest(url) &&
  57307. !isDirectRequest(url) &&
  57308. ((_e = req.headers.accept) === null || _e === void 0 ? void 0 : _e.includes('text/css'))) {
  57309. url = injectQuery(url, 'direct');
  57310. }
  57311. // check if we can return 304 early
  57312. const ifNoneMatch = req.headers['if-none-match'];
  57313. if (ifNoneMatch &&
  57314. ((_g = (_f = (await moduleGraph.getModuleByUrl(url))) === null || _f === void 0 ? void 0 : _f.transformResult) === null || _g === void 0 ? void 0 : _g.etag) ===
  57315. ifNoneMatch) {
  57316. isDebug$1 && debugCache(`[304] ${prettifyUrl(url, root)}`);
  57317. res.statusCode = 304;
  57318. return res.end();
  57319. }
  57320. // resolve, load and transform using the plugin container
  57321. const result = await transformRequest(url, server, {
  57322. html: (_h = req.headers.accept) === null || _h === void 0 ? void 0 : _h.includes('text/html')
  57323. });
  57324. if (result) {
  57325. const type = isDirectCSSRequest(url) ? 'css' : 'js';
  57326. const isDep = DEP_VERSION_RE.test(url) ||
  57327. (cacheDirPrefix && url.startsWith(cacheDirPrefix));
  57328. return send$1(req, res, result.code, type, result.etag,
  57329. // allow browser to cache npm deps!
  57330. isDep ? 'max-age=31536000,immutable' : 'no-cache', result.map);
  57331. }
  57332. }
  57333. }
  57334. catch (e) {
  57335. return next(e);
  57336. }
  57337. next();
  57338. };
  57339. }
  57340. function createDevHtmlTransformFn(server) {
  57341. const [preHooks, postHooks] = resolveHtmlTransforms(server.config.plugins);
  57342. return (url, html, originalUrl) => {
  57343. return applyHtmlTransforms(html, [...preHooks, devHtmlHook, ...postHooks], {
  57344. path: url,
  57345. filename: getHtmlFilename(url, server),
  57346. server,
  57347. originalUrl
  57348. });
  57349. };
  57350. }
  57351. function getHtmlFilename(url, server) {
  57352. if (url.startsWith(FS_PREFIX)) {
  57353. return fsPathFromId(url);
  57354. }
  57355. else {
  57356. return path__default.join(server.config.root, url.slice(1));
  57357. }
  57358. }
  57359. const startsWithSingleSlashRE = /^\/(?!\/)/;
  57360. const processNodeUrl = (node, s, config, htmlPath, originalUrl) => {
  57361. var _a;
  57362. const url = ((_a = node.value) === null || _a === void 0 ? void 0 : _a.content) || '';
  57363. if (startsWithSingleSlashRE.test(url)) {
  57364. // prefix with base
  57365. s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${config.base + url.slice(1)}"`);
  57366. }
  57367. else if (url.startsWith('.') &&
  57368. originalUrl &&
  57369. originalUrl !== '/' &&
  57370. htmlPath === '/index.html') {
  57371. // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
  57372. // path will add `/a/` prefix, it will caused 404.
  57373. // rewrite before `./index.js` -> `localhost:3000/a/index.js`.
  57374. // rewrite after `../index.js` -> `localhost:3000/index.js`.
  57375. s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${path__default.posix.join(path__default.posix.relative(originalUrl, '/'), url.slice(1))}"`);
  57376. }
  57377. };
  57378. const devHtmlHook = async (html, { path: htmlPath, server, originalUrl }) => {
  57379. // TODO: solve this design issue
  57380. // Optional chain expressions can return undefined by design
  57381. // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
  57382. const config = server === null || server === void 0 ? void 0 : server.config;
  57383. const base = config.base || '/';
  57384. const s = new MagicString(html);
  57385. let scriptModuleIndex = -1;
  57386. await traverseHtml(html, htmlPath, (node) => {
  57387. if (node.type !== 1 /* ELEMENT */) {
  57388. return;
  57389. }
  57390. // script tags
  57391. if (node.tag === 'script') {
  57392. const { src, isModule } = getScriptInfo(node);
  57393. if (isModule) {
  57394. scriptModuleIndex++;
  57395. }
  57396. if (src) {
  57397. processNodeUrl(src, s, config, htmlPath, originalUrl);
  57398. }
  57399. else if (isModule) {
  57400. // inline js module. convert to src="proxy"
  57401. s.overwrite(node.loc.start.offset, node.loc.end.offset, `<script type="module" src="${config.base + htmlPath.slice(1)}?html-proxy&index=${scriptModuleIndex}.js"></script>`);
  57402. }
  57403. }
  57404. // elements with [href/src] attrs
  57405. const assetAttrs = assetAttrsConfig[node.tag];
  57406. if (assetAttrs) {
  57407. for (const p of node.props) {
  57408. if (p.type === 6 /* ATTRIBUTE */ &&
  57409. p.value &&
  57410. assetAttrs.includes(p.name)) {
  57411. processNodeUrl(p, s, config, htmlPath, originalUrl);
  57412. }
  57413. }
  57414. }
  57415. });
  57416. html = s.toString();
  57417. return {
  57418. html,
  57419. tags: [
  57420. {
  57421. tag: 'script',
  57422. attrs: {
  57423. type: 'module',
  57424. src: path__default.posix.join(base, CLIENT_PUBLIC_PATH)
  57425. },
  57426. injectTo: 'head-prepend'
  57427. }
  57428. ]
  57429. };
  57430. };
  57431. function indexHtmlMiddleware(server) {
  57432. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  57433. return async function viteIndexHtmlMiddleware(req, res, next) {
  57434. const url = req.url && cleanUrl(req.url);
  57435. // spa-fallback always redirects to /index.html
  57436. if ((url === null || url === void 0 ? void 0 : url.endsWith('.html')) && req.headers['sec-fetch-dest'] !== 'script') {
  57437. const filename = getHtmlFilename(url, server);
  57438. if (fs__default.existsSync(filename)) {
  57439. try {
  57440. let html = fs__default.readFileSync(filename, 'utf-8');
  57441. html = await server.transformIndexHtml(url, html, req.originalUrl);
  57442. return send$1(req, res, html, 'html');
  57443. }
  57444. catch (e) {
  57445. return next(e);
  57446. }
  57447. }
  57448. }
  57449. next();
  57450. };
  57451. }
  57452. var lib = {exports: {}};
  57453. (function (module, exports) {
  57454. var url = require$$0__default$7;
  57455. module.exports = function historyApiFallback(options) {
  57456. options = options || {};
  57457. var logger = getLogger(options);
  57458. return function(req, res, next) {
  57459. var headers = req.headers;
  57460. if (req.method !== 'GET') {
  57461. logger(
  57462. 'Not rewriting',
  57463. req.method,
  57464. req.url,
  57465. 'because the method is not GET.'
  57466. );
  57467. return next();
  57468. } else if (!headers || typeof headers.accept !== 'string') {
  57469. logger(
  57470. 'Not rewriting',
  57471. req.method,
  57472. req.url,
  57473. 'because the client did not send an HTTP accept header.'
  57474. );
  57475. return next();
  57476. } else if (headers.accept.indexOf('application/json') === 0) {
  57477. logger(
  57478. 'Not rewriting',
  57479. req.method,
  57480. req.url,
  57481. 'because the client prefers JSON.'
  57482. );
  57483. return next();
  57484. } else if (!acceptsHtml(headers.accept, options)) {
  57485. logger(
  57486. 'Not rewriting',
  57487. req.method,
  57488. req.url,
  57489. 'because the client does not accept HTML.'
  57490. );
  57491. return next();
  57492. }
  57493. var parsedUrl = url.parse(req.url);
  57494. var rewriteTarget;
  57495. options.rewrites = options.rewrites || [];
  57496. for (var i = 0; i < options.rewrites.length; i++) {
  57497. var rewrite = options.rewrites[i];
  57498. var match = parsedUrl.pathname.match(rewrite.from);
  57499. if (match !== null) {
  57500. rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req);
  57501. if(rewriteTarget.charAt(0) !== '/') {
  57502. logger(
  57503. 'We recommend using an absolute path for the rewrite target.',
  57504. 'Received a non-absolute rewrite target',
  57505. rewriteTarget,
  57506. 'for URL',
  57507. req.url
  57508. );
  57509. }
  57510. logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
  57511. req.url = rewriteTarget;
  57512. return next();
  57513. }
  57514. }
  57515. var pathname = parsedUrl.pathname;
  57516. if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') &&
  57517. options.disableDotRule !== true) {
  57518. logger(
  57519. 'Not rewriting',
  57520. req.method,
  57521. req.url,
  57522. 'because the path includes a dot (.) character.'
  57523. );
  57524. return next();
  57525. }
  57526. rewriteTarget = options.index || '/index.html';
  57527. logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
  57528. req.url = rewriteTarget;
  57529. next();
  57530. };
  57531. };
  57532. function evaluateRewriteRule(parsedUrl, match, rule, req) {
  57533. if (typeof rule === 'string') {
  57534. return rule;
  57535. } else if (typeof rule !== 'function') {
  57536. throw new Error('Rewrite rule can only be of type string or function.');
  57537. }
  57538. return rule({
  57539. parsedUrl: parsedUrl,
  57540. match: match,
  57541. request: req
  57542. });
  57543. }
  57544. function acceptsHtml(header, options) {
  57545. options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*'];
  57546. for (var i = 0; i < options.htmlAcceptHeaders.length; i++) {
  57547. if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) {
  57548. return true;
  57549. }
  57550. }
  57551. return false;
  57552. }
  57553. function getLogger(options) {
  57554. if (options && options.logger) {
  57555. return options.logger;
  57556. } else if (options && options.verbose) {
  57557. return console.log.bind(console);
  57558. }
  57559. return function(){};
  57560. }
  57561. }(lib));
  57562. var history = lib.exports;
  57563. const logTime = createDebugger('vite:time');
  57564. function timeMiddleware(root) {
  57565. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  57566. return function viteTimeMiddleware(req, res, next) {
  57567. const start = Date.now();
  57568. const end = res.end;
  57569. res.end = (...args) => {
  57570. logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
  57571. // @ts-ignore
  57572. return end.call(res, ...args);
  57573. };
  57574. next();
  57575. };
  57576. }
  57577. class ModuleNode {
  57578. constructor(url) {
  57579. /**
  57580. * Resolved file system path + query
  57581. */
  57582. this.id = null;
  57583. this.file = null;
  57584. this.importers = new Set();
  57585. this.importedModules = new Set();
  57586. this.acceptedHmrDeps = new Set();
  57587. this.isSelfAccepting = false;
  57588. this.transformResult = null;
  57589. this.ssrTransformResult = null;
  57590. this.ssrModule = null;
  57591. this.lastHMRTimestamp = 0;
  57592. this.url = url;
  57593. this.type = isDirectCSSRequest(url) ? 'css' : 'js';
  57594. }
  57595. }
  57596. function invalidateSSRModule(mod, seen) {
  57597. if (seen.has(mod)) {
  57598. return;
  57599. }
  57600. seen.add(mod);
  57601. mod.ssrModule = null;
  57602. mod.importers.forEach((importer) => invalidateSSRModule(importer, seen));
  57603. }
  57604. class ModuleGraph {
  57605. constructor(container) {
  57606. this.urlToModuleMap = new Map();
  57607. this.idToModuleMap = new Map();
  57608. // a single file may corresponds to multiple modules with different queries
  57609. this.fileToModulesMap = new Map();
  57610. this.safeModulesPath = new Set();
  57611. this.container = container;
  57612. }
  57613. async getModuleByUrl(rawUrl) {
  57614. const [url] = await this.resolveUrl(rawUrl);
  57615. return this.urlToModuleMap.get(url);
  57616. }
  57617. getModuleById(id) {
  57618. return this.idToModuleMap.get(removeTimestampQuery(id));
  57619. }
  57620. getModulesByFile(file) {
  57621. return this.fileToModulesMap.get(file);
  57622. }
  57623. onFileChange(file) {
  57624. const mods = this.getModulesByFile(file);
  57625. if (mods) {
  57626. const seen = new Set();
  57627. mods.forEach((mod) => {
  57628. this.invalidateModule(mod, seen);
  57629. });
  57630. }
  57631. }
  57632. invalidateModule(mod, seen = new Set()) {
  57633. mod.transformResult = null;
  57634. mod.ssrTransformResult = null;
  57635. invalidateSSRModule(mod, seen);
  57636. }
  57637. invalidateAll() {
  57638. const seen = new Set();
  57639. this.idToModuleMap.forEach((mod) => {
  57640. this.invalidateModule(mod, seen);
  57641. });
  57642. }
  57643. /**
  57644. * Update the module graph based on a module's updated imports information
  57645. * If there are dependencies that no longer have any importers, they are
  57646. * returned as a Set.
  57647. */
  57648. async updateModuleInfo(mod, importedModules, acceptedModules, isSelfAccepting) {
  57649. mod.isSelfAccepting = isSelfAccepting;
  57650. const prevImports = mod.importedModules;
  57651. const nextImports = (mod.importedModules = new Set());
  57652. let noLongerImported;
  57653. // update import graph
  57654. for (const imported of importedModules) {
  57655. const dep = typeof imported === 'string'
  57656. ? await this.ensureEntryFromUrl(imported)
  57657. : imported;
  57658. dep.importers.add(mod);
  57659. nextImports.add(dep);
  57660. }
  57661. // remove the importer from deps that were imported but no longer are.
  57662. prevImports.forEach((dep) => {
  57663. if (!nextImports.has(dep)) {
  57664. dep.importers.delete(mod);
  57665. if (!dep.importers.size) {
  57666. (noLongerImported || (noLongerImported = new Set())).add(dep);
  57667. }
  57668. }
  57669. });
  57670. // update accepted hmr deps
  57671. const deps = (mod.acceptedHmrDeps = new Set());
  57672. for (const accepted of acceptedModules) {
  57673. const dep = typeof accepted === 'string'
  57674. ? await this.ensureEntryFromUrl(accepted)
  57675. : accepted;
  57676. deps.add(dep);
  57677. }
  57678. return noLongerImported;
  57679. }
  57680. async ensureEntryFromUrl(rawUrl) {
  57681. const [url, resolvedId] = await this.resolveUrl(rawUrl);
  57682. let mod = this.urlToModuleMap.get(url);
  57683. if (!mod) {
  57684. mod = new ModuleNode(url);
  57685. this.urlToModuleMap.set(url, mod);
  57686. mod.id = resolvedId;
  57687. this.idToModuleMap.set(resolvedId, mod);
  57688. const file = (mod.file = cleanUrl(resolvedId));
  57689. let fileMappedModules = this.fileToModulesMap.get(file);
  57690. if (!fileMappedModules) {
  57691. fileMappedModules = new Set();
  57692. this.fileToModulesMap.set(file, fileMappedModules);
  57693. }
  57694. fileMappedModules.add(mod);
  57695. }
  57696. return mod;
  57697. }
  57698. // some deps, like a css file referenced via @import, don't have its own
  57699. // url because they are inlined into the main css import. But they still
  57700. // need to be represented in the module graph so that they can trigger
  57701. // hmr in the importing css file.
  57702. createFileOnlyEntry(file) {
  57703. file = normalizePath$4(file);
  57704. let fileMappedModules = this.fileToModulesMap.get(file);
  57705. if (!fileMappedModules) {
  57706. fileMappedModules = new Set();
  57707. this.fileToModulesMap.set(file, fileMappedModules);
  57708. }
  57709. const url = `${FS_PREFIX}${file}`;
  57710. for (const m of fileMappedModules) {
  57711. if (m.url === url || m.id === file) {
  57712. return m;
  57713. }
  57714. }
  57715. const mod = new ModuleNode(url);
  57716. mod.file = file;
  57717. fileMappedModules.add(mod);
  57718. return mod;
  57719. }
  57720. // for incoming urls, it is important to:
  57721. // 1. remove the HMR timestamp query (?t=xxxx)
  57722. // 2. resolve its extension so that urls with or without extension all map to
  57723. // the same module
  57724. async resolveUrl(url) {
  57725. var _a;
  57726. url = removeImportQuery(removeTimestampQuery(url));
  57727. const resolvedId = ((_a = (await this.container.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url;
  57728. const ext = path$w.extname(cleanUrl(resolvedId));
  57729. const { pathname, search, hash } = require$$0$a.parse(url);
  57730. if (ext && !pathname.endsWith(ext)) {
  57731. url = pathname + ext + (search || '') + (hash || '');
  57732. }
  57733. return [url, resolvedId];
  57734. }
  57735. }
  57736. const debugHmr = createDebugger('vite:hmr');
  57737. const normalizedClientDir = normalizePath$4(CLIENT_DIR);
  57738. function getShortName(file, root) {
  57739. return file.startsWith(root + '/') ? path__default.posix.relative(root, file) : file;
  57740. }
  57741. async function handleHMRUpdate(file, server) {
  57742. const { ws, config, moduleGraph } = server;
  57743. const shortFile = getShortName(file, config.root);
  57744. const isConfig = file === config.configFile;
  57745. const isConfigDependency = config.configFileDependencies.some((name) => file === path__default.resolve(name));
  57746. const isEnv = config.inlineConfig.envFile !== false && file.endsWith('.env');
  57747. if (isConfig || isConfigDependency || isEnv) {
  57748. // auto restart server
  57749. debugHmr(`[config change] ${source.dim(shortFile)}`);
  57750. config.logger.info(source.green(`${path__default.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true });
  57751. await restartServer(server);
  57752. return;
  57753. }
  57754. debugHmr(`[file change] ${source.dim(shortFile)}`);
  57755. // (dev only) the client itself cannot be hot updated.
  57756. if (file.startsWith(normalizedClientDir)) {
  57757. ws.send({
  57758. type: 'full-reload',
  57759. path: '*'
  57760. });
  57761. return;
  57762. }
  57763. const mods = moduleGraph.getModulesByFile(file);
  57764. // check if any plugin wants to perform custom HMR handling
  57765. const timestamp = Date.now();
  57766. const hmrContext = {
  57767. file,
  57768. timestamp,
  57769. modules: mods ? [...mods] : [],
  57770. read: () => readModifiedFile(file),
  57771. server
  57772. };
  57773. for (const plugin of config.plugins) {
  57774. if (plugin.handleHotUpdate) {
  57775. const filteredModules = await plugin.handleHotUpdate(hmrContext);
  57776. if (filteredModules) {
  57777. hmrContext.modules = filteredModules;
  57778. }
  57779. }
  57780. }
  57781. if (!hmrContext.modules.length) {
  57782. // html file cannot be hot updated
  57783. if (file.endsWith('.html')) {
  57784. config.logger.info(source.green(`page reload `) + source.dim(shortFile), {
  57785. clear: true,
  57786. timestamp: true
  57787. });
  57788. ws.send({
  57789. type: 'full-reload',
  57790. path: config.server.middlewareMode
  57791. ? '*'
  57792. : '/' + normalizePath$4(path__default.relative(config.root, file))
  57793. });
  57794. }
  57795. else {
  57796. // loaded but not in the module graph, probably not js
  57797. debugHmr(`[no modules matched] ${source.dim(shortFile)}`);
  57798. }
  57799. return;
  57800. }
  57801. updateModules(shortFile, hmrContext.modules, timestamp, server);
  57802. }
  57803. function updateModules(file, modules, timestamp, { config, ws }) {
  57804. const updates = [];
  57805. const invalidatedModules = new Set();
  57806. let needFullReload = false;
  57807. for (const mod of modules) {
  57808. invalidate(mod, timestamp, invalidatedModules);
  57809. if (needFullReload) {
  57810. continue;
  57811. }
  57812. const boundaries = new Set();
  57813. const hasDeadEnd = propagateUpdate(mod, boundaries);
  57814. if (hasDeadEnd) {
  57815. needFullReload = true;
  57816. continue;
  57817. }
  57818. updates.push(...[...boundaries].map(({ boundary, acceptedVia }) => ({
  57819. type: `${boundary.type}-update`,
  57820. timestamp,
  57821. path: boundary.url,
  57822. acceptedPath: acceptedVia.url
  57823. })));
  57824. }
  57825. if (needFullReload) {
  57826. config.logger.info(source.green(`page reload `) + source.dim(file), {
  57827. clear: true,
  57828. timestamp: true
  57829. });
  57830. ws.send({
  57831. type: 'full-reload'
  57832. });
  57833. }
  57834. else {
  57835. config.logger.info(updates
  57836. .map(({ path }) => source.green(`hmr update `) + source.dim(path))
  57837. .join('\n'), { clear: true, timestamp: true });
  57838. ws.send({
  57839. type: 'update',
  57840. updates
  57841. });
  57842. }
  57843. }
  57844. async function handleFileAddUnlink(file, server, isUnlink = false) {
  57845. var _a;
  57846. const modules = [...((_a = server.moduleGraph.getModulesByFile(file)) !== null && _a !== void 0 ? _a : [])];
  57847. if (isUnlink && file in server._globImporters) {
  57848. delete server._globImporters[file];
  57849. }
  57850. else {
  57851. for (const i in server._globImporters) {
  57852. const { module, importGlobs } = server._globImporters[i];
  57853. for (const { base, pattern } of importGlobs) {
  57854. if (minimatch_1(file, pattern) || minimatch_1(path__default.relative(base, file), pattern)) {
  57855. modules.push(module);
  57856. // We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()`
  57857. // calls get fresh glob import results with(out) the newly added(/removed) `file`.
  57858. server.moduleGraph.onFileChange(module.file);
  57859. break;
  57860. }
  57861. }
  57862. }
  57863. }
  57864. if (modules.length > 0) {
  57865. updateModules(getShortName(file, server.config.root), modules, Date.now(), server);
  57866. }
  57867. }
  57868. function propagateUpdate(node, boundaries, currentChain = [node]) {
  57869. if (node.isSelfAccepting) {
  57870. boundaries.add({
  57871. boundary: node,
  57872. acceptedVia: node
  57873. });
  57874. // additionally check for CSS importers, since a PostCSS plugin like
  57875. // Tailwind JIT may register any file as a dependency to a CSS file.
  57876. for (const importer of node.importers) {
  57877. if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
  57878. propagateUpdate(importer, boundaries, currentChain.concat(importer));
  57879. }
  57880. }
  57881. return false;
  57882. }
  57883. if (!node.importers.size) {
  57884. return true;
  57885. }
  57886. // #3716, #3913
  57887. // For a non-CSS file, if all of its importers are CSS files (registered via
  57888. // PostCSS plugins) it should be considered a dead end and force full reload.
  57889. if (!isCSSRequest(node.url) &&
  57890. [...node.importers].every((i) => isCSSRequest(i.url))) {
  57891. return true;
  57892. }
  57893. for (const importer of node.importers) {
  57894. const subChain = currentChain.concat(importer);
  57895. if (importer.acceptedHmrDeps.has(node)) {
  57896. boundaries.add({
  57897. boundary: importer,
  57898. acceptedVia: node
  57899. });
  57900. continue;
  57901. }
  57902. if (currentChain.includes(importer)) {
  57903. // circular deps is considered dead end
  57904. return true;
  57905. }
  57906. if (propagateUpdate(importer, boundaries, subChain)) {
  57907. return true;
  57908. }
  57909. }
  57910. return false;
  57911. }
  57912. function invalidate(mod, timestamp, seen) {
  57913. if (seen.has(mod)) {
  57914. return;
  57915. }
  57916. seen.add(mod);
  57917. mod.lastHMRTimestamp = timestamp;
  57918. mod.transformResult = null;
  57919. mod.ssrModule = null;
  57920. mod.ssrTransformResult = null;
  57921. mod.importers.forEach((importer) => {
  57922. if (!importer.acceptedHmrDeps.has(mod)) {
  57923. invalidate(importer, timestamp, seen);
  57924. }
  57925. });
  57926. }
  57927. function handlePrunedModules(mods, { ws }) {
  57928. // update the disposed modules' hmr timestamp
  57929. // since if it's re-imported, it should re-apply side effects
  57930. // and without the timestamp the browser will not re-import it!
  57931. const t = Date.now();
  57932. mods.forEach((mod) => {
  57933. mod.lastHMRTimestamp = t;
  57934. debugHmr(`[dispose] ${source.dim(mod.file)}`);
  57935. });
  57936. ws.send({
  57937. type: 'prune',
  57938. paths: [...mods].map((m) => m.url)
  57939. });
  57940. }
  57941. /**
  57942. * Lex import.meta.hot.accept() for accepted deps.
  57943. * Since hot.accept() can only accept string literals or array of string
  57944. * literals, we don't really need a heavy @babel/parse call on the entire source.
  57945. *
  57946. * @returns selfAccepts
  57947. */
  57948. function lexAcceptedHmrDeps(code, start, urls) {
  57949. let state = 0 /* inCall */;
  57950. // the state can only be 2 levels deep so no need for a stack
  57951. let prevState = 0 /* inCall */;
  57952. let currentDep = '';
  57953. function addDep(index) {
  57954. urls.add({
  57955. url: currentDep,
  57956. start: index - currentDep.length - 1,
  57957. end: index + 1
  57958. });
  57959. currentDep = '';
  57960. }
  57961. for (let i = start; i < code.length; i++) {
  57962. const char = code.charAt(i);
  57963. switch (state) {
  57964. case 0 /* inCall */:
  57965. case 4 /* inArray */:
  57966. if (char === `'`) {
  57967. prevState = state;
  57968. state = 1 /* inSingleQuoteString */;
  57969. }
  57970. else if (char === `"`) {
  57971. prevState = state;
  57972. state = 2 /* inDoubleQuoteString */;
  57973. }
  57974. else if (char === '`') {
  57975. prevState = state;
  57976. state = 3 /* inTemplateString */;
  57977. }
  57978. else if (/\s/.test(char)) {
  57979. continue;
  57980. }
  57981. else {
  57982. if (state === 0 /* inCall */) {
  57983. if (char === `[`) {
  57984. state = 4 /* inArray */;
  57985. }
  57986. else {
  57987. // reaching here means the first arg is neither a string literal
  57988. // nor an Array literal (direct callback) or there is no arg
  57989. // in both case this indicates a self-accepting module
  57990. return true; // done
  57991. }
  57992. }
  57993. else if (state === 4 /* inArray */) {
  57994. if (char === `]`) {
  57995. return false; // done
  57996. }
  57997. else if (char === ',') {
  57998. continue;
  57999. }
  58000. else {
  58001. error$1(i);
  58002. }
  58003. }
  58004. }
  58005. break;
  58006. case 1 /* inSingleQuoteString */:
  58007. if (char === `'`) {
  58008. addDep(i);
  58009. if (prevState === 0 /* inCall */) {
  58010. // accept('foo', ...)
  58011. return false;
  58012. }
  58013. else {
  58014. state = prevState;
  58015. }
  58016. }
  58017. else {
  58018. currentDep += char;
  58019. }
  58020. break;
  58021. case 2 /* inDoubleQuoteString */:
  58022. if (char === `"`) {
  58023. addDep(i);
  58024. if (prevState === 0 /* inCall */) {
  58025. // accept('foo', ...)
  58026. return false;
  58027. }
  58028. else {
  58029. state = prevState;
  58030. }
  58031. }
  58032. else {
  58033. currentDep += char;
  58034. }
  58035. break;
  58036. case 3 /* inTemplateString */:
  58037. if (char === '`') {
  58038. addDep(i);
  58039. if (prevState === 0 /* inCall */) {
  58040. // accept('foo', ...)
  58041. return false;
  58042. }
  58043. else {
  58044. state = prevState;
  58045. }
  58046. }
  58047. else if (char === '$' && code.charAt(i + 1) === '{') {
  58048. error$1(i);
  58049. }
  58050. else {
  58051. currentDep += char;
  58052. }
  58053. break;
  58054. default:
  58055. throw new Error('unknown import.meta.hot lexer state');
  58056. }
  58057. }
  58058. return false;
  58059. }
  58060. function error$1(pos) {
  58061. const err = new Error(`import.meta.accept() can only accept string literals or an ` +
  58062. `Array of string literals.`);
  58063. err.pos = pos;
  58064. throw err;
  58065. }
  58066. // vitejs/vite#610 when hot-reloading Vue files, we read immediately on file
  58067. // change event and sometimes this can be too early and get an empty buffer.
  58068. // Poll until the file's modified time has changed before reading again.
  58069. async function readModifiedFile(file) {
  58070. const content = fs__default.readFileSync(file, 'utf-8');
  58071. if (!content) {
  58072. const mtime = fs__default.statSync(file).mtimeMs;
  58073. await new Promise((r) => {
  58074. let n = 0;
  58075. const poll = async () => {
  58076. n++;
  58077. const newMtime = fs__default.statSync(file).mtimeMs;
  58078. if (newMtime !== mtime || n > 10) {
  58079. r(0);
  58080. }
  58081. else {
  58082. setTimeout(poll, 10);
  58083. }
  58084. };
  58085. setTimeout(poll, 10);
  58086. });
  58087. return fs__default.readFileSync(file, 'utf-8');
  58088. }
  58089. else {
  58090. return content;
  58091. }
  58092. }
  58093. async function restartServer(server) {
  58094. // @ts-ignore
  58095. global.__vite_start_time = Date.now();
  58096. const { port } = server.config.server;
  58097. await server.close();
  58098. let newServer = null;
  58099. try {
  58100. newServer = await createServer(server.config.inlineConfig);
  58101. }
  58102. catch (err) {
  58103. server.config.logger.error(err.message, {
  58104. timestamp: true,
  58105. });
  58106. return;
  58107. }
  58108. for (const key in newServer) {
  58109. if (key !== 'app') {
  58110. // @ts-ignore
  58111. server[key] = newServer[key];
  58112. }
  58113. }
  58114. if (!server.config.server.middlewareMode) {
  58115. await server.listen(port, true);
  58116. }
  58117. else {
  58118. server.config.logger.info('server restarted.', { timestamp: true });
  58119. }
  58120. }
  58121. var isWsl$2 = {exports: {}};
  58122. const fs$7 = fs__default;
  58123. let isDocker$2;
  58124. function hasDockerEnv() {
  58125. try {
  58126. fs$7.statSync('/.dockerenv');
  58127. return true;
  58128. } catch (_) {
  58129. return false;
  58130. }
  58131. }
  58132. function hasDockerCGroup() {
  58133. try {
  58134. return fs$7.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
  58135. } catch (_) {
  58136. return false;
  58137. }
  58138. }
  58139. var isDocker_1 = () => {
  58140. if (isDocker$2 === undefined) {
  58141. isDocker$2 = hasDockerEnv() || hasDockerCGroup();
  58142. }
  58143. return isDocker$2;
  58144. };
  58145. const os$4 = require$$0__default$1;
  58146. const fs$6 = fs__default;
  58147. const isDocker$1 = isDocker_1;
  58148. const isWsl$1 = () => {
  58149. if (process.platform !== 'linux') {
  58150. return false;
  58151. }
  58152. if (os$4.release().toLowerCase().includes('microsoft')) {
  58153. if (isDocker$1()) {
  58154. return false;
  58155. }
  58156. return true;
  58157. }
  58158. try {
  58159. return fs$6.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?
  58160. !isDocker$1() : false;
  58161. } catch (_) {
  58162. return false;
  58163. }
  58164. };
  58165. if (process.env.__IS_WSL_TEST__) {
  58166. isWsl$2.exports = isWsl$1;
  58167. } else {
  58168. isWsl$2.exports = isWsl$1();
  58169. }
  58170. var defineLazyProp = (object, propertyName, fn) => {
  58171. const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});
  58172. Object.defineProperty(object, propertyName, {
  58173. configurable: true,
  58174. enumerable: true,
  58175. get() {
  58176. const result = fn();
  58177. define(result);
  58178. return result;
  58179. },
  58180. set(value) {
  58181. define(value);
  58182. }
  58183. });
  58184. return object;
  58185. };
  58186. const path$9 = path__default;
  58187. const childProcess$3 = require$$1__default$4;
  58188. const {promises: fs$5, constants: fsConstants} = fs__default;
  58189. const isWsl = isWsl$2.exports;
  58190. const isDocker = isDocker_1;
  58191. const defineLazyProperty = defineLazyProp;
  58192. // Path to included `xdg-open`.
  58193. const localXdgOpenPath = path$9.join(__dirname, 'xdg-open');
  58194. const {platform, arch} = process;
  58195. /**
  58196. Get the mount point for fixed drives in WSL.
  58197. @inner
  58198. @returns {string} The mount point.
  58199. */
  58200. const getWslDrivesMountPoint = (() => {
  58201. // Default value for "root" param
  58202. // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
  58203. const defaultMountPoint = '/mnt/';
  58204. let mountPoint;
  58205. return async function () {
  58206. if (mountPoint) {
  58207. // Return memoized mount point value
  58208. return mountPoint;
  58209. }
  58210. const configFilePath = '/etc/wsl.conf';
  58211. let isConfigFileExists = false;
  58212. try {
  58213. await fs$5.access(configFilePath, fsConstants.F_OK);
  58214. isConfigFileExists = true;
  58215. } catch {}
  58216. if (!isConfigFileExists) {
  58217. return defaultMountPoint;
  58218. }
  58219. const configContent = await fs$5.readFile(configFilePath, {encoding: 'utf8'});
  58220. const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
  58221. if (!configMountPoint) {
  58222. return defaultMountPoint;
  58223. }
  58224. mountPoint = configMountPoint.groups.mountPoint.trim();
  58225. mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
  58226. return mountPoint;
  58227. };
  58228. })();
  58229. const pTryEach = async (array, mapper) => {
  58230. let latestError;
  58231. for (const item of array) {
  58232. try {
  58233. return await mapper(item); // eslint-disable-line no-await-in-loop
  58234. } catch (error) {
  58235. latestError = error;
  58236. }
  58237. }
  58238. throw latestError;
  58239. };
  58240. const open = async (target, options) => {
  58241. if (typeof target !== 'string') {
  58242. throw new TypeError('Expected a `target`');
  58243. }
  58244. options = {
  58245. wait: false,
  58246. background: false,
  58247. newInstance: false,
  58248. allowNonzeroExitCode: false,
  58249. ...options
  58250. };
  58251. if (Array.isArray(options.app)) {
  58252. return pTryEach(options.app, singleApp => open(target, {
  58253. ...options,
  58254. app: singleApp
  58255. }));
  58256. }
  58257. let {name: app, arguments: appArguments = []} = options.app || {};
  58258. appArguments = [...appArguments];
  58259. if (Array.isArray(app)) {
  58260. return pTryEach(app, appName => open(target, {
  58261. ...options,
  58262. app: {
  58263. name: appName,
  58264. arguments: appArguments
  58265. }
  58266. }));
  58267. }
  58268. let command;
  58269. const cliArguments = [];
  58270. const childProcessOptions = {};
  58271. if (platform === 'darwin') {
  58272. command = 'open';
  58273. if (options.wait) {
  58274. cliArguments.push('--wait-apps');
  58275. }
  58276. if (options.background) {
  58277. cliArguments.push('--background');
  58278. }
  58279. if (options.newInstance) {
  58280. cliArguments.push('--new');
  58281. }
  58282. if (app) {
  58283. cliArguments.push('-a', app);
  58284. }
  58285. } else if (platform === 'win32' || (isWsl && !isDocker())) {
  58286. const mountPoint = await getWslDrivesMountPoint();
  58287. command = isWsl ?
  58288. `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :
  58289. `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
  58290. cliArguments.push(
  58291. '-NoProfile',
  58292. '-NonInteractive',
  58293. '–ExecutionPolicy',
  58294. 'Bypass',
  58295. '-EncodedCommand'
  58296. );
  58297. if (!isWsl) {
  58298. childProcessOptions.windowsVerbatimArguments = true;
  58299. }
  58300. const encodedArguments = ['Start'];
  58301. if (options.wait) {
  58302. encodedArguments.push('-Wait');
  58303. }
  58304. if (app) {
  58305. // Double quote with double quotes to ensure the inner quotes are passed through.
  58306. // Inner quotes are delimited for PowerShell interpretation with backticks.
  58307. encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
  58308. appArguments.unshift(target);
  58309. } else {
  58310. encodedArguments.push(`"${target}"`);
  58311. }
  58312. if (appArguments.length > 0) {
  58313. appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
  58314. encodedArguments.push(appArguments.join(','));
  58315. }
  58316. // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
  58317. target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
  58318. } else {
  58319. if (app) {
  58320. command = app;
  58321. } else {
  58322. // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
  58323. const isBundled = !__dirname || __dirname === '/';
  58324. // Check if local `xdg-open` exists and is executable.
  58325. let exeLocalXdgOpen = false;
  58326. try {
  58327. await fs$5.access(localXdgOpenPath, fsConstants.X_OK);
  58328. exeLocalXdgOpen = true;
  58329. } catch {}
  58330. const useSystemXdgOpen = process.versions.electron ||
  58331. platform === 'android' || isBundled || !exeLocalXdgOpen;
  58332. command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
  58333. }
  58334. if (appArguments.length > 0) {
  58335. cliArguments.push(...appArguments);
  58336. }
  58337. if (!options.wait) {
  58338. // `xdg-open` will block the process unless stdio is ignored
  58339. // and it's detached from the parent even if it's unref'd.
  58340. childProcessOptions.stdio = 'ignore';
  58341. childProcessOptions.detached = true;
  58342. }
  58343. }
  58344. cliArguments.push(target);
  58345. if (platform === 'darwin' && appArguments.length > 0) {
  58346. cliArguments.push('--args', ...appArguments);
  58347. }
  58348. const subprocess = childProcess$3.spawn(command, cliArguments, childProcessOptions);
  58349. if (options.wait) {
  58350. return new Promise((resolve, reject) => {
  58351. subprocess.once('error', reject);
  58352. subprocess.once('close', exitCode => {
  58353. if (options.allowNonzeroExitCode && exitCode > 0) {
  58354. reject(new Error(`Exited with code ${exitCode}`));
  58355. return;
  58356. }
  58357. resolve(subprocess);
  58358. });
  58359. });
  58360. }
  58361. subprocess.unref();
  58362. return subprocess;
  58363. };
  58364. function detectArchBinary(binary) {
  58365. if (typeof binary === 'string' || Array.isArray(binary)) {
  58366. return binary;
  58367. }
  58368. const {[arch]: archBinary} = binary;
  58369. if (!archBinary) {
  58370. throw new Error(`${arch} is not supported`);
  58371. }
  58372. return archBinary;
  58373. }
  58374. function detectPlatformBinary({[platform]: platformBinary}, {wsl}) {
  58375. if (wsl && isWsl) {
  58376. return detectArchBinary(wsl);
  58377. }
  58378. if (!platformBinary) {
  58379. throw new Error(`${platform} is not supported`);
  58380. }
  58381. return detectArchBinary(platformBinary);
  58382. }
  58383. const apps = {};
  58384. defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({
  58385. darwin: 'google chrome',
  58386. win32: 'chrome',
  58387. linux: ['google-chrome', 'google-chrome-stable']
  58388. }, {
  58389. wsl: {
  58390. ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
  58391. x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']
  58392. }
  58393. }));
  58394. defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({
  58395. darwin: 'firefox',
  58396. win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
  58397. linux: 'firefox'
  58398. }, {
  58399. wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'
  58400. }));
  58401. defineLazyProperty(apps, 'edge', () => detectPlatformBinary({
  58402. darwin: 'microsoft edge',
  58403. win32: 'msedge',
  58404. linux: 'microsoft-edge'
  58405. }, {
  58406. wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
  58407. }));
  58408. open.apps = apps;
  58409. var open_1 = open;
  58410. var execa$2 = {exports: {}};
  58411. var crossSpawn$1 = {exports: {}};
  58412. var windows$1 = isexe$3;
  58413. isexe$3.sync = sync$2;
  58414. var fs$4 = fs__default;
  58415. function checkPathExt (path, options) {
  58416. var pathext = options.pathExt !== undefined ?
  58417. options.pathExt : process.env.PATHEXT;
  58418. if (!pathext) {
  58419. return true
  58420. }
  58421. pathext = pathext.split(';');
  58422. if (pathext.indexOf('') !== -1) {
  58423. return true
  58424. }
  58425. for (var i = 0; i < pathext.length; i++) {
  58426. var p = pathext[i].toLowerCase();
  58427. if (p && path.substr(-p.length).toLowerCase() === p) {
  58428. return true
  58429. }
  58430. }
  58431. return false
  58432. }
  58433. function checkStat$1 (stat, path, options) {
  58434. if (!stat.isSymbolicLink() && !stat.isFile()) {
  58435. return false
  58436. }
  58437. return checkPathExt(path, options)
  58438. }
  58439. function isexe$3 (path, options, cb) {
  58440. fs$4.stat(path, function (er, stat) {
  58441. cb(er, er ? false : checkStat$1(stat, path, options));
  58442. });
  58443. }
  58444. function sync$2 (path, options) {
  58445. return checkStat$1(fs$4.statSync(path), path, options)
  58446. }
  58447. var mode = isexe$2;
  58448. isexe$2.sync = sync$1;
  58449. var fs$3 = fs__default;
  58450. function isexe$2 (path, options, cb) {
  58451. fs$3.stat(path, function (er, stat) {
  58452. cb(er, er ? false : checkStat(stat, options));
  58453. });
  58454. }
  58455. function sync$1 (path, options) {
  58456. return checkStat(fs$3.statSync(path), options)
  58457. }
  58458. function checkStat (stat, options) {
  58459. return stat.isFile() && checkMode(stat, options)
  58460. }
  58461. function checkMode (stat, options) {
  58462. var mod = stat.mode;
  58463. var uid = stat.uid;
  58464. var gid = stat.gid;
  58465. var myUid = options.uid !== undefined ?
  58466. options.uid : process.getuid && process.getuid();
  58467. var myGid = options.gid !== undefined ?
  58468. options.gid : process.getgid && process.getgid();
  58469. var u = parseInt('100', 8);
  58470. var g = parseInt('010', 8);
  58471. var o = parseInt('001', 8);
  58472. var ug = u | g;
  58473. var ret = (mod & o) ||
  58474. (mod & g) && gid === myGid ||
  58475. (mod & u) && uid === myUid ||
  58476. (mod & ug) && myUid === 0;
  58477. return ret
  58478. }
  58479. var core$1;
  58480. if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) {
  58481. core$1 = windows$1;
  58482. } else {
  58483. core$1 = mode;
  58484. }
  58485. var isexe_1 = isexe$1;
  58486. isexe$1.sync = sync;
  58487. function isexe$1 (path, options, cb) {
  58488. if (typeof options === 'function') {
  58489. cb = options;
  58490. options = {};
  58491. }
  58492. if (!cb) {
  58493. if (typeof Promise !== 'function') {
  58494. throw new TypeError('callback not provided')
  58495. }
  58496. return new Promise(function (resolve, reject) {
  58497. isexe$1(path, options || {}, function (er, is) {
  58498. if (er) {
  58499. reject(er);
  58500. } else {
  58501. resolve(is);
  58502. }
  58503. });
  58504. })
  58505. }
  58506. core$1(path, options || {}, function (er, is) {
  58507. // ignore EACCES because that just means we aren't allowed to run it
  58508. if (er) {
  58509. if (er.code === 'EACCES' || options && options.ignoreErrors) {
  58510. er = null;
  58511. is = false;
  58512. }
  58513. }
  58514. cb(er, is);
  58515. });
  58516. }
  58517. function sync (path, options) {
  58518. // my kingdom for a filtered catch
  58519. try {
  58520. return core$1.sync(path, options || {})
  58521. } catch (er) {
  58522. if (options && options.ignoreErrors || er.code === 'EACCES') {
  58523. return false
  58524. } else {
  58525. throw er
  58526. }
  58527. }
  58528. }
  58529. const isWindows = process.platform === 'win32' ||
  58530. process.env.OSTYPE === 'cygwin' ||
  58531. process.env.OSTYPE === 'msys';
  58532. const path$8 = path__default;
  58533. const COLON = isWindows ? ';' : ':';
  58534. const isexe = isexe_1;
  58535. const getNotFoundError = (cmd) =>
  58536. Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
  58537. const getPathInfo = (cmd, opt) => {
  58538. const colon = opt.colon || COLON;
  58539. // If it has a slash, then we don't bother searching the pathenv.
  58540. // just check the file itself, and that's it.
  58541. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
  58542. : (
  58543. [
  58544. // windows always checks the cwd first
  58545. ...(isWindows ? [process.cwd()] : []),
  58546. ...(opt.path || process.env.PATH ||
  58547. /* istanbul ignore next: very unusual */ '').split(colon),
  58548. ]
  58549. );
  58550. const pathExtExe = isWindows
  58551. ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
  58552. : '';
  58553. const pathExt = isWindows ? pathExtExe.split(colon) : [''];
  58554. if (isWindows) {
  58555. if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
  58556. pathExt.unshift('');
  58557. }
  58558. return {
  58559. pathEnv,
  58560. pathExt,
  58561. pathExtExe,
  58562. }
  58563. };
  58564. const which$1 = (cmd, opt, cb) => {
  58565. if (typeof opt === 'function') {
  58566. cb = opt;
  58567. opt = {};
  58568. }
  58569. if (!opt)
  58570. opt = {};
  58571. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  58572. const found = [];
  58573. const step = i => new Promise((resolve, reject) => {
  58574. if (i === pathEnv.length)
  58575. return opt.all && found.length ? resolve(found)
  58576. : reject(getNotFoundError(cmd))
  58577. const ppRaw = pathEnv[i];
  58578. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  58579. const pCmd = path$8.join(pathPart, cmd);
  58580. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  58581. : pCmd;
  58582. resolve(subStep(p, i, 0));
  58583. });
  58584. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  58585. if (ii === pathExt.length)
  58586. return resolve(step(i + 1))
  58587. const ext = pathExt[ii];
  58588. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  58589. if (!er && is) {
  58590. if (opt.all)
  58591. found.push(p + ext);
  58592. else
  58593. return resolve(p + ext)
  58594. }
  58595. return resolve(subStep(p, i, ii + 1))
  58596. });
  58597. });
  58598. return cb ? step(0).then(res => cb(null, res), cb) : step(0)
  58599. };
  58600. const whichSync = (cmd, opt) => {
  58601. opt = opt || {};
  58602. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  58603. const found = [];
  58604. for (let i = 0; i < pathEnv.length; i ++) {
  58605. const ppRaw = pathEnv[i];
  58606. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  58607. const pCmd = path$8.join(pathPart, cmd);
  58608. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  58609. : pCmd;
  58610. for (let j = 0; j < pathExt.length; j ++) {
  58611. const cur = p + pathExt[j];
  58612. try {
  58613. const is = isexe.sync(cur, { pathExt: pathExtExe });
  58614. if (is) {
  58615. if (opt.all)
  58616. found.push(cur);
  58617. else
  58618. return cur
  58619. }
  58620. } catch (ex) {}
  58621. }
  58622. }
  58623. if (opt.all && found.length)
  58624. return found
  58625. if (opt.nothrow)
  58626. return null
  58627. throw getNotFoundError(cmd)
  58628. };
  58629. var which_1 = which$1;
  58630. which$1.sync = whichSync;
  58631. var pathKey$3 = {exports: {}};
  58632. const pathKey$2 = (options = {}) => {
  58633. const environment = options.env || process.env;
  58634. const platform = options.platform || process.platform;
  58635. if (platform !== 'win32') {
  58636. return 'PATH';
  58637. }
  58638. return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  58639. };
  58640. pathKey$3.exports = pathKey$2;
  58641. // TODO: Remove this for the next major release
  58642. pathKey$3.exports.default = pathKey$2;
  58643. const path$7 = path__default;
  58644. const which = which_1;
  58645. const getPathKey = pathKey$3.exports;
  58646. function resolveCommandAttempt(parsed, withoutPathExt) {
  58647. const env = parsed.options.env || process.env;
  58648. const cwd = process.cwd();
  58649. const hasCustomCwd = parsed.options.cwd != null;
  58650. // Worker threads do not have process.chdir()
  58651. const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
  58652. // If a custom `cwd` was specified, we need to change the process cwd
  58653. // because `which` will do stat calls but does not support a custom cwd
  58654. if (shouldSwitchCwd) {
  58655. try {
  58656. process.chdir(parsed.options.cwd);
  58657. } catch (err) {
  58658. /* Empty */
  58659. }
  58660. }
  58661. let resolved;
  58662. try {
  58663. resolved = which.sync(parsed.command, {
  58664. path: env[getPathKey({ env })],
  58665. pathExt: withoutPathExt ? path$7.delimiter : undefined,
  58666. });
  58667. } catch (e) {
  58668. /* Empty */
  58669. } finally {
  58670. if (shouldSwitchCwd) {
  58671. process.chdir(cwd);
  58672. }
  58673. }
  58674. // If we successfully resolved, ensure that an absolute path is returned
  58675. // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
  58676. if (resolved) {
  58677. resolved = path$7.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
  58678. }
  58679. return resolved;
  58680. }
  58681. function resolveCommand$1(parsed) {
  58682. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  58683. }
  58684. var resolveCommand_1 = resolveCommand$1;
  58685. var _escape = {};
  58686. // See http://www.robvanderwoude.com/escapechars.php
  58687. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  58688. function escapeCommand(arg) {
  58689. // Escape meta chars
  58690. arg = arg.replace(metaCharsRegExp, '^$1');
  58691. return arg;
  58692. }
  58693. function escapeArgument(arg, doubleEscapeMetaChars) {
  58694. // Convert to string
  58695. arg = `${arg}`;
  58696. // Algorithm below is based on https://qntm.org/cmd
  58697. // Sequence of backslashes followed by a double quote:
  58698. // double up all the backslashes and escape the double quote
  58699. arg = arg.replace(/(\\*)"/g, '$1$1\\"');
  58700. // Sequence of backslashes followed by the end of the string
  58701. // (which will become a double quote later):
  58702. // double up all the backslashes
  58703. arg = arg.replace(/(\\*)$/, '$1$1');
  58704. // All other backslashes occur literally
  58705. // Quote the whole thing:
  58706. arg = `"${arg}"`;
  58707. // Escape meta chars
  58708. arg = arg.replace(metaCharsRegExp, '^$1');
  58709. // Double escape meta chars if necessary
  58710. if (doubleEscapeMetaChars) {
  58711. arg = arg.replace(metaCharsRegExp, '^$1');
  58712. }
  58713. return arg;
  58714. }
  58715. _escape.command = escapeCommand;
  58716. _escape.argument = escapeArgument;
  58717. var shebangRegex$1 = /^#!(.*)/;
  58718. const shebangRegex = shebangRegex$1;
  58719. var shebangCommand$1 = (string = '') => {
  58720. const match = string.match(shebangRegex);
  58721. if (!match) {
  58722. return null;
  58723. }
  58724. const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
  58725. const binary = path.split('/').pop();
  58726. if (binary === 'env') {
  58727. return argument;
  58728. }
  58729. return argument ? `${binary} ${argument}` : binary;
  58730. };
  58731. const fs$2 = fs__default;
  58732. const shebangCommand = shebangCommand$1;
  58733. function readShebang$1(command) {
  58734. // Read the first 150 bytes from the file
  58735. const size = 150;
  58736. const buffer = Buffer.alloc(size);
  58737. let fd;
  58738. try {
  58739. fd = fs$2.openSync(command, 'r');
  58740. fs$2.readSync(fd, buffer, 0, size, 0);
  58741. fs$2.closeSync(fd);
  58742. } catch (e) { /* Empty */ }
  58743. // Attempt to extract shebang (null is returned if not a shebang)
  58744. return shebangCommand(buffer.toString());
  58745. }
  58746. var readShebang_1 = readShebang$1;
  58747. const path$6 = path__default;
  58748. const resolveCommand = resolveCommand_1;
  58749. const escape = _escape;
  58750. const readShebang = readShebang_1;
  58751. const isWin$2 = process.platform === 'win32';
  58752. const isExecutableRegExp = /\.(?:com|exe)$/i;
  58753. const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
  58754. function detectShebang(parsed) {
  58755. parsed.file = resolveCommand(parsed);
  58756. const shebang = parsed.file && readShebang(parsed.file);
  58757. if (shebang) {
  58758. parsed.args.unshift(parsed.file);
  58759. parsed.command = shebang;
  58760. return resolveCommand(parsed);
  58761. }
  58762. return parsed.file;
  58763. }
  58764. function parseNonShell(parsed) {
  58765. if (!isWin$2) {
  58766. return parsed;
  58767. }
  58768. // Detect & add support for shebangs
  58769. const commandFile = detectShebang(parsed);
  58770. // We don't need a shell if the command filename is an executable
  58771. const needsShell = !isExecutableRegExp.test(commandFile);
  58772. // If a shell is required, use cmd.exe and take care of escaping everything correctly
  58773. // Note that `forceShell` is an hidden option used only in tests
  58774. if (parsed.options.forceShell || needsShell) {
  58775. // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
  58776. // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
  58777. // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
  58778. // we need to double escape them
  58779. const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
  58780. // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
  58781. // This is necessary otherwise it will always fail with ENOENT in those cases
  58782. parsed.command = path$6.normalize(parsed.command);
  58783. // Escape command & arguments
  58784. parsed.command = escape.command(parsed.command);
  58785. parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
  58786. const shellCommand = [parsed.command].concat(parsed.args).join(' ');
  58787. parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
  58788. parsed.command = process.env.comspec || 'cmd.exe';
  58789. parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
  58790. }
  58791. return parsed;
  58792. }
  58793. function parse$3(command, args, options) {
  58794. // Normalize arguments, similar to nodejs
  58795. if (args && !Array.isArray(args)) {
  58796. options = args;
  58797. args = null;
  58798. }
  58799. args = args ? args.slice(0) : []; // Clone array to avoid changing the original
  58800. options = Object.assign({}, options); // Clone object to avoid changing the original
  58801. // Build our parsed object
  58802. const parsed = {
  58803. command,
  58804. args,
  58805. options,
  58806. file: undefined,
  58807. original: {
  58808. command,
  58809. args,
  58810. },
  58811. };
  58812. // Delegate further parsing to shell or non-shell
  58813. return options.shell ? parsed : parseNonShell(parsed);
  58814. }
  58815. var parse_1 = parse$3;
  58816. const isWin$1 = process.platform === 'win32';
  58817. function notFoundError(original, syscall) {
  58818. return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
  58819. code: 'ENOENT',
  58820. errno: 'ENOENT',
  58821. syscall: `${syscall} ${original.command}`,
  58822. path: original.command,
  58823. spawnargs: original.args,
  58824. });
  58825. }
  58826. function hookChildProcess(cp, parsed) {
  58827. if (!isWin$1) {
  58828. return;
  58829. }
  58830. const originalEmit = cp.emit;
  58831. cp.emit = function (name, arg1) {
  58832. // If emitting "exit" event and exit code is 1, we need to check if
  58833. // the command exists and emit an "error" instead
  58834. // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
  58835. if (name === 'exit') {
  58836. const err = verifyENOENT(arg1, parsed);
  58837. if (err) {
  58838. return originalEmit.call(cp, 'error', err);
  58839. }
  58840. }
  58841. return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
  58842. };
  58843. }
  58844. function verifyENOENT(status, parsed) {
  58845. if (isWin$1 && status === 1 && !parsed.file) {
  58846. return notFoundError(parsed.original, 'spawn');
  58847. }
  58848. return null;
  58849. }
  58850. function verifyENOENTSync(status, parsed) {
  58851. if (isWin$1 && status === 1 && !parsed.file) {
  58852. return notFoundError(parsed.original, 'spawnSync');
  58853. }
  58854. return null;
  58855. }
  58856. var enoent$1 = {
  58857. hookChildProcess,
  58858. verifyENOENT,
  58859. verifyENOENTSync,
  58860. notFoundError,
  58861. };
  58862. const cp = require$$1__default$4;
  58863. const parse$2 = parse_1;
  58864. const enoent = enoent$1;
  58865. function spawn(command, args, options) {
  58866. // Parse the arguments
  58867. const parsed = parse$2(command, args, options);
  58868. // Spawn the child process
  58869. const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
  58870. // Hook into child process "exit" event to emit an error if the command
  58871. // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  58872. enoent.hookChildProcess(spawned, parsed);
  58873. return spawned;
  58874. }
  58875. function spawnSync(command, args, options) {
  58876. // Parse the arguments
  58877. const parsed = parse$2(command, args, options);
  58878. // Spawn the child process
  58879. const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
  58880. // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  58881. result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
  58882. return result;
  58883. }
  58884. crossSpawn$1.exports = spawn;
  58885. crossSpawn$1.exports.spawn = spawn;
  58886. crossSpawn$1.exports.sync = spawnSync;
  58887. crossSpawn$1.exports._parse = parse$2;
  58888. crossSpawn$1.exports._enoent = enoent;
  58889. var stripFinalNewline$1 = input => {
  58890. const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt();
  58891. const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt();
  58892. if (input[input.length - 1] === LF) {
  58893. input = input.slice(0, input.length - 1);
  58894. }
  58895. if (input[input.length - 1] === CR) {
  58896. input = input.slice(0, input.length - 1);
  58897. }
  58898. return input;
  58899. };
  58900. var npmRunPath$1 = {exports: {}};
  58901. var pathKey$1 = {exports: {}};
  58902. const pathKey = (options = {}) => {
  58903. const environment = options.env || process.env;
  58904. const platform = options.platform || process.platform;
  58905. if (platform !== 'win32') {
  58906. return 'PATH';
  58907. }
  58908. return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  58909. };
  58910. pathKey$1.exports = pathKey;
  58911. // TODO: Remove this for the next major release
  58912. pathKey$1.exports.default = pathKey;
  58913. (function (module) {
  58914. const path = path__default;
  58915. const pathKey = pathKey$1.exports;
  58916. const npmRunPath = options => {
  58917. options = {
  58918. cwd: process.cwd(),
  58919. path: process.env[pathKey()],
  58920. execPath: process.execPath,
  58921. ...options
  58922. };
  58923. let previous;
  58924. let cwdPath = path.resolve(options.cwd);
  58925. const result = [];
  58926. while (previous !== cwdPath) {
  58927. result.push(path.join(cwdPath, 'node_modules/.bin'));
  58928. previous = cwdPath;
  58929. cwdPath = path.resolve(cwdPath, '..');
  58930. }
  58931. // Ensure the running `node` binary is used
  58932. const execPathDir = path.resolve(options.cwd, options.execPath, '..');
  58933. result.push(execPathDir);
  58934. return result.concat(options.path).join(path.delimiter);
  58935. };
  58936. module.exports = npmRunPath;
  58937. // TODO: Remove this for the next major release
  58938. module.exports.default = npmRunPath;
  58939. module.exports.env = options => {
  58940. options = {
  58941. env: process.env,
  58942. ...options
  58943. };
  58944. const env = {...options.env};
  58945. const path = pathKey({env});
  58946. options.path = env[path];
  58947. env[path] = module.exports(options);
  58948. return env;
  58949. };
  58950. }(npmRunPath$1));
  58951. var onetime$2 = {exports: {}};
  58952. var mimicFn$2 = {exports: {}};
  58953. const mimicFn$1 = (to, from) => {
  58954. for (const prop of Reflect.ownKeys(from)) {
  58955. Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
  58956. }
  58957. return to;
  58958. };
  58959. mimicFn$2.exports = mimicFn$1;
  58960. // TODO: Remove this for the next major release
  58961. mimicFn$2.exports.default = mimicFn$1;
  58962. const mimicFn = mimicFn$2.exports;
  58963. const calledFunctions = new WeakMap();
  58964. const onetime$1 = (function_, options = {}) => {
  58965. if (typeof function_ !== 'function') {
  58966. throw new TypeError('Expected a function');
  58967. }
  58968. let returnValue;
  58969. let callCount = 0;
  58970. const functionName = function_.displayName || function_.name || '<anonymous>';
  58971. const onetime = function (...arguments_) {
  58972. calledFunctions.set(onetime, ++callCount);
  58973. if (callCount === 1) {
  58974. returnValue = function_.apply(this, arguments_);
  58975. function_ = null;
  58976. } else if (options.throw === true) {
  58977. throw new Error(`Function \`${functionName}\` can only be called once`);
  58978. }
  58979. return returnValue;
  58980. };
  58981. mimicFn(onetime, function_);
  58982. calledFunctions.set(onetime, callCount);
  58983. return onetime;
  58984. };
  58985. onetime$2.exports = onetime$1;
  58986. // TODO: Remove this for the next major release
  58987. onetime$2.exports.default = onetime$1;
  58988. onetime$2.exports.callCount = function_ => {
  58989. if (!calledFunctions.has(function_)) {
  58990. throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
  58991. }
  58992. return calledFunctions.get(function_);
  58993. };
  58994. var main$2 = {};
  58995. var signals$2 = {};
  58996. var core = {};
  58997. Object.defineProperty(core,"__esModule",{value:true});core.SIGNALS=void 0;
  58998. const SIGNALS=[
  58999. {
  59000. name:"SIGHUP",
  59001. number:1,
  59002. action:"terminate",
  59003. description:"Terminal closed",
  59004. standard:"posix"},
  59005. {
  59006. name:"SIGINT",
  59007. number:2,
  59008. action:"terminate",
  59009. description:"User interruption with CTRL-C",
  59010. standard:"ansi"},
  59011. {
  59012. name:"SIGQUIT",
  59013. number:3,
  59014. action:"core",
  59015. description:"User interruption with CTRL-\\",
  59016. standard:"posix"},
  59017. {
  59018. name:"SIGILL",
  59019. number:4,
  59020. action:"core",
  59021. description:"Invalid machine instruction",
  59022. standard:"ansi"},
  59023. {
  59024. name:"SIGTRAP",
  59025. number:5,
  59026. action:"core",
  59027. description:"Debugger breakpoint",
  59028. standard:"posix"},
  59029. {
  59030. name:"SIGABRT",
  59031. number:6,
  59032. action:"core",
  59033. description:"Aborted",
  59034. standard:"ansi"},
  59035. {
  59036. name:"SIGIOT",
  59037. number:6,
  59038. action:"core",
  59039. description:"Aborted",
  59040. standard:"bsd"},
  59041. {
  59042. name:"SIGBUS",
  59043. number:7,
  59044. action:"core",
  59045. description:
  59046. "Bus error due to misaligned, non-existing address or paging error",
  59047. standard:"bsd"},
  59048. {
  59049. name:"SIGEMT",
  59050. number:7,
  59051. action:"terminate",
  59052. description:"Command should be emulated but is not implemented",
  59053. standard:"other"},
  59054. {
  59055. name:"SIGFPE",
  59056. number:8,
  59057. action:"core",
  59058. description:"Floating point arithmetic error",
  59059. standard:"ansi"},
  59060. {
  59061. name:"SIGKILL",
  59062. number:9,
  59063. action:"terminate",
  59064. description:"Forced termination",
  59065. standard:"posix",
  59066. forced:true},
  59067. {
  59068. name:"SIGUSR1",
  59069. number:10,
  59070. action:"terminate",
  59071. description:"Application-specific signal",
  59072. standard:"posix"},
  59073. {
  59074. name:"SIGSEGV",
  59075. number:11,
  59076. action:"core",
  59077. description:"Segmentation fault",
  59078. standard:"ansi"},
  59079. {
  59080. name:"SIGUSR2",
  59081. number:12,
  59082. action:"terminate",
  59083. description:"Application-specific signal",
  59084. standard:"posix"},
  59085. {
  59086. name:"SIGPIPE",
  59087. number:13,
  59088. action:"terminate",
  59089. description:"Broken pipe or socket",
  59090. standard:"posix"},
  59091. {
  59092. name:"SIGALRM",
  59093. number:14,
  59094. action:"terminate",
  59095. description:"Timeout or timer",
  59096. standard:"posix"},
  59097. {
  59098. name:"SIGTERM",
  59099. number:15,
  59100. action:"terminate",
  59101. description:"Termination",
  59102. standard:"ansi"},
  59103. {
  59104. name:"SIGSTKFLT",
  59105. number:16,
  59106. action:"terminate",
  59107. description:"Stack is empty or overflowed",
  59108. standard:"other"},
  59109. {
  59110. name:"SIGCHLD",
  59111. number:17,
  59112. action:"ignore",
  59113. description:"Child process terminated, paused or unpaused",
  59114. standard:"posix"},
  59115. {
  59116. name:"SIGCLD",
  59117. number:17,
  59118. action:"ignore",
  59119. description:"Child process terminated, paused or unpaused",
  59120. standard:"other"},
  59121. {
  59122. name:"SIGCONT",
  59123. number:18,
  59124. action:"unpause",
  59125. description:"Unpaused",
  59126. standard:"posix",
  59127. forced:true},
  59128. {
  59129. name:"SIGSTOP",
  59130. number:19,
  59131. action:"pause",
  59132. description:"Paused",
  59133. standard:"posix",
  59134. forced:true},
  59135. {
  59136. name:"SIGTSTP",
  59137. number:20,
  59138. action:"pause",
  59139. description:"Paused using CTRL-Z or \"suspend\"",
  59140. standard:"posix"},
  59141. {
  59142. name:"SIGTTIN",
  59143. number:21,
  59144. action:"pause",
  59145. description:"Background process cannot read terminal input",
  59146. standard:"posix"},
  59147. {
  59148. name:"SIGBREAK",
  59149. number:21,
  59150. action:"terminate",
  59151. description:"User interruption with CTRL-BREAK",
  59152. standard:"other"},
  59153. {
  59154. name:"SIGTTOU",
  59155. number:22,
  59156. action:"pause",
  59157. description:"Background process cannot write to terminal output",
  59158. standard:"posix"},
  59159. {
  59160. name:"SIGURG",
  59161. number:23,
  59162. action:"ignore",
  59163. description:"Socket received out-of-band data",
  59164. standard:"bsd"},
  59165. {
  59166. name:"SIGXCPU",
  59167. number:24,
  59168. action:"core",
  59169. description:"Process timed out",
  59170. standard:"bsd"},
  59171. {
  59172. name:"SIGXFSZ",
  59173. number:25,
  59174. action:"core",
  59175. description:"File too big",
  59176. standard:"bsd"},
  59177. {
  59178. name:"SIGVTALRM",
  59179. number:26,
  59180. action:"terminate",
  59181. description:"Timeout or timer",
  59182. standard:"bsd"},
  59183. {
  59184. name:"SIGPROF",
  59185. number:27,
  59186. action:"terminate",
  59187. description:"Timeout or timer",
  59188. standard:"bsd"},
  59189. {
  59190. name:"SIGWINCH",
  59191. number:28,
  59192. action:"ignore",
  59193. description:"Terminal window size changed",
  59194. standard:"bsd"},
  59195. {
  59196. name:"SIGIO",
  59197. number:29,
  59198. action:"terminate",
  59199. description:"I/O is available",
  59200. standard:"other"},
  59201. {
  59202. name:"SIGPOLL",
  59203. number:29,
  59204. action:"terminate",
  59205. description:"Watched event",
  59206. standard:"other"},
  59207. {
  59208. name:"SIGINFO",
  59209. number:29,
  59210. action:"ignore",
  59211. description:"Request for process information",
  59212. standard:"other"},
  59213. {
  59214. name:"SIGPWR",
  59215. number:30,
  59216. action:"terminate",
  59217. description:"Device running out of power",
  59218. standard:"systemv"},
  59219. {
  59220. name:"SIGSYS",
  59221. number:31,
  59222. action:"core",
  59223. description:"Invalid system call",
  59224. standard:"other"},
  59225. {
  59226. name:"SIGUNUSED",
  59227. number:31,
  59228. action:"terminate",
  59229. description:"Invalid system call",
  59230. standard:"other"}];core.SIGNALS=SIGNALS;
  59231. var realtime = {};
  59232. Object.defineProperty(realtime,"__esModule",{value:true});realtime.SIGRTMAX=realtime.getRealtimeSignals=void 0;
  59233. const getRealtimeSignals=function(){
  59234. const length=SIGRTMAX-SIGRTMIN+1;
  59235. return Array.from({length},getRealtimeSignal);
  59236. };realtime.getRealtimeSignals=getRealtimeSignals;
  59237. const getRealtimeSignal=function(value,index){
  59238. return {
  59239. name:`SIGRT${index+1}`,
  59240. number:SIGRTMIN+index,
  59241. action:"terminate",
  59242. description:"Application-specific signal (realtime)",
  59243. standard:"posix"};
  59244. };
  59245. const SIGRTMIN=34;
  59246. const SIGRTMAX=64;realtime.SIGRTMAX=SIGRTMAX;
  59247. Object.defineProperty(signals$2,"__esModule",{value:true});signals$2.getSignals=void 0;var _os$1=require$$0__default$1;
  59248. var _core=core;
  59249. var _realtime$1=realtime;
  59250. const getSignals=function(){
  59251. const realtimeSignals=(0, _realtime$1.getRealtimeSignals)();
  59252. const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal);
  59253. return signals;
  59254. };signals$2.getSignals=getSignals;
  59255. const normalizeSignal=function({
  59256. name,
  59257. number:defaultNumber,
  59258. description,
  59259. action,
  59260. forced=false,
  59261. standard})
  59262. {
  59263. const{
  59264. signals:{[name]:constantSignal}}=
  59265. _os$1.constants;
  59266. const supported=constantSignal!==undefined;
  59267. const number=supported?constantSignal:defaultNumber;
  59268. return {name,number,description,supported,action,forced,standard};
  59269. };
  59270. Object.defineProperty(main$2,"__esModule",{value:true});main$2.signalsByNumber=main$2.signalsByName=void 0;var _os=require$$0__default$1;
  59271. var _signals=signals$2;
  59272. var _realtime=realtime;
  59273. const getSignalsByName=function(){
  59274. const signals=(0, _signals.getSignals)();
  59275. return signals.reduce(getSignalByName,{});
  59276. };
  59277. const getSignalByName=function(
  59278. signalByNameMemo,
  59279. {name,number,description,supported,action,forced,standard})
  59280. {
  59281. return {
  59282. ...signalByNameMemo,
  59283. [name]:{name,number,description,supported,action,forced,standard}};
  59284. };
  59285. const signalsByName$1=getSignalsByName();main$2.signalsByName=signalsByName$1;
  59286. const getSignalsByNumber=function(){
  59287. const signals=(0, _signals.getSignals)();
  59288. const length=_realtime.SIGRTMAX+1;
  59289. const signalsA=Array.from({length},(value,number)=>
  59290. getSignalByNumber(number,signals));
  59291. return Object.assign({},...signalsA);
  59292. };
  59293. const getSignalByNumber=function(number,signals){
  59294. const signal=findSignalByNumber(number,signals);
  59295. if(signal===undefined){
  59296. return {};
  59297. }
  59298. const{name,description,supported,action,forced,standard}=signal;
  59299. return {
  59300. [number]:{
  59301. name,
  59302. number,
  59303. description,
  59304. supported,
  59305. action,
  59306. forced,
  59307. standard}};
  59308. };
  59309. const findSignalByNumber=function(number,signals){
  59310. const signal=signals.find(({name})=>_os.constants.signals[name]===number);
  59311. if(signal!==undefined){
  59312. return signal;
  59313. }
  59314. return signals.find(signalA=>signalA.number===number);
  59315. };
  59316. const signalsByNumber=getSignalsByNumber();main$2.signalsByNumber=signalsByNumber;
  59317. const {signalsByName} = main$2;
  59318. const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
  59319. if (timedOut) {
  59320. return `timed out after ${timeout} milliseconds`;
  59321. }
  59322. if (isCanceled) {
  59323. return 'was canceled';
  59324. }
  59325. if (errorCode !== undefined) {
  59326. return `failed with ${errorCode}`;
  59327. }
  59328. if (signal !== undefined) {
  59329. return `was killed with ${signal} (${signalDescription})`;
  59330. }
  59331. if (exitCode !== undefined) {
  59332. return `failed with exit code ${exitCode}`;
  59333. }
  59334. return 'failed';
  59335. };
  59336. const makeError$1 = ({
  59337. stdout,
  59338. stderr,
  59339. all,
  59340. error,
  59341. signal,
  59342. exitCode,
  59343. command,
  59344. escapedCommand,
  59345. timedOut,
  59346. isCanceled,
  59347. killed,
  59348. parsed: {options: {timeout}}
  59349. }) => {
  59350. // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
  59351. // We normalize them to `undefined`
  59352. exitCode = exitCode === null ? undefined : exitCode;
  59353. signal = signal === null ? undefined : signal;
  59354. const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
  59355. const errorCode = error && error.code;
  59356. const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
  59357. const execaMessage = `Command ${prefix}: ${command}`;
  59358. const isError = Object.prototype.toString.call(error) === '[object Error]';
  59359. const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
  59360. const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
  59361. if (isError) {
  59362. error.originalMessage = error.message;
  59363. error.message = message;
  59364. } else {
  59365. error = new Error(message);
  59366. }
  59367. error.shortMessage = shortMessage;
  59368. error.command = command;
  59369. error.escapedCommand = escapedCommand;
  59370. error.exitCode = exitCode;
  59371. error.signal = signal;
  59372. error.signalDescription = signalDescription;
  59373. error.stdout = stdout;
  59374. error.stderr = stderr;
  59375. if (all !== undefined) {
  59376. error.all = all;
  59377. }
  59378. if ('bufferedData' in error) {
  59379. delete error.bufferedData;
  59380. }
  59381. error.failed = true;
  59382. error.timedOut = Boolean(timedOut);
  59383. error.isCanceled = isCanceled;
  59384. error.killed = killed && !timedOut;
  59385. return error;
  59386. };
  59387. var error = makeError$1;
  59388. var stdio = {exports: {}};
  59389. const aliases = ['stdin', 'stdout', 'stderr'];
  59390. const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
  59391. const normalizeStdio$1 = options => {
  59392. if (!options) {
  59393. return;
  59394. }
  59395. const {stdio} = options;
  59396. if (stdio === undefined) {
  59397. return aliases.map(alias => options[alias]);
  59398. }
  59399. if (hasAlias(options)) {
  59400. throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
  59401. }
  59402. if (typeof stdio === 'string') {
  59403. return stdio;
  59404. }
  59405. if (!Array.isArray(stdio)) {
  59406. throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
  59407. }
  59408. const length = Math.max(stdio.length, aliases.length);
  59409. return Array.from({length}, (value, index) => stdio[index]);
  59410. };
  59411. stdio.exports = normalizeStdio$1;
  59412. // `ipc` is pushed unless it is already present
  59413. stdio.exports.node = options => {
  59414. const stdio = normalizeStdio$1(options);
  59415. if (stdio === 'ipc') {
  59416. return 'ipc';
  59417. }
  59418. if (stdio === undefined || typeof stdio === 'string') {
  59419. return [stdio, stdio, stdio, 'ipc'];
  59420. }
  59421. if (stdio.includes('ipc')) {
  59422. return stdio;
  59423. }
  59424. return [...stdio, 'ipc'];
  59425. };
  59426. var signalExit = {exports: {}};
  59427. var signals$1 = {exports: {}};
  59428. (function (module) {
  59429. // This is not the set of all possible signals.
  59430. //
  59431. // It IS, however, the set of all signals that trigger
  59432. // an exit on either Linux or BSD systems. Linux is a
  59433. // superset of the signal names supported on BSD, and
  59434. // the unknown signals just fail to register, so we can
  59435. // catch that easily enough.
  59436. //
  59437. // Don't bother with SIGKILL. It's uncatchable, which
  59438. // means that we can't fire any callbacks anyway.
  59439. //
  59440. // If a user does happen to register a handler on a non-
  59441. // fatal signal like SIGWINCH or something, and then
  59442. // exit, it'll end up firing `process.emit('exit')`, so
  59443. // the handler will be fired anyway.
  59444. //
  59445. // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
  59446. // artificially, inherently leave the process in a
  59447. // state from which it is not safe to try and enter JS
  59448. // listeners.
  59449. module.exports = [
  59450. 'SIGABRT',
  59451. 'SIGALRM',
  59452. 'SIGHUP',
  59453. 'SIGINT',
  59454. 'SIGTERM'
  59455. ];
  59456. if (process.platform !== 'win32') {
  59457. module.exports.push(
  59458. 'SIGVTALRM',
  59459. 'SIGXCPU',
  59460. 'SIGXFSZ',
  59461. 'SIGUSR2',
  59462. 'SIGTRAP',
  59463. 'SIGSYS',
  59464. 'SIGQUIT',
  59465. 'SIGIOT'
  59466. // should detect profiler and enable/disable accordingly.
  59467. // see #21
  59468. // 'SIGPROF'
  59469. );
  59470. }
  59471. if (process.platform === 'linux') {
  59472. module.exports.push(
  59473. 'SIGIO',
  59474. 'SIGPOLL',
  59475. 'SIGPWR',
  59476. 'SIGSTKFLT',
  59477. 'SIGUNUSED'
  59478. );
  59479. }
  59480. }(signals$1));
  59481. // Note: since nyc uses this module to output coverage, any lines
  59482. // that are in the direct sync flow of nyc's outputCoverage are
  59483. // ignored, since we can never get coverage for them.
  59484. var assert = require$$6__default;
  59485. var signals = signals$1.exports;
  59486. var isWin = /^win/i.test(process.platform);
  59487. var EE = require$$0__default$6;
  59488. /* istanbul ignore if */
  59489. if (typeof EE !== 'function') {
  59490. EE = EE.EventEmitter;
  59491. }
  59492. var emitter;
  59493. if (process.__signal_exit_emitter__) {
  59494. emitter = process.__signal_exit_emitter__;
  59495. } else {
  59496. emitter = process.__signal_exit_emitter__ = new EE();
  59497. emitter.count = 0;
  59498. emitter.emitted = {};
  59499. }
  59500. // Because this emitter is a global, we have to check to see if a
  59501. // previous version of this library failed to enable infinite listeners.
  59502. // I know what you're about to say. But literally everything about
  59503. // signal-exit is a compromise with evil. Get used to it.
  59504. if (!emitter.infinite) {
  59505. emitter.setMaxListeners(Infinity);
  59506. emitter.infinite = true;
  59507. }
  59508. signalExit.exports = function (cb, opts) {
  59509. assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
  59510. if (loaded === false) {
  59511. load();
  59512. }
  59513. var ev = 'exit';
  59514. if (opts && opts.alwaysLast) {
  59515. ev = 'afterexit';
  59516. }
  59517. var remove = function () {
  59518. emitter.removeListener(ev, cb);
  59519. if (emitter.listeners('exit').length === 0 &&
  59520. emitter.listeners('afterexit').length === 0) {
  59521. unload();
  59522. }
  59523. };
  59524. emitter.on(ev, cb);
  59525. return remove
  59526. };
  59527. signalExit.exports.unload = unload;
  59528. function unload () {
  59529. if (!loaded) {
  59530. return
  59531. }
  59532. loaded = false;
  59533. signals.forEach(function (sig) {
  59534. try {
  59535. process.removeListener(sig, sigListeners[sig]);
  59536. } catch (er) {}
  59537. });
  59538. process.emit = originalProcessEmit;
  59539. process.reallyExit = originalProcessReallyExit;
  59540. emitter.count -= 1;
  59541. }
  59542. function emit (event, code, signal) {
  59543. if (emitter.emitted[event]) {
  59544. return
  59545. }
  59546. emitter.emitted[event] = true;
  59547. emitter.emit(event, code, signal);
  59548. }
  59549. // { <signal>: <listener fn>, ... }
  59550. var sigListeners = {};
  59551. signals.forEach(function (sig) {
  59552. sigListeners[sig] = function listener () {
  59553. // If there are no other listeners, an exit is coming!
  59554. // Simplest way: remove us and then re-send the signal.
  59555. // We know that this will kill the process, so we can
  59556. // safely emit now.
  59557. var listeners = process.listeners(sig);
  59558. if (listeners.length === emitter.count) {
  59559. unload();
  59560. emit('exit', null, sig);
  59561. /* istanbul ignore next */
  59562. emit('afterexit', null, sig);
  59563. /* istanbul ignore next */
  59564. if (isWin && sig === 'SIGHUP') {
  59565. // "SIGHUP" throws an `ENOSYS` error on Windows,
  59566. // so use a supported signal instead
  59567. sig = 'SIGINT';
  59568. }
  59569. process.kill(process.pid, sig);
  59570. }
  59571. };
  59572. });
  59573. signalExit.exports.signals = function () {
  59574. return signals
  59575. };
  59576. signalExit.exports.load = load;
  59577. var loaded = false;
  59578. function load () {
  59579. if (loaded) {
  59580. return
  59581. }
  59582. loaded = true;
  59583. // This is the number of onSignalExit's that are in play.
  59584. // It's important so that we can count the correct number of
  59585. // listeners on signals, and don't wait for the other one to
  59586. // handle it instead of us.
  59587. emitter.count += 1;
  59588. signals = signals.filter(function (sig) {
  59589. try {
  59590. process.on(sig, sigListeners[sig]);
  59591. return true
  59592. } catch (er) {
  59593. return false
  59594. }
  59595. });
  59596. process.emit = processEmit;
  59597. process.reallyExit = processReallyExit;
  59598. }
  59599. var originalProcessReallyExit = process.reallyExit;
  59600. function processReallyExit (code) {
  59601. process.exitCode = code || 0;
  59602. emit('exit', process.exitCode, null);
  59603. /* istanbul ignore next */
  59604. emit('afterexit', process.exitCode, null);
  59605. /* istanbul ignore next */
  59606. originalProcessReallyExit.call(process, process.exitCode);
  59607. }
  59608. var originalProcessEmit = process.emit;
  59609. function processEmit (ev, arg) {
  59610. if (ev === 'exit') {
  59611. if (arg !== undefined) {
  59612. process.exitCode = arg;
  59613. }
  59614. var ret = originalProcessEmit.apply(this, arguments);
  59615. emit('exit', process.exitCode, null);
  59616. /* istanbul ignore next */
  59617. emit('afterexit', process.exitCode, null);
  59618. return ret
  59619. } else {
  59620. return originalProcessEmit.apply(this, arguments)
  59621. }
  59622. }
  59623. const os$3 = require$$0__default$1;
  59624. const onExit = signalExit.exports;
  59625. const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
  59626. // Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
  59627. const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => {
  59628. const killResult = kill(signal);
  59629. setKillTimeout(kill, signal, options, killResult);
  59630. return killResult;
  59631. };
  59632. const setKillTimeout = (kill, signal, options, killResult) => {
  59633. if (!shouldForceKill(signal, options, killResult)) {
  59634. return;
  59635. }
  59636. const timeout = getForceKillAfterTimeout(options);
  59637. const t = setTimeout(() => {
  59638. kill('SIGKILL');
  59639. }, timeout);
  59640. // Guarded because there's no `.unref()` when `execa` is used in the renderer
  59641. // process in Electron. This cannot be tested since we don't run tests in
  59642. // Electron.
  59643. // istanbul ignore else
  59644. if (t.unref) {
  59645. t.unref();
  59646. }
  59647. };
  59648. const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {
  59649. return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
  59650. };
  59651. const isSigterm = signal => {
  59652. return signal === os$3.constants.signals.SIGTERM ||
  59653. (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
  59654. };
  59655. const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
  59656. if (forceKillAfterTimeout === true) {
  59657. return DEFAULT_FORCE_KILL_TIMEOUT;
  59658. }
  59659. if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
  59660. throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
  59661. }
  59662. return forceKillAfterTimeout;
  59663. };
  59664. // `childProcess.cancel()`
  59665. const spawnedCancel$1 = (spawned, context) => {
  59666. const killResult = spawned.kill();
  59667. if (killResult) {
  59668. context.isCanceled = true;
  59669. }
  59670. };
  59671. const timeoutKill = (spawned, signal, reject) => {
  59672. spawned.kill(signal);
  59673. reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
  59674. };
  59675. // `timeout` option handling
  59676. const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
  59677. if (timeout === 0 || timeout === undefined) {
  59678. return spawnedPromise;
  59679. }
  59680. let timeoutId;
  59681. const timeoutPromise = new Promise((resolve, reject) => {
  59682. timeoutId = setTimeout(() => {
  59683. timeoutKill(spawned, killSignal, reject);
  59684. }, timeout);
  59685. });
  59686. const safeSpawnedPromise = spawnedPromise.finally(() => {
  59687. clearTimeout(timeoutId);
  59688. });
  59689. return Promise.race([timeoutPromise, safeSpawnedPromise]);
  59690. };
  59691. const validateTimeout$1 = ({timeout}) => {
  59692. if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
  59693. throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
  59694. }
  59695. };
  59696. // `cleanup` option handling
  59697. const setExitHandler$1 = async (spawned, {cleanup, detached}, timedPromise) => {
  59698. if (!cleanup || detached) {
  59699. return timedPromise;
  59700. }
  59701. const removeExitHandler = onExit(() => {
  59702. spawned.kill();
  59703. });
  59704. return timedPromise.finally(() => {
  59705. removeExitHandler();
  59706. });
  59707. };
  59708. var kill = {
  59709. spawnedKill: spawnedKill$1,
  59710. spawnedCancel: spawnedCancel$1,
  59711. setupTimeout: setupTimeout$1,
  59712. validateTimeout: validateTimeout$1,
  59713. setExitHandler: setExitHandler$1
  59714. };
  59715. const isStream$1 = stream =>
  59716. stream !== null &&
  59717. typeof stream === 'object' &&
  59718. typeof stream.pipe === 'function';
  59719. isStream$1.writable = stream =>
  59720. isStream$1(stream) &&
  59721. stream.writable !== false &&
  59722. typeof stream._write === 'function' &&
  59723. typeof stream._writableState === 'object';
  59724. isStream$1.readable = stream =>
  59725. isStream$1(stream) &&
  59726. stream.readable !== false &&
  59727. typeof stream._read === 'function' &&
  59728. typeof stream._readableState === 'object';
  59729. isStream$1.duplex = stream =>
  59730. isStream$1.writable(stream) &&
  59731. isStream$1.readable(stream);
  59732. isStream$1.transform = stream =>
  59733. isStream$1.duplex(stream) &&
  59734. typeof stream._transform === 'function';
  59735. var isStream_1 = isStream$1;
  59736. var getStream$2 = {exports: {}};
  59737. const {PassThrough: PassThroughStream} = require$$0__default$2;
  59738. var bufferStream$1 = options => {
  59739. options = {...options};
  59740. const {array} = options;
  59741. let {encoding} = options;
  59742. const isBuffer = encoding === 'buffer';
  59743. let objectMode = false;
  59744. if (array) {
  59745. objectMode = !(encoding || isBuffer);
  59746. } else {
  59747. encoding = encoding || 'utf8';
  59748. }
  59749. if (isBuffer) {
  59750. encoding = null;
  59751. }
  59752. const stream = new PassThroughStream({objectMode});
  59753. if (encoding) {
  59754. stream.setEncoding(encoding);
  59755. }
  59756. let length = 0;
  59757. const chunks = [];
  59758. stream.on('data', chunk => {
  59759. chunks.push(chunk);
  59760. if (objectMode) {
  59761. length = chunks.length;
  59762. } else {
  59763. length += chunk.length;
  59764. }
  59765. });
  59766. stream.getBufferedValue = () => {
  59767. if (array) {
  59768. return chunks;
  59769. }
  59770. return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
  59771. };
  59772. stream.getBufferedLength = () => length;
  59773. return stream;
  59774. };
  59775. const {constants: BufferConstants} = require$$0__default$8;
  59776. const stream$1 = require$$0__default$2;
  59777. const {promisify} = require$$0__default$3;
  59778. const bufferStream = bufferStream$1;
  59779. const streamPipelinePromisified = promisify(stream$1.pipeline);
  59780. class MaxBufferError extends Error {
  59781. constructor() {
  59782. super('maxBuffer exceeded');
  59783. this.name = 'MaxBufferError';
  59784. }
  59785. }
  59786. async function getStream$1(inputStream, options) {
  59787. if (!inputStream) {
  59788. throw new Error('Expected a stream');
  59789. }
  59790. options = {
  59791. maxBuffer: Infinity,
  59792. ...options
  59793. };
  59794. const {maxBuffer} = options;
  59795. const stream = bufferStream(options);
  59796. await new Promise((resolve, reject) => {
  59797. const rejectPromise = error => {
  59798. // Don't retrieve an oversized buffer.
  59799. if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
  59800. error.bufferedData = stream.getBufferedValue();
  59801. }
  59802. reject(error);
  59803. };
  59804. (async () => {
  59805. try {
  59806. await streamPipelinePromisified(inputStream, stream);
  59807. resolve();
  59808. } catch (error) {
  59809. rejectPromise(error);
  59810. }
  59811. })();
  59812. stream.on('data', () => {
  59813. if (stream.getBufferedLength() > maxBuffer) {
  59814. rejectPromise(new MaxBufferError());
  59815. }
  59816. });
  59817. });
  59818. return stream.getBufferedValue();
  59819. }
  59820. getStream$2.exports = getStream$1;
  59821. getStream$2.exports.buffer = (stream, options) => getStream$1(stream, {...options, encoding: 'buffer'});
  59822. getStream$2.exports.array = (stream, options) => getStream$1(stream, {...options, array: true});
  59823. getStream$2.exports.MaxBufferError = MaxBufferError;
  59824. const { PassThrough } = require$$0__default$2;
  59825. var mergeStream$1 = function (/*streams...*/) {
  59826. var sources = [];
  59827. var output = new PassThrough({objectMode: true});
  59828. output.setMaxListeners(0);
  59829. output.add = add;
  59830. output.isEmpty = isEmpty;
  59831. output.on('unpipe', remove);
  59832. Array.prototype.slice.call(arguments).forEach(add);
  59833. return output
  59834. function add (source) {
  59835. if (Array.isArray(source)) {
  59836. source.forEach(add);
  59837. return this
  59838. }
  59839. sources.push(source);
  59840. source.once('end', remove.bind(null, source));
  59841. source.once('error', output.emit.bind(output, 'error'));
  59842. source.pipe(output, {end: false});
  59843. return this
  59844. }
  59845. function isEmpty () {
  59846. return sources.length == 0;
  59847. }
  59848. function remove (source) {
  59849. sources = sources.filter(function (it) { return it !== source });
  59850. if (!sources.length && output.readable) { output.end(); }
  59851. }
  59852. };
  59853. const isStream = isStream_1;
  59854. const getStream = getStream$2.exports;
  59855. const mergeStream = mergeStream$1;
  59856. // `input` option
  59857. const handleInput$1 = (spawned, input) => {
  59858. // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
  59859. // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
  59860. if (input === undefined || spawned.stdin === undefined) {
  59861. return;
  59862. }
  59863. if (isStream(input)) {
  59864. input.pipe(spawned.stdin);
  59865. } else {
  59866. spawned.stdin.end(input);
  59867. }
  59868. };
  59869. // `all` interleaves `stdout` and `stderr`
  59870. const makeAllStream$1 = (spawned, {all}) => {
  59871. if (!all || (!spawned.stdout && !spawned.stderr)) {
  59872. return;
  59873. }
  59874. const mixed = mergeStream();
  59875. if (spawned.stdout) {
  59876. mixed.add(spawned.stdout);
  59877. }
  59878. if (spawned.stderr) {
  59879. mixed.add(spawned.stderr);
  59880. }
  59881. return mixed;
  59882. };
  59883. // On failure, `result.stdout|stderr|all` should contain the currently buffered stream
  59884. const getBufferedData = async (stream, streamPromise) => {
  59885. if (!stream) {
  59886. return;
  59887. }
  59888. stream.destroy();
  59889. try {
  59890. return await streamPromise;
  59891. } catch (error) {
  59892. return error.bufferedData;
  59893. }
  59894. };
  59895. const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
  59896. if (!stream || !buffer) {
  59897. return;
  59898. }
  59899. if (encoding) {
  59900. return getStream(stream, {encoding, maxBuffer});
  59901. }
  59902. return getStream.buffer(stream, {maxBuffer});
  59903. };
  59904. // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
  59905. const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
  59906. const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
  59907. const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
  59908. const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
  59909. try {
  59910. return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
  59911. } catch (error) {
  59912. return Promise.all([
  59913. {error, signal: error.signal, timedOut: error.timedOut},
  59914. getBufferedData(stdout, stdoutPromise),
  59915. getBufferedData(stderr, stderrPromise),
  59916. getBufferedData(all, allPromise)
  59917. ]);
  59918. }
  59919. };
  59920. const validateInputSync$1 = ({input}) => {
  59921. if (isStream(input)) {
  59922. throw new TypeError('The `input` option cannot be a stream in sync mode');
  59923. }
  59924. };
  59925. var stream = {
  59926. handleInput: handleInput$1,
  59927. makeAllStream: makeAllStream$1,
  59928. getSpawnedResult: getSpawnedResult$1,
  59929. validateInputSync: validateInputSync$1
  59930. };
  59931. const nativePromisePrototype = (async () => {})().constructor.prototype;
  59932. const descriptors = ['then', 'catch', 'finally'].map(property => [
  59933. property,
  59934. Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
  59935. ]);
  59936. // The return value is a mixin of `childProcess` and `Promise`
  59937. const mergePromise$1 = (spawned, promise) => {
  59938. for (const [property, descriptor] of descriptors) {
  59939. // Starting the main `promise` is deferred to avoid consuming streams
  59940. const value = typeof promise === 'function' ?
  59941. (...args) => Reflect.apply(descriptor.value, promise(), args) :
  59942. descriptor.value.bind(promise);
  59943. Reflect.defineProperty(spawned, property, {...descriptor, value});
  59944. }
  59945. return spawned;
  59946. };
  59947. // Use promises instead of `child_process` events
  59948. const getSpawnedPromise$1 = spawned => {
  59949. return new Promise((resolve, reject) => {
  59950. spawned.on('exit', (exitCode, signal) => {
  59951. resolve({exitCode, signal});
  59952. });
  59953. spawned.on('error', error => {
  59954. reject(error);
  59955. });
  59956. if (spawned.stdin) {
  59957. spawned.stdin.on('error', error => {
  59958. reject(error);
  59959. });
  59960. }
  59961. });
  59962. };
  59963. var promise = {
  59964. mergePromise: mergePromise$1,
  59965. getSpawnedPromise: getSpawnedPromise$1
  59966. };
  59967. const normalizeArgs = (file, args = []) => {
  59968. if (!Array.isArray(args)) {
  59969. return [file];
  59970. }
  59971. return [file, ...args];
  59972. };
  59973. const NO_ESCAPE_REGEXP = /^[\w.-]+$/;
  59974. const DOUBLE_QUOTES_REGEXP = /"/g;
  59975. const escapeArg = arg => {
  59976. if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) {
  59977. return arg;
  59978. }
  59979. return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
  59980. };
  59981. const joinCommand$1 = (file, args) => {
  59982. return normalizeArgs(file, args).join(' ');
  59983. };
  59984. const getEscapedCommand$1 = (file, args) => {
  59985. return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');
  59986. };
  59987. const SPACES_REGEXP = / +/g;
  59988. // Handle `execa.command()`
  59989. const parseCommand$1 = command => {
  59990. const tokens = [];
  59991. for (const token of command.trim().split(SPACES_REGEXP)) {
  59992. // Allow spaces to be escaped by a backslash if not meant as a delimiter
  59993. const previousToken = tokens[tokens.length - 1];
  59994. if (previousToken && previousToken.endsWith('\\')) {
  59995. // Merge previous token with current one
  59996. tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
  59997. } else {
  59998. tokens.push(token);
  59999. }
  60000. }
  60001. return tokens;
  60002. };
  60003. var command = {
  60004. joinCommand: joinCommand$1,
  60005. getEscapedCommand: getEscapedCommand$1,
  60006. parseCommand: parseCommand$1
  60007. };
  60008. const path$5 = path__default;
  60009. const childProcess$2 = require$$1__default$4;
  60010. const crossSpawn = crossSpawn$1.exports;
  60011. const stripFinalNewline = stripFinalNewline$1;
  60012. const npmRunPath = npmRunPath$1.exports;
  60013. const onetime = onetime$2.exports;
  60014. const makeError = error;
  60015. const normalizeStdio = stdio.exports;
  60016. const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = kill;
  60017. const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream;
  60018. const {mergePromise, getSpawnedPromise} = promise;
  60019. const {joinCommand, parseCommand, getEscapedCommand} = command;
  60020. const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
  60021. const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
  60022. const env = extendEnv ? {...process.env, ...envOption} : envOption;
  60023. if (preferLocal) {
  60024. return npmRunPath.env({env, cwd: localDir, execPath});
  60025. }
  60026. return env;
  60027. };
  60028. const handleArguments = (file, args, options = {}) => {
  60029. const parsed = crossSpawn._parse(file, args, options);
  60030. file = parsed.command;
  60031. args = parsed.args;
  60032. options = parsed.options;
  60033. options = {
  60034. maxBuffer: DEFAULT_MAX_BUFFER,
  60035. buffer: true,
  60036. stripFinalNewline: true,
  60037. extendEnv: true,
  60038. preferLocal: false,
  60039. localDir: options.cwd || process.cwd(),
  60040. execPath: process.execPath,
  60041. encoding: 'utf8',
  60042. reject: true,
  60043. cleanup: true,
  60044. all: false,
  60045. windowsHide: true,
  60046. ...options
  60047. };
  60048. options.env = getEnv(options);
  60049. options.stdio = normalizeStdio(options);
  60050. if (process.platform === 'win32' && path$5.basename(file, '.exe') === 'cmd') {
  60051. // #116
  60052. args.unshift('/q');
  60053. }
  60054. return {file, args, options, parsed};
  60055. };
  60056. const handleOutput = (options, value, error) => {
  60057. if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
  60058. // When `execa.sync()` errors, we normalize it to '' to mimic `execa()`
  60059. return error === undefined ? undefined : '';
  60060. }
  60061. if (options.stripFinalNewline) {
  60062. return stripFinalNewline(value);
  60063. }
  60064. return value;
  60065. };
  60066. const execa = (file, args, options) => {
  60067. const parsed = handleArguments(file, args, options);
  60068. const command = joinCommand(file, args);
  60069. const escapedCommand = getEscapedCommand(file, args);
  60070. validateTimeout(parsed.options);
  60071. let spawned;
  60072. try {
  60073. spawned = childProcess$2.spawn(parsed.file, parsed.args, parsed.options);
  60074. } catch (error) {
  60075. // Ensure the returned error is always both a promise and a child process
  60076. const dummySpawned = new childProcess$2.ChildProcess();
  60077. const errorPromise = Promise.reject(makeError({
  60078. error,
  60079. stdout: '',
  60080. stderr: '',
  60081. all: '',
  60082. command,
  60083. escapedCommand,
  60084. parsed,
  60085. timedOut: false,
  60086. isCanceled: false,
  60087. killed: false
  60088. }));
  60089. return mergePromise(dummySpawned, errorPromise);
  60090. }
  60091. const spawnedPromise = getSpawnedPromise(spawned);
  60092. const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
  60093. const processDone = setExitHandler(spawned, parsed.options, timedPromise);
  60094. const context = {isCanceled: false};
  60095. spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
  60096. spawned.cancel = spawnedCancel.bind(null, spawned, context);
  60097. const handlePromise = async () => {
  60098. const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
  60099. const stdout = handleOutput(parsed.options, stdoutResult);
  60100. const stderr = handleOutput(parsed.options, stderrResult);
  60101. const all = handleOutput(parsed.options, allResult);
  60102. if (error || exitCode !== 0 || signal !== null) {
  60103. const returnedError = makeError({
  60104. error,
  60105. exitCode,
  60106. signal,
  60107. stdout,
  60108. stderr,
  60109. all,
  60110. command,
  60111. escapedCommand,
  60112. parsed,
  60113. timedOut,
  60114. isCanceled: context.isCanceled,
  60115. killed: spawned.killed
  60116. });
  60117. if (!parsed.options.reject) {
  60118. return returnedError;
  60119. }
  60120. throw returnedError;
  60121. }
  60122. return {
  60123. command,
  60124. escapedCommand,
  60125. exitCode: 0,
  60126. stdout,
  60127. stderr,
  60128. all,
  60129. failed: false,
  60130. timedOut: false,
  60131. isCanceled: false,
  60132. killed: false
  60133. };
  60134. };
  60135. const handlePromiseOnce = onetime(handlePromise);
  60136. handleInput(spawned, parsed.options.input);
  60137. spawned.all = makeAllStream(spawned, parsed.options);
  60138. return mergePromise(spawned, handlePromiseOnce);
  60139. };
  60140. execa$2.exports = execa;
  60141. execa$2.exports.sync = (file, args, options) => {
  60142. const parsed = handleArguments(file, args, options);
  60143. const command = joinCommand(file, args);
  60144. const escapedCommand = getEscapedCommand(file, args);
  60145. validateInputSync(parsed.options);
  60146. let result;
  60147. try {
  60148. result = childProcess$2.spawnSync(parsed.file, parsed.args, parsed.options);
  60149. } catch (error) {
  60150. throw makeError({
  60151. error,
  60152. stdout: '',
  60153. stderr: '',
  60154. all: '',
  60155. command,
  60156. escapedCommand,
  60157. parsed,
  60158. timedOut: false,
  60159. isCanceled: false,
  60160. killed: false
  60161. });
  60162. }
  60163. const stdout = handleOutput(parsed.options, result.stdout, result.error);
  60164. const stderr = handleOutput(parsed.options, result.stderr, result.error);
  60165. if (result.error || result.status !== 0 || result.signal !== null) {
  60166. const error = makeError({
  60167. stdout,
  60168. stderr,
  60169. error: result.error,
  60170. signal: result.signal,
  60171. exitCode: result.status,
  60172. command,
  60173. escapedCommand,
  60174. parsed,
  60175. timedOut: result.error && result.error.code === 'ETIMEDOUT',
  60176. isCanceled: false,
  60177. killed: result.signal !== null
  60178. });
  60179. if (!parsed.options.reject) {
  60180. return error;
  60181. }
  60182. throw error;
  60183. }
  60184. return {
  60185. command,
  60186. escapedCommand,
  60187. exitCode: 0,
  60188. stdout,
  60189. stderr,
  60190. failed: false,
  60191. timedOut: false,
  60192. isCanceled: false,
  60193. killed: false
  60194. };
  60195. };
  60196. execa$2.exports.command = (command, options) => {
  60197. const [file, ...args] = parseCommand(command);
  60198. return execa(file, args, options);
  60199. };
  60200. execa$2.exports.commandSync = (command, options) => {
  60201. const [file, ...args] = parseCommand(command);
  60202. return execa.sync(file, args, options);
  60203. };
  60204. execa$2.exports.node = (scriptPath, args, options = {}) => {
  60205. if (args && !Array.isArray(args) && typeof args === 'object') {
  60206. options = args;
  60207. args = [];
  60208. }
  60209. const stdio = normalizeStdio.node(options);
  60210. const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));
  60211. const {
  60212. nodePath = process.execPath,
  60213. nodeOptions = defaultExecArgv
  60214. } = options;
  60215. return execa(
  60216. nodePath,
  60217. [
  60218. ...nodeOptions,
  60219. scriptPath,
  60220. ...(Array.isArray(args) ? args : [])
  60221. ],
  60222. {
  60223. ...options,
  60224. stdin: undefined,
  60225. stdout: undefined,
  60226. stderr: undefined,
  60227. stdio,
  60228. shell: false
  60229. }
  60230. );
  60231. };
  60232. var execa$1 = execa$2.exports;
  60233. /**
  60234. * The following is modified based on source found in
  60235. * https://github.com/facebook/create-react-app
  60236. *
  60237. * MIT Licensed
  60238. * Copyright (c) 2015-present, Facebook, Inc.
  60239. * https://github.com/facebook/create-react-app/blob/master/LICENSE
  60240. *
  60241. */
  60242. // https://github.com/sindresorhus/open#app
  60243. const OSX_CHROME = 'google chrome';
  60244. /**
  60245. * Reads the BROWSER environment variable and decides what to do with it.
  60246. * Returns true if it opened a browser or ran a node.js script, otherwise false.
  60247. */
  60248. function openBrowser(url, opt, logger) {
  60249. // The browser executable to open.
  60250. // See https://github.com/sindresorhus/open#app for documentation.
  60251. const browser = typeof opt === 'string' ? opt : process.env.BROWSER || '';
  60252. if (browser.toLowerCase().endsWith('.js')) {
  60253. return executeNodeScript(browser, url, logger);
  60254. }
  60255. else if (browser.toLowerCase() !== 'none') {
  60256. return startBrowserProcess(browser, url);
  60257. }
  60258. return false;
  60259. }
  60260. function executeNodeScript(scriptPath, url, logger) {
  60261. const extraArgs = process.argv.slice(2);
  60262. const child = execa$1('node', [scriptPath, ...extraArgs, url], {
  60263. stdio: 'inherit'
  60264. });
  60265. child.on('close', (code) => {
  60266. if (code !== 0) {
  60267. logger.error(source.red(`\nThe script specified as BROWSER environment variable failed.\n\n${source.cyan(scriptPath)} exited with code ${code}.`), { error: null });
  60268. }
  60269. });
  60270. return true;
  60271. }
  60272. function startBrowserProcess(browser, url) {
  60273. // If we're on OS X, the user hasn't specifically
  60274. // requested a different browser, we can try opening
  60275. // Chrome with AppleScript. This lets us reuse an
  60276. // existing tab when possible instead of creating a new one.
  60277. const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME);
  60278. if (shouldTryOpenChromeWithAppleScript) {
  60279. try {
  60280. // Try our best to reuse existing tab
  60281. // on OS X Google Chrome with AppleScript
  60282. require$$1$5.execSync('ps cax | grep "Google Chrome"');
  60283. require$$1$5.execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
  60284. cwd: path__default.dirname(require.resolve('vite/bin/openChrome.applescript')),
  60285. stdio: 'ignore'
  60286. });
  60287. return true;
  60288. }
  60289. catch (err) {
  60290. // Ignore errors
  60291. }
  60292. }
  60293. // Another special case: on OS X, check if BROWSER has been set to "open".
  60294. // In this case, instead of passing the string `open` to `open` function (which won't work),
  60295. // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
  60296. // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
  60297. if (process.platform === 'darwin' && browser === 'open') {
  60298. browser = undefined;
  60299. }
  60300. // Fallback to open
  60301. // (It will always open new tab)
  60302. try {
  60303. const options = browser ? { app: { name: browser } } : {};
  60304. open_1(url, options).catch(() => { }); // Prevent `unhandledRejection` error.
  60305. return true;
  60306. }
  60307. catch (err) {
  60308. return false;
  60309. }
  60310. }
  60311. var chalk$1 = {exports: {}};
  60312. var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
  60313. var escapeStringRegexp = function (str) {
  60314. if (typeof str !== 'string') {
  60315. throw new TypeError('Expected a string');
  60316. }
  60317. return str.replace(matchOperatorsRe, '\\$&');
  60318. };
  60319. var ansiStyles = {exports: {}};
  60320. var conversions$2 = {exports: {}};
  60321. var colorName = {
  60322. "aliceblue": [240, 248, 255],
  60323. "antiquewhite": [250, 235, 215],
  60324. "aqua": [0, 255, 255],
  60325. "aquamarine": [127, 255, 212],
  60326. "azure": [240, 255, 255],
  60327. "beige": [245, 245, 220],
  60328. "bisque": [255, 228, 196],
  60329. "black": [0, 0, 0],
  60330. "blanchedalmond": [255, 235, 205],
  60331. "blue": [0, 0, 255],
  60332. "blueviolet": [138, 43, 226],
  60333. "brown": [165, 42, 42],
  60334. "burlywood": [222, 184, 135],
  60335. "cadetblue": [95, 158, 160],
  60336. "chartreuse": [127, 255, 0],
  60337. "chocolate": [210, 105, 30],
  60338. "coral": [255, 127, 80],
  60339. "cornflowerblue": [100, 149, 237],
  60340. "cornsilk": [255, 248, 220],
  60341. "crimson": [220, 20, 60],
  60342. "cyan": [0, 255, 255],
  60343. "darkblue": [0, 0, 139],
  60344. "darkcyan": [0, 139, 139],
  60345. "darkgoldenrod": [184, 134, 11],
  60346. "darkgray": [169, 169, 169],
  60347. "darkgreen": [0, 100, 0],
  60348. "darkgrey": [169, 169, 169],
  60349. "darkkhaki": [189, 183, 107],
  60350. "darkmagenta": [139, 0, 139],
  60351. "darkolivegreen": [85, 107, 47],
  60352. "darkorange": [255, 140, 0],
  60353. "darkorchid": [153, 50, 204],
  60354. "darkred": [139, 0, 0],
  60355. "darksalmon": [233, 150, 122],
  60356. "darkseagreen": [143, 188, 143],
  60357. "darkslateblue": [72, 61, 139],
  60358. "darkslategray": [47, 79, 79],
  60359. "darkslategrey": [47, 79, 79],
  60360. "darkturquoise": [0, 206, 209],
  60361. "darkviolet": [148, 0, 211],
  60362. "deeppink": [255, 20, 147],
  60363. "deepskyblue": [0, 191, 255],
  60364. "dimgray": [105, 105, 105],
  60365. "dimgrey": [105, 105, 105],
  60366. "dodgerblue": [30, 144, 255],
  60367. "firebrick": [178, 34, 34],
  60368. "floralwhite": [255, 250, 240],
  60369. "forestgreen": [34, 139, 34],
  60370. "fuchsia": [255, 0, 255],
  60371. "gainsboro": [220, 220, 220],
  60372. "ghostwhite": [248, 248, 255],
  60373. "gold": [255, 215, 0],
  60374. "goldenrod": [218, 165, 32],
  60375. "gray": [128, 128, 128],
  60376. "green": [0, 128, 0],
  60377. "greenyellow": [173, 255, 47],
  60378. "grey": [128, 128, 128],
  60379. "honeydew": [240, 255, 240],
  60380. "hotpink": [255, 105, 180],
  60381. "indianred": [205, 92, 92],
  60382. "indigo": [75, 0, 130],
  60383. "ivory": [255, 255, 240],
  60384. "khaki": [240, 230, 140],
  60385. "lavender": [230, 230, 250],
  60386. "lavenderblush": [255, 240, 245],
  60387. "lawngreen": [124, 252, 0],
  60388. "lemonchiffon": [255, 250, 205],
  60389. "lightblue": [173, 216, 230],
  60390. "lightcoral": [240, 128, 128],
  60391. "lightcyan": [224, 255, 255],
  60392. "lightgoldenrodyellow": [250, 250, 210],
  60393. "lightgray": [211, 211, 211],
  60394. "lightgreen": [144, 238, 144],
  60395. "lightgrey": [211, 211, 211],
  60396. "lightpink": [255, 182, 193],
  60397. "lightsalmon": [255, 160, 122],
  60398. "lightseagreen": [32, 178, 170],
  60399. "lightskyblue": [135, 206, 250],
  60400. "lightslategray": [119, 136, 153],
  60401. "lightslategrey": [119, 136, 153],
  60402. "lightsteelblue": [176, 196, 222],
  60403. "lightyellow": [255, 255, 224],
  60404. "lime": [0, 255, 0],
  60405. "limegreen": [50, 205, 50],
  60406. "linen": [250, 240, 230],
  60407. "magenta": [255, 0, 255],
  60408. "maroon": [128, 0, 0],
  60409. "mediumaquamarine": [102, 205, 170],
  60410. "mediumblue": [0, 0, 205],
  60411. "mediumorchid": [186, 85, 211],
  60412. "mediumpurple": [147, 112, 219],
  60413. "mediumseagreen": [60, 179, 113],
  60414. "mediumslateblue": [123, 104, 238],
  60415. "mediumspringgreen": [0, 250, 154],
  60416. "mediumturquoise": [72, 209, 204],
  60417. "mediumvioletred": [199, 21, 133],
  60418. "midnightblue": [25, 25, 112],
  60419. "mintcream": [245, 255, 250],
  60420. "mistyrose": [255, 228, 225],
  60421. "moccasin": [255, 228, 181],
  60422. "navajowhite": [255, 222, 173],
  60423. "navy": [0, 0, 128],
  60424. "oldlace": [253, 245, 230],
  60425. "olive": [128, 128, 0],
  60426. "olivedrab": [107, 142, 35],
  60427. "orange": [255, 165, 0],
  60428. "orangered": [255, 69, 0],
  60429. "orchid": [218, 112, 214],
  60430. "palegoldenrod": [238, 232, 170],
  60431. "palegreen": [152, 251, 152],
  60432. "paleturquoise": [175, 238, 238],
  60433. "palevioletred": [219, 112, 147],
  60434. "papayawhip": [255, 239, 213],
  60435. "peachpuff": [255, 218, 185],
  60436. "peru": [205, 133, 63],
  60437. "pink": [255, 192, 203],
  60438. "plum": [221, 160, 221],
  60439. "powderblue": [176, 224, 230],
  60440. "purple": [128, 0, 128],
  60441. "rebeccapurple": [102, 51, 153],
  60442. "red": [255, 0, 0],
  60443. "rosybrown": [188, 143, 143],
  60444. "royalblue": [65, 105, 225],
  60445. "saddlebrown": [139, 69, 19],
  60446. "salmon": [250, 128, 114],
  60447. "sandybrown": [244, 164, 96],
  60448. "seagreen": [46, 139, 87],
  60449. "seashell": [255, 245, 238],
  60450. "sienna": [160, 82, 45],
  60451. "silver": [192, 192, 192],
  60452. "skyblue": [135, 206, 235],
  60453. "slateblue": [106, 90, 205],
  60454. "slategray": [112, 128, 144],
  60455. "slategrey": [112, 128, 144],
  60456. "snow": [255, 250, 250],
  60457. "springgreen": [0, 255, 127],
  60458. "steelblue": [70, 130, 180],
  60459. "tan": [210, 180, 140],
  60460. "teal": [0, 128, 128],
  60461. "thistle": [216, 191, 216],
  60462. "tomato": [255, 99, 71],
  60463. "turquoise": [64, 224, 208],
  60464. "violet": [238, 130, 238],
  60465. "wheat": [245, 222, 179],
  60466. "white": [255, 255, 255],
  60467. "whitesmoke": [245, 245, 245],
  60468. "yellow": [255, 255, 0],
  60469. "yellowgreen": [154, 205, 50]
  60470. };
  60471. /* MIT license */
  60472. var cssKeywords = colorName;
  60473. // NOTE: conversions should only return primitive values (i.e. arrays, or
  60474. // values that give correct `typeof` results).
  60475. // do not use box values types (i.e. Number(), String(), etc.)
  60476. var reverseKeywords = {};
  60477. for (var key in cssKeywords) {
  60478. if (cssKeywords.hasOwnProperty(key)) {
  60479. reverseKeywords[cssKeywords[key]] = key;
  60480. }
  60481. }
  60482. var convert$1 = conversions$2.exports = {
  60483. rgb: {channels: 3, labels: 'rgb'},
  60484. hsl: {channels: 3, labels: 'hsl'},
  60485. hsv: {channels: 3, labels: 'hsv'},
  60486. hwb: {channels: 3, labels: 'hwb'},
  60487. cmyk: {channels: 4, labels: 'cmyk'},
  60488. xyz: {channels: 3, labels: 'xyz'},
  60489. lab: {channels: 3, labels: 'lab'},
  60490. lch: {channels: 3, labels: 'lch'},
  60491. hex: {channels: 1, labels: ['hex']},
  60492. keyword: {channels: 1, labels: ['keyword']},
  60493. ansi16: {channels: 1, labels: ['ansi16']},
  60494. ansi256: {channels: 1, labels: ['ansi256']},
  60495. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  60496. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  60497. gray: {channels: 1, labels: ['gray']}
  60498. };
  60499. // hide .channels and .labels properties
  60500. for (var model in convert$1) {
  60501. if (convert$1.hasOwnProperty(model)) {
  60502. if (!('channels' in convert$1[model])) {
  60503. throw new Error('missing channels property: ' + model);
  60504. }
  60505. if (!('labels' in convert$1[model])) {
  60506. throw new Error('missing channel labels property: ' + model);
  60507. }
  60508. if (convert$1[model].labels.length !== convert$1[model].channels) {
  60509. throw new Error('channel and label counts mismatch: ' + model);
  60510. }
  60511. var channels = convert$1[model].channels;
  60512. var labels = convert$1[model].labels;
  60513. delete convert$1[model].channels;
  60514. delete convert$1[model].labels;
  60515. Object.defineProperty(convert$1[model], 'channels', {value: channels});
  60516. Object.defineProperty(convert$1[model], 'labels', {value: labels});
  60517. }
  60518. }
  60519. convert$1.rgb.hsl = function (rgb) {
  60520. var r = rgb[0] / 255;
  60521. var g = rgb[1] / 255;
  60522. var b = rgb[2] / 255;
  60523. var min = Math.min(r, g, b);
  60524. var max = Math.max(r, g, b);
  60525. var delta = max - min;
  60526. var h;
  60527. var s;
  60528. var l;
  60529. if (max === min) {
  60530. h = 0;
  60531. } else if (r === max) {
  60532. h = (g - b) / delta;
  60533. } else if (g === max) {
  60534. h = 2 + (b - r) / delta;
  60535. } else if (b === max) {
  60536. h = 4 + (r - g) / delta;
  60537. }
  60538. h = Math.min(h * 60, 360);
  60539. if (h < 0) {
  60540. h += 360;
  60541. }
  60542. l = (min + max) / 2;
  60543. if (max === min) {
  60544. s = 0;
  60545. } else if (l <= 0.5) {
  60546. s = delta / (max + min);
  60547. } else {
  60548. s = delta / (2 - max - min);
  60549. }
  60550. return [h, s * 100, l * 100];
  60551. };
  60552. convert$1.rgb.hsv = function (rgb) {
  60553. var rdif;
  60554. var gdif;
  60555. var bdif;
  60556. var h;
  60557. var s;
  60558. var r = rgb[0] / 255;
  60559. var g = rgb[1] / 255;
  60560. var b = rgb[2] / 255;
  60561. var v = Math.max(r, g, b);
  60562. var diff = v - Math.min(r, g, b);
  60563. var diffc = function (c) {
  60564. return (v - c) / 6 / diff + 1 / 2;
  60565. };
  60566. if (diff === 0) {
  60567. h = s = 0;
  60568. } else {
  60569. s = diff / v;
  60570. rdif = diffc(r);
  60571. gdif = diffc(g);
  60572. bdif = diffc(b);
  60573. if (r === v) {
  60574. h = bdif - gdif;
  60575. } else if (g === v) {
  60576. h = (1 / 3) + rdif - bdif;
  60577. } else if (b === v) {
  60578. h = (2 / 3) + gdif - rdif;
  60579. }
  60580. if (h < 0) {
  60581. h += 1;
  60582. } else if (h > 1) {
  60583. h -= 1;
  60584. }
  60585. }
  60586. return [
  60587. h * 360,
  60588. s * 100,
  60589. v * 100
  60590. ];
  60591. };
  60592. convert$1.rgb.hwb = function (rgb) {
  60593. var r = rgb[0];
  60594. var g = rgb[1];
  60595. var b = rgb[2];
  60596. var h = convert$1.rgb.hsl(rgb)[0];
  60597. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  60598. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  60599. return [h, w * 100, b * 100];
  60600. };
  60601. convert$1.rgb.cmyk = function (rgb) {
  60602. var r = rgb[0] / 255;
  60603. var g = rgb[1] / 255;
  60604. var b = rgb[2] / 255;
  60605. var c;
  60606. var m;
  60607. var y;
  60608. var k;
  60609. k = Math.min(1 - r, 1 - g, 1 - b);
  60610. c = (1 - r - k) / (1 - k) || 0;
  60611. m = (1 - g - k) / (1 - k) || 0;
  60612. y = (1 - b - k) / (1 - k) || 0;
  60613. return [c * 100, m * 100, y * 100, k * 100];
  60614. };
  60615. /**
  60616. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  60617. * */
  60618. function comparativeDistance(x, y) {
  60619. return (
  60620. Math.pow(x[0] - y[0], 2) +
  60621. Math.pow(x[1] - y[1], 2) +
  60622. Math.pow(x[2] - y[2], 2)
  60623. );
  60624. }
  60625. convert$1.rgb.keyword = function (rgb) {
  60626. var reversed = reverseKeywords[rgb];
  60627. if (reversed) {
  60628. return reversed;
  60629. }
  60630. var currentClosestDistance = Infinity;
  60631. var currentClosestKeyword;
  60632. for (var keyword in cssKeywords) {
  60633. if (cssKeywords.hasOwnProperty(keyword)) {
  60634. var value = cssKeywords[keyword];
  60635. // Compute comparative distance
  60636. var distance = comparativeDistance(rgb, value);
  60637. // Check if its less, if so set as closest
  60638. if (distance < currentClosestDistance) {
  60639. currentClosestDistance = distance;
  60640. currentClosestKeyword = keyword;
  60641. }
  60642. }
  60643. }
  60644. return currentClosestKeyword;
  60645. };
  60646. convert$1.keyword.rgb = function (keyword) {
  60647. return cssKeywords[keyword];
  60648. };
  60649. convert$1.rgb.xyz = function (rgb) {
  60650. var r = rgb[0] / 255;
  60651. var g = rgb[1] / 255;
  60652. var b = rgb[2] / 255;
  60653. // assume sRGB
  60654. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  60655. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  60656. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  60657. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  60658. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  60659. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  60660. return [x * 100, y * 100, z * 100];
  60661. };
  60662. convert$1.rgb.lab = function (rgb) {
  60663. var xyz = convert$1.rgb.xyz(rgb);
  60664. var x = xyz[0];
  60665. var y = xyz[1];
  60666. var z = xyz[2];
  60667. var l;
  60668. var a;
  60669. var b;
  60670. x /= 95.047;
  60671. y /= 100;
  60672. z /= 108.883;
  60673. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  60674. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  60675. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  60676. l = (116 * y) - 16;
  60677. a = 500 * (x - y);
  60678. b = 200 * (y - z);
  60679. return [l, a, b];
  60680. };
  60681. convert$1.hsl.rgb = function (hsl) {
  60682. var h = hsl[0] / 360;
  60683. var s = hsl[1] / 100;
  60684. var l = hsl[2] / 100;
  60685. var t1;
  60686. var t2;
  60687. var t3;
  60688. var rgb;
  60689. var val;
  60690. if (s === 0) {
  60691. val = l * 255;
  60692. return [val, val, val];
  60693. }
  60694. if (l < 0.5) {
  60695. t2 = l * (1 + s);
  60696. } else {
  60697. t2 = l + s - l * s;
  60698. }
  60699. t1 = 2 * l - t2;
  60700. rgb = [0, 0, 0];
  60701. for (var i = 0; i < 3; i++) {
  60702. t3 = h + 1 / 3 * -(i - 1);
  60703. if (t3 < 0) {
  60704. t3++;
  60705. }
  60706. if (t3 > 1) {
  60707. t3--;
  60708. }
  60709. if (6 * t3 < 1) {
  60710. val = t1 + (t2 - t1) * 6 * t3;
  60711. } else if (2 * t3 < 1) {
  60712. val = t2;
  60713. } else if (3 * t3 < 2) {
  60714. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  60715. } else {
  60716. val = t1;
  60717. }
  60718. rgb[i] = val * 255;
  60719. }
  60720. return rgb;
  60721. };
  60722. convert$1.hsl.hsv = function (hsl) {
  60723. var h = hsl[0];
  60724. var s = hsl[1] / 100;
  60725. var l = hsl[2] / 100;
  60726. var smin = s;
  60727. var lmin = Math.max(l, 0.01);
  60728. var sv;
  60729. var v;
  60730. l *= 2;
  60731. s *= (l <= 1) ? l : 2 - l;
  60732. smin *= lmin <= 1 ? lmin : 2 - lmin;
  60733. v = (l + s) / 2;
  60734. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  60735. return [h, sv * 100, v * 100];
  60736. };
  60737. convert$1.hsv.rgb = function (hsv) {
  60738. var h = hsv[0] / 60;
  60739. var s = hsv[1] / 100;
  60740. var v = hsv[2] / 100;
  60741. var hi = Math.floor(h) % 6;
  60742. var f = h - Math.floor(h);
  60743. var p = 255 * v * (1 - s);
  60744. var q = 255 * v * (1 - (s * f));
  60745. var t = 255 * v * (1 - (s * (1 - f)));
  60746. v *= 255;
  60747. switch (hi) {
  60748. case 0:
  60749. return [v, t, p];
  60750. case 1:
  60751. return [q, v, p];
  60752. case 2:
  60753. return [p, v, t];
  60754. case 3:
  60755. return [p, q, v];
  60756. case 4:
  60757. return [t, p, v];
  60758. case 5:
  60759. return [v, p, q];
  60760. }
  60761. };
  60762. convert$1.hsv.hsl = function (hsv) {
  60763. var h = hsv[0];
  60764. var s = hsv[1] / 100;
  60765. var v = hsv[2] / 100;
  60766. var vmin = Math.max(v, 0.01);
  60767. var lmin;
  60768. var sl;
  60769. var l;
  60770. l = (2 - s) * v;
  60771. lmin = (2 - s) * vmin;
  60772. sl = s * vmin;
  60773. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  60774. sl = sl || 0;
  60775. l /= 2;
  60776. return [h, sl * 100, l * 100];
  60777. };
  60778. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  60779. convert$1.hwb.rgb = function (hwb) {
  60780. var h = hwb[0] / 360;
  60781. var wh = hwb[1] / 100;
  60782. var bl = hwb[2] / 100;
  60783. var ratio = wh + bl;
  60784. var i;
  60785. var v;
  60786. var f;
  60787. var n;
  60788. // wh + bl cant be > 1
  60789. if (ratio > 1) {
  60790. wh /= ratio;
  60791. bl /= ratio;
  60792. }
  60793. i = Math.floor(6 * h);
  60794. v = 1 - bl;
  60795. f = 6 * h - i;
  60796. if ((i & 0x01) !== 0) {
  60797. f = 1 - f;
  60798. }
  60799. n = wh + f * (v - wh); // linear interpolation
  60800. var r;
  60801. var g;
  60802. var b;
  60803. switch (i) {
  60804. default:
  60805. case 6:
  60806. case 0: r = v; g = n; b = wh; break;
  60807. case 1: r = n; g = v; b = wh; break;
  60808. case 2: r = wh; g = v; b = n; break;
  60809. case 3: r = wh; g = n; b = v; break;
  60810. case 4: r = n; g = wh; b = v; break;
  60811. case 5: r = v; g = wh; b = n; break;
  60812. }
  60813. return [r * 255, g * 255, b * 255];
  60814. };
  60815. convert$1.cmyk.rgb = function (cmyk) {
  60816. var c = cmyk[0] / 100;
  60817. var m = cmyk[1] / 100;
  60818. var y = cmyk[2] / 100;
  60819. var k = cmyk[3] / 100;
  60820. var r;
  60821. var g;
  60822. var b;
  60823. r = 1 - Math.min(1, c * (1 - k) + k);
  60824. g = 1 - Math.min(1, m * (1 - k) + k);
  60825. b = 1 - Math.min(1, y * (1 - k) + k);
  60826. return [r * 255, g * 255, b * 255];
  60827. };
  60828. convert$1.xyz.rgb = function (xyz) {
  60829. var x = xyz[0] / 100;
  60830. var y = xyz[1] / 100;
  60831. var z = xyz[2] / 100;
  60832. var r;
  60833. var g;
  60834. var b;
  60835. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  60836. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  60837. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  60838. // assume sRGB
  60839. r = r > 0.0031308
  60840. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  60841. : r * 12.92;
  60842. g = g > 0.0031308
  60843. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  60844. : g * 12.92;
  60845. b = b > 0.0031308
  60846. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  60847. : b * 12.92;
  60848. r = Math.min(Math.max(0, r), 1);
  60849. g = Math.min(Math.max(0, g), 1);
  60850. b = Math.min(Math.max(0, b), 1);
  60851. return [r * 255, g * 255, b * 255];
  60852. };
  60853. convert$1.xyz.lab = function (xyz) {
  60854. var x = xyz[0];
  60855. var y = xyz[1];
  60856. var z = xyz[2];
  60857. var l;
  60858. var a;
  60859. var b;
  60860. x /= 95.047;
  60861. y /= 100;
  60862. z /= 108.883;
  60863. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  60864. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  60865. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  60866. l = (116 * y) - 16;
  60867. a = 500 * (x - y);
  60868. b = 200 * (y - z);
  60869. return [l, a, b];
  60870. };
  60871. convert$1.lab.xyz = function (lab) {
  60872. var l = lab[0];
  60873. var a = lab[1];
  60874. var b = lab[2];
  60875. var x;
  60876. var y;
  60877. var z;
  60878. y = (l + 16) / 116;
  60879. x = a / 500 + y;
  60880. z = y - b / 200;
  60881. var y2 = Math.pow(y, 3);
  60882. var x2 = Math.pow(x, 3);
  60883. var z2 = Math.pow(z, 3);
  60884. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  60885. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  60886. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  60887. x *= 95.047;
  60888. y *= 100;
  60889. z *= 108.883;
  60890. return [x, y, z];
  60891. };
  60892. convert$1.lab.lch = function (lab) {
  60893. var l = lab[0];
  60894. var a = lab[1];
  60895. var b = lab[2];
  60896. var hr;
  60897. var h;
  60898. var c;
  60899. hr = Math.atan2(b, a);
  60900. h = hr * 360 / 2 / Math.PI;
  60901. if (h < 0) {
  60902. h += 360;
  60903. }
  60904. c = Math.sqrt(a * a + b * b);
  60905. return [l, c, h];
  60906. };
  60907. convert$1.lch.lab = function (lch) {
  60908. var l = lch[0];
  60909. var c = lch[1];
  60910. var h = lch[2];
  60911. var a;
  60912. var b;
  60913. var hr;
  60914. hr = h / 360 * 2 * Math.PI;
  60915. a = c * Math.cos(hr);
  60916. b = c * Math.sin(hr);
  60917. return [l, a, b];
  60918. };
  60919. convert$1.rgb.ansi16 = function (args) {
  60920. var r = args[0];
  60921. var g = args[1];
  60922. var b = args[2];
  60923. var value = 1 in arguments ? arguments[1] : convert$1.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  60924. value = Math.round(value / 50);
  60925. if (value === 0) {
  60926. return 30;
  60927. }
  60928. var ansi = 30
  60929. + ((Math.round(b / 255) << 2)
  60930. | (Math.round(g / 255) << 1)
  60931. | Math.round(r / 255));
  60932. if (value === 2) {
  60933. ansi += 60;
  60934. }
  60935. return ansi;
  60936. };
  60937. convert$1.hsv.ansi16 = function (args) {
  60938. // optimization here; we already know the value and don't need to get
  60939. // it converted for us.
  60940. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
  60941. };
  60942. convert$1.rgb.ansi256 = function (args) {
  60943. var r = args[0];
  60944. var g = args[1];
  60945. var b = args[2];
  60946. // we use the extended greyscale palette here, with the exception of
  60947. // black and white. normal palette only has 4 greyscale shades.
  60948. if (r === g && g === b) {
  60949. if (r < 8) {
  60950. return 16;
  60951. }
  60952. if (r > 248) {
  60953. return 231;
  60954. }
  60955. return Math.round(((r - 8) / 247) * 24) + 232;
  60956. }
  60957. var ansi = 16
  60958. + (36 * Math.round(r / 255 * 5))
  60959. + (6 * Math.round(g / 255 * 5))
  60960. + Math.round(b / 255 * 5);
  60961. return ansi;
  60962. };
  60963. convert$1.ansi16.rgb = function (args) {
  60964. var color = args % 10;
  60965. // handle greyscale
  60966. if (color === 0 || color === 7) {
  60967. if (args > 50) {
  60968. color += 3.5;
  60969. }
  60970. color = color / 10.5 * 255;
  60971. return [color, color, color];
  60972. }
  60973. var mult = (~~(args > 50) + 1) * 0.5;
  60974. var r = ((color & 1) * mult) * 255;
  60975. var g = (((color >> 1) & 1) * mult) * 255;
  60976. var b = (((color >> 2) & 1) * mult) * 255;
  60977. return [r, g, b];
  60978. };
  60979. convert$1.ansi256.rgb = function (args) {
  60980. // handle greyscale
  60981. if (args >= 232) {
  60982. var c = (args - 232) * 10 + 8;
  60983. return [c, c, c];
  60984. }
  60985. args -= 16;
  60986. var rem;
  60987. var r = Math.floor(args / 36) / 5 * 255;
  60988. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  60989. var b = (rem % 6) / 5 * 255;
  60990. return [r, g, b];
  60991. };
  60992. convert$1.rgb.hex = function (args) {
  60993. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  60994. + ((Math.round(args[1]) & 0xFF) << 8)
  60995. + (Math.round(args[2]) & 0xFF);
  60996. var string = integer.toString(16).toUpperCase();
  60997. return '000000'.substring(string.length) + string;
  60998. };
  60999. convert$1.hex.rgb = function (args) {
  61000. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  61001. if (!match) {
  61002. return [0, 0, 0];
  61003. }
  61004. var colorString = match[0];
  61005. if (match[0].length === 3) {
  61006. colorString = colorString.split('').map(function (char) {
  61007. return char + char;
  61008. }).join('');
  61009. }
  61010. var integer = parseInt(colorString, 16);
  61011. var r = (integer >> 16) & 0xFF;
  61012. var g = (integer >> 8) & 0xFF;
  61013. var b = integer & 0xFF;
  61014. return [r, g, b];
  61015. };
  61016. convert$1.rgb.hcg = function (rgb) {
  61017. var r = rgb[0] / 255;
  61018. var g = rgb[1] / 255;
  61019. var b = rgb[2] / 255;
  61020. var max = Math.max(Math.max(r, g), b);
  61021. var min = Math.min(Math.min(r, g), b);
  61022. var chroma = (max - min);
  61023. var grayscale;
  61024. var hue;
  61025. if (chroma < 1) {
  61026. grayscale = min / (1 - chroma);
  61027. } else {
  61028. grayscale = 0;
  61029. }
  61030. if (chroma <= 0) {
  61031. hue = 0;
  61032. } else
  61033. if (max === r) {
  61034. hue = ((g - b) / chroma) % 6;
  61035. } else
  61036. if (max === g) {
  61037. hue = 2 + (b - r) / chroma;
  61038. } else {
  61039. hue = 4 + (r - g) / chroma + 4;
  61040. }
  61041. hue /= 6;
  61042. hue %= 1;
  61043. return [hue * 360, chroma * 100, grayscale * 100];
  61044. };
  61045. convert$1.hsl.hcg = function (hsl) {
  61046. var s = hsl[1] / 100;
  61047. var l = hsl[2] / 100;
  61048. var c = 1;
  61049. var f = 0;
  61050. if (l < 0.5) {
  61051. c = 2.0 * s * l;
  61052. } else {
  61053. c = 2.0 * s * (1.0 - l);
  61054. }
  61055. if (c < 1.0) {
  61056. f = (l - 0.5 * c) / (1.0 - c);
  61057. }
  61058. return [hsl[0], c * 100, f * 100];
  61059. };
  61060. convert$1.hsv.hcg = function (hsv) {
  61061. var s = hsv[1] / 100;
  61062. var v = hsv[2] / 100;
  61063. var c = s * v;
  61064. var f = 0;
  61065. if (c < 1.0) {
  61066. f = (v - c) / (1 - c);
  61067. }
  61068. return [hsv[0], c * 100, f * 100];
  61069. };
  61070. convert$1.hcg.rgb = function (hcg) {
  61071. var h = hcg[0] / 360;
  61072. var c = hcg[1] / 100;
  61073. var g = hcg[2] / 100;
  61074. if (c === 0.0) {
  61075. return [g * 255, g * 255, g * 255];
  61076. }
  61077. var pure = [0, 0, 0];
  61078. var hi = (h % 1) * 6;
  61079. var v = hi % 1;
  61080. var w = 1 - v;
  61081. var mg = 0;
  61082. switch (Math.floor(hi)) {
  61083. case 0:
  61084. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  61085. case 1:
  61086. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  61087. case 2:
  61088. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  61089. case 3:
  61090. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  61091. case 4:
  61092. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  61093. default:
  61094. pure[0] = 1; pure[1] = 0; pure[2] = w;
  61095. }
  61096. mg = (1.0 - c) * g;
  61097. return [
  61098. (c * pure[0] + mg) * 255,
  61099. (c * pure[1] + mg) * 255,
  61100. (c * pure[2] + mg) * 255
  61101. ];
  61102. };
  61103. convert$1.hcg.hsv = function (hcg) {
  61104. var c = hcg[1] / 100;
  61105. var g = hcg[2] / 100;
  61106. var v = c + g * (1.0 - c);
  61107. var f = 0;
  61108. if (v > 0.0) {
  61109. f = c / v;
  61110. }
  61111. return [hcg[0], f * 100, v * 100];
  61112. };
  61113. convert$1.hcg.hsl = function (hcg) {
  61114. var c = hcg[1] / 100;
  61115. var g = hcg[2] / 100;
  61116. var l = g * (1.0 - c) + 0.5 * c;
  61117. var s = 0;
  61118. if (l > 0.0 && l < 0.5) {
  61119. s = c / (2 * l);
  61120. } else
  61121. if (l >= 0.5 && l < 1.0) {
  61122. s = c / (2 * (1 - l));
  61123. }
  61124. return [hcg[0], s * 100, l * 100];
  61125. };
  61126. convert$1.hcg.hwb = function (hcg) {
  61127. var c = hcg[1] / 100;
  61128. var g = hcg[2] / 100;
  61129. var v = c + g * (1.0 - c);
  61130. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  61131. };
  61132. convert$1.hwb.hcg = function (hwb) {
  61133. var w = hwb[1] / 100;
  61134. var b = hwb[2] / 100;
  61135. var v = 1 - b;
  61136. var c = v - w;
  61137. var g = 0;
  61138. if (c < 1) {
  61139. g = (v - c) / (1 - c);
  61140. }
  61141. return [hwb[0], c * 100, g * 100];
  61142. };
  61143. convert$1.apple.rgb = function (apple) {
  61144. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  61145. };
  61146. convert$1.rgb.apple = function (rgb) {
  61147. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  61148. };
  61149. convert$1.gray.rgb = function (args) {
  61150. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  61151. };
  61152. convert$1.gray.hsl = convert$1.gray.hsv = function (args) {
  61153. return [0, 0, args[0]];
  61154. };
  61155. convert$1.gray.hwb = function (gray) {
  61156. return [0, 100, gray[0]];
  61157. };
  61158. convert$1.gray.cmyk = function (gray) {
  61159. return [0, 0, 0, gray[0]];
  61160. };
  61161. convert$1.gray.lab = function (gray) {
  61162. return [gray[0], 0, 0];
  61163. };
  61164. convert$1.gray.hex = function (gray) {
  61165. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  61166. var integer = (val << 16) + (val << 8) + val;
  61167. var string = integer.toString(16).toUpperCase();
  61168. return '000000'.substring(string.length) + string;
  61169. };
  61170. convert$1.rgb.gray = function (rgb) {
  61171. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  61172. return [val / 255 * 100];
  61173. };
  61174. var conversions$1 = conversions$2.exports;
  61175. /*
  61176. this function routes a model to all other models.
  61177. all functions that are routed have a property `.conversion` attached
  61178. to the returned synthetic function. This property is an array
  61179. of strings, each with the steps in between the 'from' and 'to'
  61180. color models (inclusive).
  61181. conversions that are not possible simply are not included.
  61182. */
  61183. function buildGraph() {
  61184. var graph = {};
  61185. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  61186. var models = Object.keys(conversions$1);
  61187. for (var len = models.length, i = 0; i < len; i++) {
  61188. graph[models[i]] = {
  61189. // http://jsperf.com/1-vs-infinity
  61190. // micro-opt, but this is simple.
  61191. distance: -1,
  61192. parent: null
  61193. };
  61194. }
  61195. return graph;
  61196. }
  61197. // https://en.wikipedia.org/wiki/Breadth-first_search
  61198. function deriveBFS(fromModel) {
  61199. var graph = buildGraph();
  61200. var queue = [fromModel]; // unshift -> queue -> pop
  61201. graph[fromModel].distance = 0;
  61202. while (queue.length) {
  61203. var current = queue.pop();
  61204. var adjacents = Object.keys(conversions$1[current]);
  61205. for (var len = adjacents.length, i = 0; i < len; i++) {
  61206. var adjacent = adjacents[i];
  61207. var node = graph[adjacent];
  61208. if (node.distance === -1) {
  61209. node.distance = graph[current].distance + 1;
  61210. node.parent = current;
  61211. queue.unshift(adjacent);
  61212. }
  61213. }
  61214. }
  61215. return graph;
  61216. }
  61217. function link(from, to) {
  61218. return function (args) {
  61219. return to(from(args));
  61220. };
  61221. }
  61222. function wrapConversion(toModel, graph) {
  61223. var path = [graph[toModel].parent, toModel];
  61224. var fn = conversions$1[graph[toModel].parent][toModel];
  61225. var cur = graph[toModel].parent;
  61226. while (graph[cur].parent) {
  61227. path.unshift(graph[cur].parent);
  61228. fn = link(conversions$1[graph[cur].parent][cur], fn);
  61229. cur = graph[cur].parent;
  61230. }
  61231. fn.conversion = path;
  61232. return fn;
  61233. }
  61234. var route$1 = function (fromModel) {
  61235. var graph = deriveBFS(fromModel);
  61236. var conversion = {};
  61237. var models = Object.keys(graph);
  61238. for (var len = models.length, i = 0; i < len; i++) {
  61239. var toModel = models[i];
  61240. var node = graph[toModel];
  61241. if (node.parent === null) {
  61242. // no possible conversion, or this node is the source model.
  61243. continue;
  61244. }
  61245. conversion[toModel] = wrapConversion(toModel, graph);
  61246. }
  61247. return conversion;
  61248. };
  61249. var conversions = conversions$2.exports;
  61250. var route = route$1;
  61251. var convert = {};
  61252. var models = Object.keys(conversions);
  61253. function wrapRaw(fn) {
  61254. var wrappedFn = function (args) {
  61255. if (args === undefined || args === null) {
  61256. return args;
  61257. }
  61258. if (arguments.length > 1) {
  61259. args = Array.prototype.slice.call(arguments);
  61260. }
  61261. return fn(args);
  61262. };
  61263. // preserve .conversion property if there is one
  61264. if ('conversion' in fn) {
  61265. wrappedFn.conversion = fn.conversion;
  61266. }
  61267. return wrappedFn;
  61268. }
  61269. function wrapRounded(fn) {
  61270. var wrappedFn = function (args) {
  61271. if (args === undefined || args === null) {
  61272. return args;
  61273. }
  61274. if (arguments.length > 1) {
  61275. args = Array.prototype.slice.call(arguments);
  61276. }
  61277. var result = fn(args);
  61278. // we're assuming the result is an array here.
  61279. // see notice in conversions.js; don't use box types
  61280. // in conversion functions.
  61281. if (typeof result === 'object') {
  61282. for (var len = result.length, i = 0; i < len; i++) {
  61283. result[i] = Math.round(result[i]);
  61284. }
  61285. }
  61286. return result;
  61287. };
  61288. // preserve .conversion property if there is one
  61289. if ('conversion' in fn) {
  61290. wrappedFn.conversion = fn.conversion;
  61291. }
  61292. return wrappedFn;
  61293. }
  61294. models.forEach(function (fromModel) {
  61295. convert[fromModel] = {};
  61296. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  61297. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  61298. var routes = route(fromModel);
  61299. var routeModels = Object.keys(routes);
  61300. routeModels.forEach(function (toModel) {
  61301. var fn = routes[toModel];
  61302. convert[fromModel][toModel] = wrapRounded(fn);
  61303. convert[fromModel][toModel].raw = wrapRaw(fn);
  61304. });
  61305. });
  61306. var colorConvert = convert;
  61307. (function (module) {
  61308. const colorConvert$1 = colorConvert;
  61309. const wrapAnsi16 = (fn, offset) => function () {
  61310. const code = fn.apply(colorConvert$1, arguments);
  61311. return `\u001B[${code + offset}m`;
  61312. };
  61313. const wrapAnsi256 = (fn, offset) => function () {
  61314. const code = fn.apply(colorConvert$1, arguments);
  61315. return `\u001B[${38 + offset};5;${code}m`;
  61316. };
  61317. const wrapAnsi16m = (fn, offset) => function () {
  61318. const rgb = fn.apply(colorConvert$1, arguments);
  61319. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  61320. };
  61321. function assembleStyles() {
  61322. const codes = new Map();
  61323. const styles = {
  61324. modifier: {
  61325. reset: [0, 0],
  61326. // 21 isn't widely supported and 22 does the same thing
  61327. bold: [1, 22],
  61328. dim: [2, 22],
  61329. italic: [3, 23],
  61330. underline: [4, 24],
  61331. inverse: [7, 27],
  61332. hidden: [8, 28],
  61333. strikethrough: [9, 29]
  61334. },
  61335. color: {
  61336. black: [30, 39],
  61337. red: [31, 39],
  61338. green: [32, 39],
  61339. yellow: [33, 39],
  61340. blue: [34, 39],
  61341. magenta: [35, 39],
  61342. cyan: [36, 39],
  61343. white: [37, 39],
  61344. gray: [90, 39],
  61345. // Bright color
  61346. redBright: [91, 39],
  61347. greenBright: [92, 39],
  61348. yellowBright: [93, 39],
  61349. blueBright: [94, 39],
  61350. magentaBright: [95, 39],
  61351. cyanBright: [96, 39],
  61352. whiteBright: [97, 39]
  61353. },
  61354. bgColor: {
  61355. bgBlack: [40, 49],
  61356. bgRed: [41, 49],
  61357. bgGreen: [42, 49],
  61358. bgYellow: [43, 49],
  61359. bgBlue: [44, 49],
  61360. bgMagenta: [45, 49],
  61361. bgCyan: [46, 49],
  61362. bgWhite: [47, 49],
  61363. // Bright color
  61364. bgBlackBright: [100, 49],
  61365. bgRedBright: [101, 49],
  61366. bgGreenBright: [102, 49],
  61367. bgYellowBright: [103, 49],
  61368. bgBlueBright: [104, 49],
  61369. bgMagentaBright: [105, 49],
  61370. bgCyanBright: [106, 49],
  61371. bgWhiteBright: [107, 49]
  61372. }
  61373. };
  61374. // Fix humans
  61375. styles.color.grey = styles.color.gray;
  61376. for (const groupName of Object.keys(styles)) {
  61377. const group = styles[groupName];
  61378. for (const styleName of Object.keys(group)) {
  61379. const style = group[styleName];
  61380. styles[styleName] = {
  61381. open: `\u001B[${style[0]}m`,
  61382. close: `\u001B[${style[1]}m`
  61383. };
  61384. group[styleName] = styles[styleName];
  61385. codes.set(style[0], style[1]);
  61386. }
  61387. Object.defineProperty(styles, groupName, {
  61388. value: group,
  61389. enumerable: false
  61390. });
  61391. Object.defineProperty(styles, 'codes', {
  61392. value: codes,
  61393. enumerable: false
  61394. });
  61395. }
  61396. const ansi2ansi = n => n;
  61397. const rgb2rgb = (r, g, b) => [r, g, b];
  61398. styles.color.close = '\u001B[39m';
  61399. styles.bgColor.close = '\u001B[49m';
  61400. styles.color.ansi = {
  61401. ansi: wrapAnsi16(ansi2ansi, 0)
  61402. };
  61403. styles.color.ansi256 = {
  61404. ansi256: wrapAnsi256(ansi2ansi, 0)
  61405. };
  61406. styles.color.ansi16m = {
  61407. rgb: wrapAnsi16m(rgb2rgb, 0)
  61408. };
  61409. styles.bgColor.ansi = {
  61410. ansi: wrapAnsi16(ansi2ansi, 10)
  61411. };
  61412. styles.bgColor.ansi256 = {
  61413. ansi256: wrapAnsi256(ansi2ansi, 10)
  61414. };
  61415. styles.bgColor.ansi16m = {
  61416. rgb: wrapAnsi16m(rgb2rgb, 10)
  61417. };
  61418. for (let key of Object.keys(colorConvert$1)) {
  61419. if (typeof colorConvert$1[key] !== 'object') {
  61420. continue;
  61421. }
  61422. const suite = colorConvert$1[key];
  61423. if (key === 'ansi16') {
  61424. key = 'ansi';
  61425. }
  61426. if ('ansi16' in suite) {
  61427. styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
  61428. styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
  61429. }
  61430. if ('ansi256' in suite) {
  61431. styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
  61432. styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
  61433. }
  61434. if ('rgb' in suite) {
  61435. styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
  61436. styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
  61437. }
  61438. }
  61439. return styles;
  61440. }
  61441. // Make the export immutable
  61442. Object.defineProperty(module, 'exports', {
  61443. enumerable: true,
  61444. get: assembleStyles
  61445. });
  61446. }(ansiStyles));
  61447. var hasFlag$1 = (flag, argv) => {
  61448. argv = argv || process.argv;
  61449. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  61450. const pos = argv.indexOf(prefix + flag);
  61451. const terminatorPos = argv.indexOf('--');
  61452. return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
  61453. };
  61454. const os$2 = require$$0__default$1;
  61455. const hasFlag = hasFlag$1;
  61456. const env = process.env;
  61457. let forceColor;
  61458. if (hasFlag('no-color') ||
  61459. hasFlag('no-colors') ||
  61460. hasFlag('color=false')) {
  61461. forceColor = false;
  61462. } else if (hasFlag('color') ||
  61463. hasFlag('colors') ||
  61464. hasFlag('color=true') ||
  61465. hasFlag('color=always')) {
  61466. forceColor = true;
  61467. }
  61468. if ('FORCE_COLOR' in env) {
  61469. forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
  61470. }
  61471. function translateLevel(level) {
  61472. if (level === 0) {
  61473. return false;
  61474. }
  61475. return {
  61476. level,
  61477. hasBasic: true,
  61478. has256: level >= 2,
  61479. has16m: level >= 3
  61480. };
  61481. }
  61482. function supportsColor(stream) {
  61483. if (forceColor === false) {
  61484. return 0;
  61485. }
  61486. if (hasFlag('color=16m') ||
  61487. hasFlag('color=full') ||
  61488. hasFlag('color=truecolor')) {
  61489. return 3;
  61490. }
  61491. if (hasFlag('color=256')) {
  61492. return 2;
  61493. }
  61494. if (stream && !stream.isTTY && forceColor !== true) {
  61495. return 0;
  61496. }
  61497. const min = forceColor ? 1 : 0;
  61498. if (process.platform === 'win32') {
  61499. // Node.js 7.5.0 is the first version of Node.js to include a patch to
  61500. // libuv that enables 256 color output on Windows. Anything earlier and it
  61501. // won't work. However, here we target Node.js 8 at minimum as it is an LTS
  61502. // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
  61503. // release that supports 256 colors. Windows 10 build 14931 is the first release
  61504. // that supports 16m/TrueColor.
  61505. const osRelease = os$2.release().split('.');
  61506. if (
  61507. Number(process.versions.node.split('.')[0]) >= 8 &&
  61508. Number(osRelease[0]) >= 10 &&
  61509. Number(osRelease[2]) >= 10586
  61510. ) {
  61511. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  61512. }
  61513. return 1;
  61514. }
  61515. if ('CI' in env) {
  61516. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
  61517. return 1;
  61518. }
  61519. return min;
  61520. }
  61521. if ('TEAMCITY_VERSION' in env) {
  61522. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  61523. }
  61524. if (env.COLORTERM === 'truecolor') {
  61525. return 3;
  61526. }
  61527. if ('TERM_PROGRAM' in env) {
  61528. const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  61529. switch (env.TERM_PROGRAM) {
  61530. case 'iTerm.app':
  61531. return version >= 3 ? 3 : 2;
  61532. case 'Apple_Terminal':
  61533. return 2;
  61534. // No default
  61535. }
  61536. }
  61537. if (/-256(color)?$/i.test(env.TERM)) {
  61538. return 2;
  61539. }
  61540. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  61541. return 1;
  61542. }
  61543. if ('COLORTERM' in env) {
  61544. return 1;
  61545. }
  61546. if (env.TERM === 'dumb') {
  61547. return min;
  61548. }
  61549. return min;
  61550. }
  61551. function getSupportLevel(stream) {
  61552. const level = supportsColor(stream);
  61553. return translateLevel(level);
  61554. }
  61555. var supportsColor_1 = {
  61556. supportsColor: getSupportLevel,
  61557. stdout: getSupportLevel(process.stdout),
  61558. stderr: getSupportLevel(process.stderr)
  61559. };
  61560. const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
  61561. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  61562. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  61563. const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
  61564. const ESCAPES = new Map([
  61565. ['n', '\n'],
  61566. ['r', '\r'],
  61567. ['t', '\t'],
  61568. ['b', '\b'],
  61569. ['f', '\f'],
  61570. ['v', '\v'],
  61571. ['0', '\0'],
  61572. ['\\', '\\'],
  61573. ['e', '\u001B'],
  61574. ['a', '\u0007']
  61575. ]);
  61576. function unescape$1(c) {
  61577. if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
  61578. return String.fromCharCode(parseInt(c.slice(1), 16));
  61579. }
  61580. return ESCAPES.get(c) || c;
  61581. }
  61582. function parseArguments(name, args) {
  61583. const results = [];
  61584. const chunks = args.trim().split(/\s*,\s*/g);
  61585. let matches;
  61586. for (const chunk of chunks) {
  61587. if (!isNaN(chunk)) {
  61588. results.push(Number(chunk));
  61589. } else if ((matches = chunk.match(STRING_REGEX))) {
  61590. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape$1(escape) : chr));
  61591. } else {
  61592. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  61593. }
  61594. }
  61595. return results;
  61596. }
  61597. function parseStyle(style) {
  61598. STYLE_REGEX.lastIndex = 0;
  61599. const results = [];
  61600. let matches;
  61601. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  61602. const name = matches[1];
  61603. if (matches[2]) {
  61604. const args = parseArguments(name, matches[2]);
  61605. results.push([name].concat(args));
  61606. } else {
  61607. results.push([name]);
  61608. }
  61609. }
  61610. return results;
  61611. }
  61612. function buildStyle(chalk, styles) {
  61613. const enabled = {};
  61614. for (const layer of styles) {
  61615. for (const style of layer.styles) {
  61616. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  61617. }
  61618. }
  61619. let current = chalk;
  61620. for (const styleName of Object.keys(enabled)) {
  61621. if (Array.isArray(enabled[styleName])) {
  61622. if (!(styleName in current)) {
  61623. throw new Error(`Unknown Chalk style: ${styleName}`);
  61624. }
  61625. if (enabled[styleName].length > 0) {
  61626. current = current[styleName].apply(current, enabled[styleName]);
  61627. } else {
  61628. current = current[styleName];
  61629. }
  61630. }
  61631. }
  61632. return current;
  61633. }
  61634. var templates = (chalk, tmp) => {
  61635. const styles = [];
  61636. const chunks = [];
  61637. let chunk = [];
  61638. // eslint-disable-next-line max-params
  61639. tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
  61640. if (escapeChar) {
  61641. chunk.push(unescape$1(escapeChar));
  61642. } else if (style) {
  61643. const str = chunk.join('');
  61644. chunk = [];
  61645. chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
  61646. styles.push({inverse, styles: parseStyle(style)});
  61647. } else if (close) {
  61648. if (styles.length === 0) {
  61649. throw new Error('Found extraneous } in Chalk template literal');
  61650. }
  61651. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  61652. chunk = [];
  61653. styles.pop();
  61654. } else {
  61655. chunk.push(chr);
  61656. }
  61657. });
  61658. chunks.push(chunk.join(''));
  61659. if (styles.length > 0) {
  61660. const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  61661. throw new Error(errMsg);
  61662. }
  61663. return chunks.join('');
  61664. };
  61665. (function (module) {
  61666. const escapeStringRegexp$1 = escapeStringRegexp;
  61667. const ansiStyles$1 = ansiStyles.exports;
  61668. const stdoutColor = supportsColor_1.stdout;
  61669. const template = templates;
  61670. const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
  61671. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  61672. const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
  61673. // `color-convert` models to exclude from the Chalk API due to conflicts and such
  61674. const skipModels = new Set(['gray']);
  61675. const styles = Object.create(null);
  61676. function applyOptions(obj, options) {
  61677. options = options || {};
  61678. // Detect level if not set manually
  61679. const scLevel = stdoutColor ? stdoutColor.level : 0;
  61680. obj.level = options.level === undefined ? scLevel : options.level;
  61681. obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
  61682. }
  61683. function Chalk(options) {
  61684. // We check for this.template here since calling `chalk.constructor()`
  61685. // by itself will have a `this` of a previously constructed chalk object
  61686. if (!this || !(this instanceof Chalk) || this.template) {
  61687. const chalk = {};
  61688. applyOptions(chalk, options);
  61689. chalk.template = function () {
  61690. const args = [].slice.call(arguments);
  61691. return chalkTag.apply(null, [chalk.template].concat(args));
  61692. };
  61693. Object.setPrototypeOf(chalk, Chalk.prototype);
  61694. Object.setPrototypeOf(chalk.template, chalk);
  61695. chalk.template.constructor = Chalk;
  61696. return chalk.template;
  61697. }
  61698. applyOptions(this, options);
  61699. }
  61700. // Use bright blue on Windows as the normal blue color is illegible
  61701. if (isSimpleWindowsTerm) {
  61702. ansiStyles$1.blue.open = '\u001B[94m';
  61703. }
  61704. for (const key of Object.keys(ansiStyles$1)) {
  61705. ansiStyles$1[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1[key].close), 'g');
  61706. styles[key] = {
  61707. get() {
  61708. const codes = ansiStyles$1[key];
  61709. return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
  61710. }
  61711. };
  61712. }
  61713. styles.visible = {
  61714. get() {
  61715. return build.call(this, this._styles || [], true, 'visible');
  61716. }
  61717. };
  61718. ansiStyles$1.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.color.close), 'g');
  61719. for (const model of Object.keys(ansiStyles$1.color.ansi)) {
  61720. if (skipModels.has(model)) {
  61721. continue;
  61722. }
  61723. styles[model] = {
  61724. get() {
  61725. const level = this.level;
  61726. return function () {
  61727. const open = ansiStyles$1.color[levelMapping[level]][model].apply(null, arguments);
  61728. const codes = {
  61729. open,
  61730. close: ansiStyles$1.color.close,
  61731. closeRe: ansiStyles$1.color.closeRe
  61732. };
  61733. return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
  61734. };
  61735. }
  61736. };
  61737. }
  61738. ansiStyles$1.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$1.bgColor.close), 'g');
  61739. for (const model of Object.keys(ansiStyles$1.bgColor.ansi)) {
  61740. if (skipModels.has(model)) {
  61741. continue;
  61742. }
  61743. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  61744. styles[bgModel] = {
  61745. get() {
  61746. const level = this.level;
  61747. return function () {
  61748. const open = ansiStyles$1.bgColor[levelMapping[level]][model].apply(null, arguments);
  61749. const codes = {
  61750. open,
  61751. close: ansiStyles$1.bgColor.close,
  61752. closeRe: ansiStyles$1.bgColor.closeRe
  61753. };
  61754. return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
  61755. };
  61756. }
  61757. };
  61758. }
  61759. const proto = Object.defineProperties(() => {}, styles);
  61760. function build(_styles, _empty, key) {
  61761. const builder = function () {
  61762. return applyStyle.apply(builder, arguments);
  61763. };
  61764. builder._styles = _styles;
  61765. builder._empty = _empty;
  61766. const self = this;
  61767. Object.defineProperty(builder, 'level', {
  61768. enumerable: true,
  61769. get() {
  61770. return self.level;
  61771. },
  61772. set(level) {
  61773. self.level = level;
  61774. }
  61775. });
  61776. Object.defineProperty(builder, 'enabled', {
  61777. enumerable: true,
  61778. get() {
  61779. return self.enabled;
  61780. },
  61781. set(enabled) {
  61782. self.enabled = enabled;
  61783. }
  61784. });
  61785. // See below for fix regarding invisible grey/dim combination on Windows
  61786. builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
  61787. // `__proto__` is used because we must return a function, but there is
  61788. // no way to create a function with a different prototype
  61789. builder.__proto__ = proto; // eslint-disable-line no-proto
  61790. return builder;
  61791. }
  61792. function applyStyle() {
  61793. // Support varags, but simply cast to string in case there's only one arg
  61794. const args = arguments;
  61795. const argsLen = args.length;
  61796. let str = String(arguments[0]);
  61797. if (argsLen === 0) {
  61798. return '';
  61799. }
  61800. if (argsLen > 1) {
  61801. // Don't slice `arguments`, it prevents V8 optimizations
  61802. for (let a = 1; a < argsLen; a++) {
  61803. str += ' ' + args[a];
  61804. }
  61805. }
  61806. if (!this.enabled || this.level <= 0 || !str) {
  61807. return this._empty ? '' : str;
  61808. }
  61809. // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
  61810. // see https://github.com/chalk/chalk/issues/58
  61811. // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
  61812. const originalDim = ansiStyles$1.dim.open;
  61813. if (isSimpleWindowsTerm && this.hasGrey) {
  61814. ansiStyles$1.dim.open = '';
  61815. }
  61816. for (const code of this._styles.slice().reverse()) {
  61817. // Replace any instances already present with a re-opening code
  61818. // otherwise only the part of the string until said closing code
  61819. // will be colored, and the rest will simply be 'plain'.
  61820. str = code.open + str.replace(code.closeRe, code.open) + code.close;
  61821. // Close the styling before a linebreak and reopen
  61822. // after next line to fix a bleed issue on macOS
  61823. // https://github.com/chalk/chalk/pull/92
  61824. str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
  61825. }
  61826. // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
  61827. ansiStyles$1.dim.open = originalDim;
  61828. return str;
  61829. }
  61830. function chalkTag(chalk, strings) {
  61831. if (!Array.isArray(strings)) {
  61832. // If chalk() was called by itself or with a string,
  61833. // return the string itself as a string.
  61834. return [].slice.call(arguments, 1).join(' ');
  61835. }
  61836. const args = [].slice.call(arguments, 2);
  61837. const parts = [strings.raw[0]];
  61838. for (let i = 1; i < strings.length; i++) {
  61839. parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
  61840. parts.push(String(strings.raw[i]));
  61841. }
  61842. return template(chalk, parts.join(''));
  61843. }
  61844. Object.defineProperties(Chalk.prototype, styles);
  61845. module.exports = Chalk(); // eslint-disable-line new-cap
  61846. module.exports.supportsColor = stdoutColor;
  61847. module.exports.default = module.exports; // For TypeScript
  61848. }(chalk$1));
  61849. var shellQuote$1 = {};
  61850. shellQuote$1.quote = function (xs) {
  61851. return xs.map(function (s) {
  61852. if (s && typeof s === 'object') {
  61853. return s.op.replace(/(.)/g, '\\$1');
  61854. }
  61855. else if (/["\s]/.test(s) && !/'/.test(s)) {
  61856. return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
  61857. }
  61858. else if (/["'\s]/.test(s)) {
  61859. return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"';
  61860. }
  61861. else {
  61862. return String(s).replace(/([A-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2');
  61863. }
  61864. }).join(' ');
  61865. };
  61866. // '<(' is process substitution operator and
  61867. // can be parsed the same as control operator
  61868. var CONTROL = '(?:' + [
  61869. '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]'
  61870. ].join('|') + ')';
  61871. var META = '|&;()<> \\t';
  61872. var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+';
  61873. var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
  61874. var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
  61875. var TOKEN = '';
  61876. for (var i = 0; i < 4; i++) {
  61877. TOKEN += (Math.pow(16,8)*Math.random()).toString(16);
  61878. }
  61879. shellQuote$1.parse = function (s, env, opts) {
  61880. var mapped = parse$1(s, env, opts);
  61881. if (typeof env !== 'function') return mapped;
  61882. return mapped.reduce(function (acc, s) {
  61883. if (typeof s === 'object') return acc.concat(s);
  61884. var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
  61885. if (xs.length === 1) return acc.concat(xs[0]);
  61886. return acc.concat(xs.filter(Boolean).map(function (x) {
  61887. if (RegExp('^' + TOKEN).test(x)) {
  61888. return JSON.parse(x.split(TOKEN)[1]);
  61889. }
  61890. else return x;
  61891. }));
  61892. }, []);
  61893. };
  61894. function parse$1 (s, env, opts) {
  61895. var chunker = new RegExp([
  61896. '(' + CONTROL + ')', // control chars
  61897. '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'
  61898. ].join('|'), 'g');
  61899. var match = s.match(chunker).filter(Boolean);
  61900. var commented = false;
  61901. if (!match) return [];
  61902. if (!env) env = {};
  61903. if (!opts) opts = {};
  61904. return match.map(function (s, j) {
  61905. if (commented) {
  61906. return;
  61907. }
  61908. if (RegExp('^' + CONTROL + '$').test(s)) {
  61909. return { op: s };
  61910. }
  61911. // Hand-written scanner/parser for Bash quoting rules:
  61912. //
  61913. // 1. inside single quotes, all characters are printed literally.
  61914. // 2. inside double quotes, all characters are printed literally
  61915. // except variables prefixed by '$' and backslashes followed by
  61916. // either a double quote or another backslash.
  61917. // 3. outside of any quotes, backslashes are treated as escape
  61918. // characters and not printed (unless they are themselves escaped)
  61919. // 4. quote context can switch mid-token if there is no whitespace
  61920. // between the two quote contexts (e.g. all'one'"token" parses as
  61921. // "allonetoken")
  61922. var SQ = "'";
  61923. var DQ = '"';
  61924. var DS = '$';
  61925. var BS = opts.escape || '\\';
  61926. var quote = false;
  61927. var esc = false;
  61928. var out = '';
  61929. var isGlob = false;
  61930. for (var i = 0, len = s.length; i < len; i++) {
  61931. var c = s.charAt(i);
  61932. isGlob = isGlob || (!quote && (c === '*' || c === '?'));
  61933. if (esc) {
  61934. out += c;
  61935. esc = false;
  61936. }
  61937. else if (quote) {
  61938. if (c === quote) {
  61939. quote = false;
  61940. }
  61941. else if (quote == SQ) {
  61942. out += c;
  61943. }
  61944. else { // Double quote
  61945. if (c === BS) {
  61946. i += 1;
  61947. c = s.charAt(i);
  61948. if (c === DQ || c === BS || c === DS) {
  61949. out += c;
  61950. } else {
  61951. out += BS + c;
  61952. }
  61953. }
  61954. else if (c === DS) {
  61955. out += parseEnvVar();
  61956. }
  61957. else {
  61958. out += c;
  61959. }
  61960. }
  61961. }
  61962. else if (c === DQ || c === SQ) {
  61963. quote = c;
  61964. }
  61965. else if (RegExp('^' + CONTROL + '$').test(c)) {
  61966. return { op: s };
  61967. }
  61968. else if (RegExp('^#$').test(c)) {
  61969. commented = true;
  61970. if (out.length){
  61971. return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
  61972. }
  61973. return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
  61974. }
  61975. else if (c === BS) {
  61976. esc = true;
  61977. }
  61978. else if (c === DS) {
  61979. out += parseEnvVar();
  61980. }
  61981. else out += c;
  61982. }
  61983. if (isGlob) return {op: 'glob', pattern: out};
  61984. return out;
  61985. function parseEnvVar() {
  61986. i += 1;
  61987. var varend, varname;
  61988. //debugger
  61989. if (s.charAt(i) === '{') {
  61990. i += 1;
  61991. if (s.charAt(i) === '}') {
  61992. throw new Error("Bad substitution: " + s.substr(i - 2, 3));
  61993. }
  61994. varend = s.indexOf('}', i);
  61995. if (varend < 0) {
  61996. throw new Error("Bad substitution: " + s.substr(i));
  61997. }
  61998. varname = s.substr(i, varend - i);
  61999. i = varend;
  62000. }
  62001. else if (/[*@#?$!_\-]/.test(s.charAt(i))) {
  62002. varname = s.charAt(i);
  62003. i += 1;
  62004. }
  62005. else {
  62006. varend = s.substr(i).match(/[^\w\d_]/);
  62007. if (!varend) {
  62008. varname = s.substr(i);
  62009. i = s.length;
  62010. } else {
  62011. varname = s.substr(i, varend.index);
  62012. i += varend.index - 1;
  62013. }
  62014. }
  62015. return getVar(null, '', varname);
  62016. }
  62017. })
  62018. // finalize parsed aruments
  62019. .reduce(function(prev, arg){
  62020. if (arg === undefined){
  62021. return prev;
  62022. }
  62023. return prev.concat(arg);
  62024. },[]);
  62025. function getVar (_, pre, key) {
  62026. var r = typeof env === 'function' ? env(key) : env[key];
  62027. if (r === undefined && key != '')
  62028. r = '';
  62029. else if (r === undefined)
  62030. r = '$';
  62031. if (typeof r === 'object') {
  62032. return pre + TOKEN + JSON.stringify(r) + TOKEN;
  62033. }
  62034. else return pre + r;
  62035. }
  62036. }
  62037. var osx = {
  62038. '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
  62039. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
  62040. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
  62041. '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
  62042. '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
  62043. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  62044. '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
  62045. '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
  62046. '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':
  62047. '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',
  62048. '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
  62049. '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':
  62050. 'code-insiders',
  62051. '/Applications/AppCode.app/Contents/MacOS/appcode':
  62052. '/Applications/AppCode.app/Contents/MacOS/appcode',
  62053. '/Applications/CLion.app/Contents/MacOS/clion':
  62054. '/Applications/CLion.app/Contents/MacOS/clion',
  62055. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':
  62056. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',
  62057. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':
  62058. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',
  62059. '/Applications/PyCharm.app/Contents/MacOS/pycharm':
  62060. '/Applications/PyCharm.app/Contents/MacOS/pycharm',
  62061. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':
  62062. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',
  62063. '/Applications/RubyMine.app/Contents/MacOS/rubymine':
  62064. '/Applications/RubyMine.app/Contents/MacOS/rubymine',
  62065. '/Applications/WebStorm.app/Contents/MacOS/webstorm':
  62066. '/Applications/WebStorm.app/Contents/MacOS/webstorm'
  62067. };
  62068. var linux = {
  62069. atom: 'atom',
  62070. Brackets: 'brackets',
  62071. code: 'code',
  62072. emacs: 'emacs',
  62073. 'idea.sh': 'idea',
  62074. 'phpstorm.sh': 'phpstorm',
  62075. 'pycharm.sh': 'pycharm',
  62076. 'rubymine.sh': 'rubymine',
  62077. sublime_text: 'subl',
  62078. vim: 'vim',
  62079. 'webstorm.sh': 'webstorm'
  62080. };
  62081. var windows = [
  62082. 'Brackets.exe',
  62083. 'Code.exe',
  62084. 'atom.exe',
  62085. 'sublime_text.exe',
  62086. 'notepad++.exe',
  62087. 'clion.exe',
  62088. 'clion64.exe',
  62089. 'idea.exe',
  62090. 'idea64.exe',
  62091. 'phpstorm.exe',
  62092. 'phpstorm64.exe',
  62093. 'pycharm.exe',
  62094. 'pycharm64.exe',
  62095. 'rubymine.exe',
  62096. 'rubymine64.exe',
  62097. 'webstorm.exe',
  62098. 'webstorm64.exe'
  62099. ];
  62100. const path$4 = path__default;
  62101. const shellQuote = shellQuote$1;
  62102. const childProcess$1 = require$$1__default$4;
  62103. // Map from full process name to binary that starts the process
  62104. // We can't just re-use full process name, because it will spawn a new instance
  62105. // of the app every time
  62106. const COMMON_EDITORS_OSX = osx;
  62107. const COMMON_EDITORS_LINUX = linux;
  62108. const COMMON_EDITORS_WIN = windows;
  62109. var guess = function guessEditor (specifiedEditor) {
  62110. if (specifiedEditor) {
  62111. return shellQuote.parse(specifiedEditor)
  62112. }
  62113. // We can find out which editor is currently running by:
  62114. // `ps x` on macOS and Linux
  62115. // `Get-Process` on Windows
  62116. try {
  62117. if (process.platform === 'darwin') {
  62118. const output = childProcess$1.execSync('ps x').toString();
  62119. const processNames = Object.keys(COMMON_EDITORS_OSX);
  62120. for (let i = 0; i < processNames.length; i++) {
  62121. const processName = processNames[i];
  62122. if (output.indexOf(processName) !== -1) {
  62123. return [COMMON_EDITORS_OSX[processName]]
  62124. }
  62125. }
  62126. } else if (process.platform === 'win32') {
  62127. const output = childProcess$1
  62128. .execSync('powershell -Command "Get-Process | Select-Object Path"', {
  62129. stdio: ['pipe', 'pipe', 'ignore']
  62130. })
  62131. .toString();
  62132. const runningProcesses = output.split('\r\n');
  62133. for (let i = 0; i < runningProcesses.length; i++) {
  62134. // `Get-Process` sometimes returns empty lines
  62135. if (!runningProcesses[i]) {
  62136. continue
  62137. }
  62138. const fullProcessPath = runningProcesses[i].trim();
  62139. const shortProcessName = path$4.basename(fullProcessPath);
  62140. if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
  62141. return [fullProcessPath]
  62142. }
  62143. }
  62144. } else if (process.platform === 'linux') {
  62145. // --no-heading No header line
  62146. // x List all processes owned by you
  62147. // -o comm Need only names column
  62148. const output = childProcess$1
  62149. .execSync('ps x --no-heading -o comm --sort=comm')
  62150. .toString();
  62151. const processNames = Object.keys(COMMON_EDITORS_LINUX);
  62152. for (let i = 0; i < processNames.length; i++) {
  62153. const processName = processNames[i];
  62154. if (output.indexOf(processName) !== -1) {
  62155. return [COMMON_EDITORS_LINUX[processName]]
  62156. }
  62157. }
  62158. }
  62159. } catch (error) {
  62160. // Ignore...
  62161. }
  62162. // Last resort, use old skool env vars
  62163. if (process.env.VISUAL) {
  62164. return [process.env.VISUAL]
  62165. } else if (process.env.EDITOR) {
  62166. return [process.env.EDITOR]
  62167. }
  62168. return [null]
  62169. };
  62170. const path$3 = path__default;
  62171. // normalize file/line numbers into command line args for specific editors
  62172. var getArgs = function getArgumentsForPosition (
  62173. editor,
  62174. fileName,
  62175. lineNumber,
  62176. columnNumber = 1
  62177. ) {
  62178. const editorBasename = path$3.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');
  62179. switch (editorBasename) {
  62180. case 'atom':
  62181. case 'Atom':
  62182. case 'Atom Beta':
  62183. case 'subl':
  62184. case 'sublime':
  62185. case 'sublime_text':
  62186. case 'wstorm':
  62187. case 'charm':
  62188. return [`${fileName}:${lineNumber}:${columnNumber}`]
  62189. case 'notepad++':
  62190. return ['-n' + lineNumber, fileName]
  62191. case 'vim':
  62192. case 'mvim':
  62193. return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName]
  62194. case 'joe':
  62195. return ['+' + `${lineNumber}`, fileName]
  62196. case 'emacs':
  62197. case 'emacsclient':
  62198. return [`+${lineNumber}:${columnNumber}`, fileName]
  62199. case 'rmate':
  62200. case 'mate':
  62201. case 'mine':
  62202. return ['--line', lineNumber, fileName]
  62203. case 'code':
  62204. case 'code-insiders':
  62205. case 'Code':
  62206. return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`]
  62207. case 'appcode':
  62208. case 'clion':
  62209. case 'clion64':
  62210. case 'idea':
  62211. case 'idea64':
  62212. case 'phpstorm':
  62213. case 'phpstorm64':
  62214. case 'pycharm':
  62215. case 'pycharm64':
  62216. case 'rubymine':
  62217. case 'rubymine64':
  62218. case 'webstorm':
  62219. case 'webstorm64':
  62220. return ['--line', lineNumber, fileName]
  62221. }
  62222. // For all others, drop the lineNumber until we have
  62223. // a mapping above, since providing the lineNumber incorrectly
  62224. // can result in errors or confusing behavior.
  62225. return [fileName]
  62226. };
  62227. /**
  62228. * Copyright (c) 2015-present, Facebook, Inc.
  62229. *
  62230. * This source code is licensed under the MIT license found in the
  62231. * LICENSE file at
  62232. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  62233. *
  62234. * Modified by Yuxi Evan You
  62235. */
  62236. const fs$1 = fs__default;
  62237. const os$1 = require$$0__default$1;
  62238. const path$2 = path__default;
  62239. const chalk = chalk$1.exports;
  62240. const childProcess = require$$1__default$4;
  62241. const guessEditor = guess;
  62242. const getArgumentsForPosition = getArgs;
  62243. function wrapErrorCallback (cb) {
  62244. return (fileName, errorMessage) => {
  62245. console.log();
  62246. console.log(
  62247. chalk.red('Could not open ' + path$2.basename(fileName) + ' in the editor.')
  62248. );
  62249. if (errorMessage) {
  62250. if (errorMessage[errorMessage.length - 1] !== '.') {
  62251. errorMessage += '.';
  62252. }
  62253. console.log(
  62254. chalk.red('The editor process exited with an error: ' + errorMessage)
  62255. );
  62256. }
  62257. console.log();
  62258. if (cb) cb(fileName, errorMessage);
  62259. }
  62260. }
  62261. function isTerminalEditor (editor) {
  62262. switch (editor) {
  62263. case 'vim':
  62264. case 'emacs':
  62265. case 'nano':
  62266. return true
  62267. }
  62268. return false
  62269. }
  62270. const positionRE = /:(\d+)(:(\d+))?$/;
  62271. function parseFile (file) {
  62272. const fileName = file.replace(positionRE, '');
  62273. const match = file.match(positionRE);
  62274. const lineNumber = match && match[1];
  62275. const columnNumber = match && match[3];
  62276. return {
  62277. fileName,
  62278. lineNumber,
  62279. columnNumber
  62280. }
  62281. }
  62282. let _childProcess = null;
  62283. function launchEditor (file, specifiedEditor, onErrorCallback) {
  62284. const parsed = parseFile(file);
  62285. let { fileName } = parsed;
  62286. const { lineNumber, columnNumber } = parsed;
  62287. if (!fs$1.existsSync(fileName)) {
  62288. return
  62289. }
  62290. if (typeof specifiedEditor === 'function') {
  62291. onErrorCallback = specifiedEditor;
  62292. specifiedEditor = undefined;
  62293. }
  62294. onErrorCallback = wrapErrorCallback(onErrorCallback);
  62295. const [editor, ...args] = guessEditor(specifiedEditor);
  62296. if (!editor) {
  62297. onErrorCallback(fileName, null);
  62298. return
  62299. }
  62300. if (
  62301. process.platform === 'linux' &&
  62302. fileName.startsWith('/mnt/') &&
  62303. /Microsoft/i.test(os$1.release())
  62304. ) {
  62305. // Assume WSL / "Bash on Ubuntu on Windows" is being used, and
  62306. // that the file exists on the Windows file system.
  62307. // `os.release()` is "4.4.0-43-Microsoft" in the current release
  62308. // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
  62309. // When a Windows editor is specified, interop functionality can
  62310. // handle the path translation, but only if a relative path is used.
  62311. fileName = path$2.relative('', fileName);
  62312. }
  62313. if (lineNumber) {
  62314. const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
  62315. args.push.apply(args, extraArgs);
  62316. } else {
  62317. args.push(fileName);
  62318. }
  62319. if (_childProcess && isTerminalEditor(editor)) {
  62320. // There's an existing editor process already and it's attached
  62321. // to the terminal, so go kill it. Otherwise two separate editor
  62322. // instances attach to the stdin/stdout which gets confusing.
  62323. _childProcess.kill('SIGKILL');
  62324. }
  62325. if (process.platform === 'win32') {
  62326. // On Windows, launch the editor in a shell because spawn can only
  62327. // launch .exe files.
  62328. _childProcess = childProcess.spawn(
  62329. 'cmd.exe',
  62330. ['/C', editor].concat(args),
  62331. { stdio: 'inherit' }
  62332. );
  62333. } else {
  62334. _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' });
  62335. }
  62336. _childProcess.on('exit', function (errorCode) {
  62337. _childProcess = null;
  62338. if (errorCode) {
  62339. onErrorCallback(fileName, '(code ' + errorCode + ')');
  62340. }
  62341. });
  62342. _childProcess.on('error', function (error) {
  62343. onErrorCallback(fileName, error.message);
  62344. });
  62345. }
  62346. var launchEditor_1 = launchEditor;
  62347. const url = require$$0__default$7;
  62348. const path$1 = path__default;
  62349. const launch = launchEditor_1;
  62350. var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => {
  62351. if (typeof specifiedEditor === 'function') {
  62352. onErrorCallback = specifiedEditor;
  62353. specifiedEditor = undefined;
  62354. }
  62355. if (typeof srcRoot === 'function') {
  62356. onErrorCallback = srcRoot;
  62357. srcRoot = undefined;
  62358. }
  62359. srcRoot = srcRoot || process.cwd();
  62360. return function launchEditorMiddleware (req, res, next) {
  62361. const { file } = url.parse(req.url, true).query || {};
  62362. if (!file) {
  62363. res.statusCode = 500;
  62364. res.end(`launch-editor-middleware: required query param "file" is missing.`);
  62365. } else {
  62366. launch(path$1.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
  62367. res.end();
  62368. }
  62369. }
  62370. };
  62371. const externalTypes = [
  62372. 'css',
  62373. // supported pre-processor types
  62374. 'less',
  62375. 'sass',
  62376. 'scss',
  62377. 'styl',
  62378. 'stylus',
  62379. 'pcss',
  62380. 'postcss',
  62381. // known SFC types
  62382. 'vue',
  62383. 'svelte',
  62384. 'marko',
  62385. // JSX/TSX may be configured to be compiled differently from how esbuild
  62386. // handles it by default, so exclude them as well
  62387. 'jsx',
  62388. 'tsx',
  62389. ...KNOWN_ASSET_TYPES
  62390. ];
  62391. function esbuildDepPlugin(qualified, exportsData, config, ssr) {
  62392. // default resolver which prefers ESM
  62393. const _resolve = config.createResolver({ asSrc: false });
  62394. // cjs resolver that prefers Node
  62395. const _resolveRequire = config.createResolver({
  62396. asSrc: false,
  62397. isRequire: true
  62398. });
  62399. const resolve = (id, importer, kind, resolveDir) => {
  62400. let _importer;
  62401. // explicit resolveDir - this is passed only during yarn pnp resolve for
  62402. // entries
  62403. if (resolveDir) {
  62404. _importer = normalizePath$4(path__default.join(resolveDir, '*'));
  62405. }
  62406. else {
  62407. // map importer ids to file paths for correct resolution
  62408. _importer = importer in qualified ? qualified[importer] : importer;
  62409. }
  62410. const resolver = kind.startsWith('require') ? _resolveRequire : _resolve;
  62411. return resolver(id, _importer, undefined, ssr);
  62412. };
  62413. return {
  62414. name: 'vite:dep-pre-bundle',
  62415. setup(build) {
  62416. // externalize assets and commonly known non-js file types
  62417. build.onResolve({
  62418. filter: new RegExp(`\\.(` + externalTypes.join('|') + `)(\\?.*)?$`)
  62419. }, async ({ path: id, importer, kind }) => {
  62420. const resolved = await resolve(id, importer, kind);
  62421. if (resolved) {
  62422. return {
  62423. path: resolved,
  62424. external: true
  62425. };
  62426. }
  62427. });
  62428. function resolveEntry(id) {
  62429. const flatId = flattenId(id);
  62430. if (flatId in qualified) {
  62431. return {
  62432. path: flatId,
  62433. namespace: 'dep'
  62434. };
  62435. }
  62436. }
  62437. build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => {
  62438. // ensure esbuild uses our resolved entries
  62439. let entry;
  62440. // if this is an entry, return entry namespace resolve result
  62441. if (!importer) {
  62442. if ((entry = resolveEntry(id)))
  62443. return entry;
  62444. // check if this is aliased to an entry - also return entry namespace
  62445. const aliased = await _resolve(id, undefined, true);
  62446. if (aliased && (entry = resolveEntry(aliased))) {
  62447. return entry;
  62448. }
  62449. }
  62450. // use vite's own resolver
  62451. const resolved = await resolve(id, importer, kind);
  62452. if (resolved) {
  62453. if (resolved.startsWith(browserExternalId)) {
  62454. return {
  62455. path: id,
  62456. namespace: 'browser-external'
  62457. };
  62458. }
  62459. if (isExternalUrl(resolved)) {
  62460. return {
  62461. path: resolved,
  62462. external: true
  62463. };
  62464. }
  62465. return {
  62466. path: path__default.resolve(resolved)
  62467. };
  62468. }
  62469. });
  62470. // For entry files, we'll read it ourselves and construct a proxy module
  62471. // to retain the entry's raw id instead of file path so that esbuild
  62472. // outputs desired output file structure.
  62473. // It is necessary to do the re-exporting to separate the virtual proxy
  62474. // module from the actual module since the actual module may get
  62475. // referenced via relative imports - if we don't separate the proxy and
  62476. // the actual module, esbuild will create duplicated copies of the same
  62477. // module!
  62478. const root = path__default.resolve(config.root);
  62479. build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => {
  62480. const entryFile = qualified[id];
  62481. let relativePath = normalizePath$4(path__default.relative(root, entryFile));
  62482. if (!relativePath.startsWith('./') &&
  62483. !relativePath.startsWith('../') &&
  62484. relativePath !== '.') {
  62485. relativePath = `./${relativePath}`;
  62486. }
  62487. let contents = '';
  62488. const data = exportsData[id];
  62489. const [imports, exports] = data;
  62490. if (!imports.length && !exports.length) {
  62491. // cjs
  62492. contents += `export default require("${relativePath}");`;
  62493. }
  62494. else {
  62495. if (exports.includes('default')) {
  62496. contents += `import d from "${relativePath}";export default d;`;
  62497. }
  62498. if (data.hasReExports ||
  62499. exports.length > 1 ||
  62500. exports[0] !== 'default') {
  62501. contents += `\nexport * from "${relativePath}"`;
  62502. }
  62503. }
  62504. let ext = path__default.extname(entryFile).slice(1);
  62505. if (ext === 'mjs')
  62506. ext = 'js';
  62507. return {
  62508. loader: ext,
  62509. contents,
  62510. resolveDir: root
  62511. };
  62512. });
  62513. build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path: id }) => {
  62514. return {
  62515. contents: `export default new Proxy({}, {
  62516. get() {
  62517. throw new Error('Module "${id}" has been externalized for ` +
  62518. `browser compatibility and cannot be accessed in client code.')
  62519. }
  62520. })`
  62521. };
  62522. });
  62523. // yarn 2 pnp compat
  62524. if (isRunningWithYarnPnp) {
  62525. build.onResolve({ filter: /.*/ }, async ({ path, importer, kind, resolveDir }) => ({
  62526. // pass along resolveDir for entries
  62527. path: await resolve(path, importer, kind, resolveDir)
  62528. }));
  62529. build.onLoad({ filter: /.*/ }, async (args) => ({
  62530. contents: await require('fs').promises.readFile(args.path),
  62531. loader: 'default'
  62532. }));
  62533. }
  62534. }
  62535. };
  62536. }
  62537. const debug$1 = createDebugger('vite:deps');
  62538. async function optimizeDeps(config, force = config.server.force, asCommand = false, newDeps, // missing imports encountered after server has started
  62539. ssr) {
  62540. var _a, _b, _c, _d;
  62541. config = {
  62542. ...config,
  62543. command: 'build'
  62544. };
  62545. const { root, logger, cacheDir } = config;
  62546. const log = asCommand ? logger.info : debug$1;
  62547. if (!cacheDir) {
  62548. log(`No cache directory. Skipping.`);
  62549. return null;
  62550. }
  62551. const dataPath = path__default.join(cacheDir, '_metadata.json');
  62552. const mainHash = getDepHash(root, config);
  62553. const data = {
  62554. hash: mainHash,
  62555. browserHash: mainHash,
  62556. optimized: {}
  62557. };
  62558. if (!force) {
  62559. let prevData;
  62560. try {
  62561. prevData = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8'));
  62562. }
  62563. catch (e) { }
  62564. // hash is consistent, no need to re-bundle
  62565. if (prevData && prevData.hash === data.hash) {
  62566. log('Hash is consistent. Skipping. Use --force to override.');
  62567. return prevData;
  62568. }
  62569. }
  62570. if (fs__default.existsSync(cacheDir)) {
  62571. emptyDir(cacheDir);
  62572. }
  62573. else {
  62574. fs__default.mkdirSync(cacheDir, { recursive: true });
  62575. }
  62576. // a hint for Node.js
  62577. // all files in the cache directory should be recognized as ES modules
  62578. writeFile(path__default.resolve(cacheDir, 'package.json'), JSON.stringify({ type: 'module' }));
  62579. let deps, missing;
  62580. if (!newDeps) {
  62581. ({ deps, missing } = await scanImports(config));
  62582. }
  62583. else {
  62584. deps = newDeps;
  62585. missing = {};
  62586. }
  62587. // update browser hash
  62588. data.browserHash = require$$1$1.createHash('sha256')
  62589. .update(data.hash + JSON.stringify(deps))
  62590. .digest('hex')
  62591. .substr(0, 8);
  62592. const missingIds = Object.keys(missing);
  62593. if (missingIds.length) {
  62594. throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds
  62595. .map((id) => `${source.cyan(id)} ${source.white.dim(`(imported by ${missing[id]})`)}`)
  62596. .join(`\n `)}\n\nAre they installed?`);
  62597. }
  62598. const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include;
  62599. if (include) {
  62600. const resolve = config.createResolver({ asSrc: false });
  62601. for (const id of include) {
  62602. // normalize 'foo >bar` as 'foo > bar' to prevent same id being added
  62603. // and for pretty printing
  62604. const normalizedId = normalizeId$1(id);
  62605. if (!deps[normalizedId]) {
  62606. const entry = await resolve(id);
  62607. if (entry) {
  62608. deps[normalizedId] = entry;
  62609. }
  62610. else {
  62611. throw new Error(`Failed to resolve force included dependency: ${source.cyan(id)}`);
  62612. }
  62613. }
  62614. }
  62615. }
  62616. const qualifiedIds = Object.keys(deps);
  62617. if (!qualifiedIds.length) {
  62618. writeFile(dataPath, JSON.stringify(data, null, 2));
  62619. log(`No dependencies to bundle. Skipping.\n\n\n`);
  62620. return data;
  62621. }
  62622. const total = qualifiedIds.length;
  62623. const maxListed = 5;
  62624. const listed = Math.min(total, maxListed);
  62625. const extra = Math.max(0, total - maxListed);
  62626. const depsString = source.yellow(qualifiedIds.slice(0, listed).join(`\n `) +
  62627. (extra > 0 ? `\n (...and ${extra} more)` : ``));
  62628. if (!asCommand) {
  62629. if (!newDeps) {
  62630. // This is auto run on server start - let the user know that we are
  62631. // pre-optimizing deps
  62632. logger.info(source.greenBright(`Pre-bundling dependencies:\n ${depsString}`));
  62633. logger.info(`(this will be run only when your dependencies or config have changed)`);
  62634. }
  62635. }
  62636. else {
  62637. logger.info(source.greenBright(`Optimizing dependencies:\n ${depsString}`));
  62638. }
  62639. // esbuild generates nested directory output with lowest common ancestor base
  62640. // this is unpredictable and makes it difficult to analyze entry / output
  62641. // mapping. So what we do here is:
  62642. // 1. flatten all ids to eliminate slash
  62643. // 2. in the plugin, read the entry ourselves as virtual files to retain the
  62644. // path.
  62645. const flatIdDeps = {};
  62646. const idToExports = {};
  62647. const flatIdToExports = {};
  62648. const { plugins = [], ...esbuildOptions } = (_c = (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.esbuildOptions) !== null && _c !== void 0 ? _c : {};
  62649. await init;
  62650. for (const id in deps) {
  62651. const flatId = flattenId(id);
  62652. const filePath = (flatIdDeps[flatId] = deps[id]);
  62653. const entryContent = fs__default.readFileSync(filePath, 'utf-8');
  62654. let exportsData;
  62655. try {
  62656. exportsData = parse$d(entryContent);
  62657. }
  62658. catch {
  62659. debug$1(`Unable to parse dependency: ${id}. Trying again with a JSX transform.`);
  62660. const transformed = await transformWithEsbuild(entryContent, filePath, {
  62661. loader: 'jsx'
  62662. });
  62663. // Ensure that optimization won't fail by defaulting '.js' to the JSX parser.
  62664. // This is useful for packages such as Gatsby.
  62665. esbuildOptions.loader = {
  62666. '.js': 'jsx',
  62667. ...esbuildOptions.loader
  62668. };
  62669. exportsData = parse$d(transformed.code);
  62670. }
  62671. for (const { ss, se } of exportsData[0]) {
  62672. const exp = entryContent.slice(ss, se);
  62673. if (/export\s+\*\s+from/.test(exp)) {
  62674. exportsData.hasReExports = true;
  62675. }
  62676. }
  62677. idToExports[id] = exportsData;
  62678. flatIdToExports[flatId] = exportsData;
  62679. }
  62680. const define = {
  62681. 'process.env.NODE_ENV': JSON.stringify(config.mode)
  62682. };
  62683. for (const key in config.define) {
  62684. const value = config.define[key];
  62685. define[key] = typeof value === 'string' ? value : JSON.stringify(value);
  62686. }
  62687. const start = Date.now();
  62688. const result = await esbuild.build({
  62689. absWorkingDir: process.cwd(),
  62690. entryPoints: Object.keys(flatIdDeps),
  62691. bundle: true,
  62692. format: 'esm',
  62693. external: (_d = config.optimizeDeps) === null || _d === void 0 ? void 0 : _d.exclude,
  62694. logLevel: 'error',
  62695. splitting: true,
  62696. sourcemap: true,
  62697. outdir: cacheDir,
  62698. treeShaking: 'ignore-annotations',
  62699. metafile: true,
  62700. define,
  62701. plugins: [
  62702. ...plugins,
  62703. esbuildDepPlugin(flatIdDeps, flatIdToExports, config, ssr)
  62704. ],
  62705. ...esbuildOptions
  62706. });
  62707. const meta = result.metafile;
  62708. // the paths in `meta.outputs` are relative to `process.cwd()`
  62709. const cacheDirOutputPath = path__default.relative(process.cwd(), cacheDir);
  62710. for (const id in deps) {
  62711. const entry = deps[id];
  62712. data.optimized[id] = {
  62713. file: normalizePath$4(path__default.resolve(cacheDir, flattenId(id) + '.js')),
  62714. src: entry,
  62715. needsInterop: needsInterop(id, idToExports[id], meta.outputs, cacheDirOutputPath)
  62716. };
  62717. }
  62718. writeFile(dataPath, JSON.stringify(data, null, 2));
  62719. debug$1(`deps bundled in ${Date.now() - start}ms`);
  62720. return data;
  62721. }
  62722. // https://github.com/vitejs/vite/issues/1724#issuecomment-767619642
  62723. // a list of modules that pretends to be ESM but still uses `require`.
  62724. // this causes esbuild to wrap them as CJS even when its entry appears to be ESM.
  62725. const KNOWN_INTEROP_IDS = new Set(['moment']);
  62726. function needsInterop(id, exportsData, outputs, cacheDirOutputPath) {
  62727. if (KNOWN_INTEROP_IDS.has(id)) {
  62728. return true;
  62729. }
  62730. const [imports, exports] = exportsData;
  62731. // entry has no ESM syntax - likely CJS or UMD
  62732. if (!exports.length && !imports.length) {
  62733. return true;
  62734. }
  62735. // if a peer dependency used require() on a ESM dependency, esbuild turns the
  62736. // ESM dependency's entry chunk into a single default export... detect
  62737. // such cases by checking exports mismatch, and force interop.
  62738. const flatId = flattenId(id) + '.js';
  62739. let generatedExports;
  62740. for (const output in outputs) {
  62741. if (normalizePath$4(output) ===
  62742. normalizePath$4(path__default.join(cacheDirOutputPath, flatId))) {
  62743. generatedExports = outputs[output].exports;
  62744. break;
  62745. }
  62746. }
  62747. if (!generatedExports ||
  62748. (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))) {
  62749. return true;
  62750. }
  62751. return false;
  62752. }
  62753. function isSingleDefaultExport(exports) {
  62754. return exports.length === 1 && exports[0] === 'default';
  62755. }
  62756. const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
  62757. function getDepHash(root, config) {
  62758. var _a, _b;
  62759. let content = lookupFile(root, lockfileFormats) || '';
  62760. // also take config into account
  62761. // only a subset of config options that can affect dep optimization
  62762. content += JSON.stringify({
  62763. mode: config.mode,
  62764. root: config.root,
  62765. resolve: config.resolve,
  62766. assetsInclude: config.assetsInclude,
  62767. plugins: config.plugins.map((p) => p.name),
  62768. optimizeDeps: {
  62769. include: (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include,
  62770. exclude: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude
  62771. }
  62772. }, (_, value) => {
  62773. if (typeof value === 'function' || value instanceof RegExp) {
  62774. return value.toString();
  62775. }
  62776. return value;
  62777. });
  62778. return require$$1$1.createHash('sha256').update(content).digest('hex').substr(0, 8);
  62779. }
  62780. var index$1 = {
  62781. __proto__: null,
  62782. optimizeDeps: optimizeDeps
  62783. };
  62784. var sourceMapGenerator = {};
  62785. var base64Vlq = {};
  62786. var base64$1 = {};
  62787. /* -*- Mode: js; js-indent-level: 2; -*- */
  62788. /*
  62789. * Copyright 2011 Mozilla Foundation and contributors
  62790. * Licensed under the New BSD license. See LICENSE or:
  62791. * http://opensource.org/licenses/BSD-3-Clause
  62792. */
  62793. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  62794. /**
  62795. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  62796. */
  62797. base64$1.encode = function (number) {
  62798. if (0 <= number && number < intToCharMap.length) {
  62799. return intToCharMap[number];
  62800. }
  62801. throw new TypeError("Must be between 0 and 63: " + number);
  62802. };
  62803. /**
  62804. * Decode a single base 64 character code digit to an integer. Returns -1 on
  62805. * failure.
  62806. */
  62807. base64$1.decode = function (charCode) {
  62808. var bigA = 65; // 'A'
  62809. var bigZ = 90; // 'Z'
  62810. var littleA = 97; // 'a'
  62811. var littleZ = 122; // 'z'
  62812. var zero = 48; // '0'
  62813. var nine = 57; // '9'
  62814. var plus = 43; // '+'
  62815. var slash = 47; // '/'
  62816. var littleOffset = 26;
  62817. var numberOffset = 52;
  62818. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  62819. if (bigA <= charCode && charCode <= bigZ) {
  62820. return (charCode - bigA);
  62821. }
  62822. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  62823. if (littleA <= charCode && charCode <= littleZ) {
  62824. return (charCode - littleA + littleOffset);
  62825. }
  62826. // 52 - 61: 0123456789
  62827. if (zero <= charCode && charCode <= nine) {
  62828. return (charCode - zero + numberOffset);
  62829. }
  62830. // 62: +
  62831. if (charCode == plus) {
  62832. return 62;
  62833. }
  62834. // 63: /
  62835. if (charCode == slash) {
  62836. return 63;
  62837. }
  62838. // Invalid base64 digit.
  62839. return -1;
  62840. };
  62841. /* -*- Mode: js; js-indent-level: 2; -*- */
  62842. /*
  62843. * Copyright 2011 Mozilla Foundation and contributors
  62844. * Licensed under the New BSD license. See LICENSE or:
  62845. * http://opensource.org/licenses/BSD-3-Clause
  62846. *
  62847. * Based on the Base 64 VLQ implementation in Closure Compiler:
  62848. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  62849. *
  62850. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  62851. * Redistribution and use in source and binary forms, with or without
  62852. * modification, are permitted provided that the following conditions are
  62853. * met:
  62854. *
  62855. * * Redistributions of source code must retain the above copyright
  62856. * notice, this list of conditions and the following disclaimer.
  62857. * * Redistributions in binary form must reproduce the above
  62858. * copyright notice, this list of conditions and the following
  62859. * disclaimer in the documentation and/or other materials provided
  62860. * with the distribution.
  62861. * * Neither the name of Google Inc. nor the names of its
  62862. * contributors may be used to endorse or promote products derived
  62863. * from this software without specific prior written permission.
  62864. *
  62865. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  62866. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  62867. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  62868. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  62869. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  62870. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  62871. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  62872. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  62873. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  62874. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  62875. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  62876. */
  62877. var base64 = base64$1;
  62878. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  62879. // length quantities we use in the source map spec, the first bit is the sign,
  62880. // the next four bits are the actual value, and the 6th bit is the
  62881. // continuation bit. The continuation bit tells us whether there are more
  62882. // digits in this value following this digit.
  62883. //
  62884. // Continuation
  62885. // | Sign
  62886. // | |
  62887. // V V
  62888. // 101011
  62889. var VLQ_BASE_SHIFT = 5;
  62890. // binary: 100000
  62891. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  62892. // binary: 011111
  62893. var VLQ_BASE_MASK = VLQ_BASE - 1;
  62894. // binary: 100000
  62895. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  62896. /**
  62897. * Converts from a two-complement value to a value where the sign bit is
  62898. * placed in the least significant bit. For example, as decimals:
  62899. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  62900. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  62901. */
  62902. function toVLQSigned(aValue) {
  62903. return aValue < 0
  62904. ? ((-aValue) << 1) + 1
  62905. : (aValue << 1) + 0;
  62906. }
  62907. /**
  62908. * Converts to a two-complement value from a value where the sign bit is
  62909. * placed in the least significant bit. For example, as decimals:
  62910. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  62911. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  62912. */
  62913. function fromVLQSigned(aValue) {
  62914. var isNegative = (aValue & 1) === 1;
  62915. var shifted = aValue >> 1;
  62916. return isNegative
  62917. ? -shifted
  62918. : shifted;
  62919. }
  62920. /**
  62921. * Returns the base 64 VLQ encoded value.
  62922. */
  62923. base64Vlq.encode = function base64VLQ_encode(aValue) {
  62924. var encoded = "";
  62925. var digit;
  62926. var vlq = toVLQSigned(aValue);
  62927. do {
  62928. digit = vlq & VLQ_BASE_MASK;
  62929. vlq >>>= VLQ_BASE_SHIFT;
  62930. if (vlq > 0) {
  62931. // There are still more digits in this value, so we must make sure the
  62932. // continuation bit is marked.
  62933. digit |= VLQ_CONTINUATION_BIT;
  62934. }
  62935. encoded += base64.encode(digit);
  62936. } while (vlq > 0);
  62937. return encoded;
  62938. };
  62939. /**
  62940. * Decodes the next base 64 VLQ value from the given string and returns the
  62941. * value and the rest of the string via the out parameter.
  62942. */
  62943. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  62944. var strLen = aStr.length;
  62945. var result = 0;
  62946. var shift = 0;
  62947. var continuation, digit;
  62948. do {
  62949. if (aIndex >= strLen) {
  62950. throw new Error("Expected more digits in base 64 VLQ value.");
  62951. }
  62952. digit = base64.decode(aStr.charCodeAt(aIndex++));
  62953. if (digit === -1) {
  62954. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  62955. }
  62956. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  62957. digit &= VLQ_BASE_MASK;
  62958. result = result + (digit << shift);
  62959. shift += VLQ_BASE_SHIFT;
  62960. } while (continuation);
  62961. aOutParam.value = fromVLQSigned(result);
  62962. aOutParam.rest = aIndex;
  62963. };
  62964. var util$5 = {};
  62965. /* -*- Mode: js; js-indent-level: 2; -*- */
  62966. (function (exports) {
  62967. /*
  62968. * Copyright 2011 Mozilla Foundation and contributors
  62969. * Licensed under the New BSD license. See LICENSE or:
  62970. * http://opensource.org/licenses/BSD-3-Clause
  62971. */
  62972. /**
  62973. * This is a helper function for getting values from parameter/options
  62974. * objects.
  62975. *
  62976. * @param args The object we are extracting values from
  62977. * @param name The name of the property we are getting.
  62978. * @param defaultValue An optional value to return if the property is missing
  62979. * from the object. If this is not specified and the property is missing, an
  62980. * error will be thrown.
  62981. */
  62982. function getArg(aArgs, aName, aDefaultValue) {
  62983. if (aName in aArgs) {
  62984. return aArgs[aName];
  62985. } else if (arguments.length === 3) {
  62986. return aDefaultValue;
  62987. } else {
  62988. throw new Error('"' + aName + '" is a required argument.');
  62989. }
  62990. }
  62991. exports.getArg = getArg;
  62992. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  62993. var dataUrlRegexp = /^data:.+\,.+$/;
  62994. function urlParse(aUrl) {
  62995. var match = aUrl.match(urlRegexp);
  62996. if (!match) {
  62997. return null;
  62998. }
  62999. return {
  63000. scheme: match[1],
  63001. auth: match[2],
  63002. host: match[3],
  63003. port: match[4],
  63004. path: match[5]
  63005. };
  63006. }
  63007. exports.urlParse = urlParse;
  63008. function urlGenerate(aParsedUrl) {
  63009. var url = '';
  63010. if (aParsedUrl.scheme) {
  63011. url += aParsedUrl.scheme + ':';
  63012. }
  63013. url += '//';
  63014. if (aParsedUrl.auth) {
  63015. url += aParsedUrl.auth + '@';
  63016. }
  63017. if (aParsedUrl.host) {
  63018. url += aParsedUrl.host;
  63019. }
  63020. if (aParsedUrl.port) {
  63021. url += ":" + aParsedUrl.port;
  63022. }
  63023. if (aParsedUrl.path) {
  63024. url += aParsedUrl.path;
  63025. }
  63026. return url;
  63027. }
  63028. exports.urlGenerate = urlGenerate;
  63029. /**
  63030. * Normalizes a path, or the path portion of a URL:
  63031. *
  63032. * - Replaces consecutive slashes with one slash.
  63033. * - Removes unnecessary '.' parts.
  63034. * - Removes unnecessary '<dir>/..' parts.
  63035. *
  63036. * Based on code in the Node.js 'path' core module.
  63037. *
  63038. * @param aPath The path or url to normalize.
  63039. */
  63040. function normalize(aPath) {
  63041. var path = aPath;
  63042. var url = urlParse(aPath);
  63043. if (url) {
  63044. if (!url.path) {
  63045. return aPath;
  63046. }
  63047. path = url.path;
  63048. }
  63049. var isAbsolute = exports.isAbsolute(path);
  63050. var parts = path.split(/\/+/);
  63051. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  63052. part = parts[i];
  63053. if (part === '.') {
  63054. parts.splice(i, 1);
  63055. } else if (part === '..') {
  63056. up++;
  63057. } else if (up > 0) {
  63058. if (part === '') {
  63059. // The first part is blank if the path is absolute. Trying to go
  63060. // above the root is a no-op. Therefore we can remove all '..' parts
  63061. // directly after the root.
  63062. parts.splice(i + 1, up);
  63063. up = 0;
  63064. } else {
  63065. parts.splice(i, 2);
  63066. up--;
  63067. }
  63068. }
  63069. }
  63070. path = parts.join('/');
  63071. if (path === '') {
  63072. path = isAbsolute ? '/' : '.';
  63073. }
  63074. if (url) {
  63075. url.path = path;
  63076. return urlGenerate(url);
  63077. }
  63078. return path;
  63079. }
  63080. exports.normalize = normalize;
  63081. /**
  63082. * Joins two paths/URLs.
  63083. *
  63084. * @param aRoot The root path or URL.
  63085. * @param aPath The path or URL to be joined with the root.
  63086. *
  63087. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  63088. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  63089. * first.
  63090. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  63091. * is updated with the result and aRoot is returned. Otherwise the result
  63092. * is returned.
  63093. * - If aPath is absolute, the result is aPath.
  63094. * - Otherwise the two paths are joined with a slash.
  63095. * - Joining for example 'http://' and 'www.example.com' is also supported.
  63096. */
  63097. function join(aRoot, aPath) {
  63098. if (aRoot === "") {
  63099. aRoot = ".";
  63100. }
  63101. if (aPath === "") {
  63102. aPath = ".";
  63103. }
  63104. var aPathUrl = urlParse(aPath);
  63105. var aRootUrl = urlParse(aRoot);
  63106. if (aRootUrl) {
  63107. aRoot = aRootUrl.path || '/';
  63108. }
  63109. // `join(foo, '//www.example.org')`
  63110. if (aPathUrl && !aPathUrl.scheme) {
  63111. if (aRootUrl) {
  63112. aPathUrl.scheme = aRootUrl.scheme;
  63113. }
  63114. return urlGenerate(aPathUrl);
  63115. }
  63116. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  63117. return aPath;
  63118. }
  63119. // `join('http://', 'www.example.com')`
  63120. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  63121. aRootUrl.host = aPath;
  63122. return urlGenerate(aRootUrl);
  63123. }
  63124. var joined = aPath.charAt(0) === '/'
  63125. ? aPath
  63126. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  63127. if (aRootUrl) {
  63128. aRootUrl.path = joined;
  63129. return urlGenerate(aRootUrl);
  63130. }
  63131. return joined;
  63132. }
  63133. exports.join = join;
  63134. exports.isAbsolute = function (aPath) {
  63135. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  63136. };
  63137. /**
  63138. * Make a path relative to a URL or another path.
  63139. *
  63140. * @param aRoot The root path or URL.
  63141. * @param aPath The path or URL to be made relative to aRoot.
  63142. */
  63143. function relative(aRoot, aPath) {
  63144. if (aRoot === "") {
  63145. aRoot = ".";
  63146. }
  63147. aRoot = aRoot.replace(/\/$/, '');
  63148. // It is possible for the path to be above the root. In this case, simply
  63149. // checking whether the root is a prefix of the path won't work. Instead, we
  63150. // need to remove components from the root one by one, until either we find
  63151. // a prefix that fits, or we run out of components to remove.
  63152. var level = 0;
  63153. while (aPath.indexOf(aRoot + '/') !== 0) {
  63154. var index = aRoot.lastIndexOf("/");
  63155. if (index < 0) {
  63156. return aPath;
  63157. }
  63158. // If the only part of the root that is left is the scheme (i.e. http://,
  63159. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  63160. // have exhausted all components, so the path is not relative to the root.
  63161. aRoot = aRoot.slice(0, index);
  63162. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  63163. return aPath;
  63164. }
  63165. ++level;
  63166. }
  63167. // Make sure we add a "../" for each component we removed from the root.
  63168. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  63169. }
  63170. exports.relative = relative;
  63171. var supportsNullProto = (function () {
  63172. var obj = Object.create(null);
  63173. return !('__proto__' in obj);
  63174. }());
  63175. function identity (s) {
  63176. return s;
  63177. }
  63178. /**
  63179. * Because behavior goes wacky when you set `__proto__` on objects, we
  63180. * have to prefix all the strings in our set with an arbitrary character.
  63181. *
  63182. * See https://github.com/mozilla/source-map/pull/31 and
  63183. * https://github.com/mozilla/source-map/issues/30
  63184. *
  63185. * @param String aStr
  63186. */
  63187. function toSetString(aStr) {
  63188. if (isProtoString(aStr)) {
  63189. return '$' + aStr;
  63190. }
  63191. return aStr;
  63192. }
  63193. exports.toSetString = supportsNullProto ? identity : toSetString;
  63194. function fromSetString(aStr) {
  63195. if (isProtoString(aStr)) {
  63196. return aStr.slice(1);
  63197. }
  63198. return aStr;
  63199. }
  63200. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  63201. function isProtoString(s) {
  63202. if (!s) {
  63203. return false;
  63204. }
  63205. var length = s.length;
  63206. if (length < 9 /* "__proto__".length */) {
  63207. return false;
  63208. }
  63209. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  63210. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  63211. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  63212. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  63213. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  63214. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  63215. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  63216. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  63217. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  63218. return false;
  63219. }
  63220. for (var i = length - 10; i >= 0; i--) {
  63221. if (s.charCodeAt(i) !== 36 /* '$' */) {
  63222. return false;
  63223. }
  63224. }
  63225. return true;
  63226. }
  63227. /**
  63228. * Comparator between two mappings where the original positions are compared.
  63229. *
  63230. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  63231. * mappings with the same original source/line/column, but different generated
  63232. * line and column the same. Useful when searching for a mapping with a
  63233. * stubbed out mapping.
  63234. */
  63235. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  63236. var cmp = strcmp(mappingA.source, mappingB.source);
  63237. if (cmp !== 0) {
  63238. return cmp;
  63239. }
  63240. cmp = mappingA.originalLine - mappingB.originalLine;
  63241. if (cmp !== 0) {
  63242. return cmp;
  63243. }
  63244. cmp = mappingA.originalColumn - mappingB.originalColumn;
  63245. if (cmp !== 0 || onlyCompareOriginal) {
  63246. return cmp;
  63247. }
  63248. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  63249. if (cmp !== 0) {
  63250. return cmp;
  63251. }
  63252. cmp = mappingA.generatedLine - mappingB.generatedLine;
  63253. if (cmp !== 0) {
  63254. return cmp;
  63255. }
  63256. return strcmp(mappingA.name, mappingB.name);
  63257. }
  63258. exports.compareByOriginalPositions = compareByOriginalPositions;
  63259. /**
  63260. * Comparator between two mappings with deflated source and name indices where
  63261. * the generated positions are compared.
  63262. *
  63263. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  63264. * mappings with the same generated line and column, but different
  63265. * source/name/original line and column the same. Useful when searching for a
  63266. * mapping with a stubbed out mapping.
  63267. */
  63268. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  63269. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  63270. if (cmp !== 0) {
  63271. return cmp;
  63272. }
  63273. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  63274. if (cmp !== 0 || onlyCompareGenerated) {
  63275. return cmp;
  63276. }
  63277. cmp = strcmp(mappingA.source, mappingB.source);
  63278. if (cmp !== 0) {
  63279. return cmp;
  63280. }
  63281. cmp = mappingA.originalLine - mappingB.originalLine;
  63282. if (cmp !== 0) {
  63283. return cmp;
  63284. }
  63285. cmp = mappingA.originalColumn - mappingB.originalColumn;
  63286. if (cmp !== 0) {
  63287. return cmp;
  63288. }
  63289. return strcmp(mappingA.name, mappingB.name);
  63290. }
  63291. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  63292. function strcmp(aStr1, aStr2) {
  63293. if (aStr1 === aStr2) {
  63294. return 0;
  63295. }
  63296. if (aStr1 === null) {
  63297. return 1; // aStr2 !== null
  63298. }
  63299. if (aStr2 === null) {
  63300. return -1; // aStr1 !== null
  63301. }
  63302. if (aStr1 > aStr2) {
  63303. return 1;
  63304. }
  63305. return -1;
  63306. }
  63307. /**
  63308. * Comparator between two mappings with inflated source and name strings where
  63309. * the generated positions are compared.
  63310. */
  63311. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  63312. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  63313. if (cmp !== 0) {
  63314. return cmp;
  63315. }
  63316. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  63317. if (cmp !== 0) {
  63318. return cmp;
  63319. }
  63320. cmp = strcmp(mappingA.source, mappingB.source);
  63321. if (cmp !== 0) {
  63322. return cmp;
  63323. }
  63324. cmp = mappingA.originalLine - mappingB.originalLine;
  63325. if (cmp !== 0) {
  63326. return cmp;
  63327. }
  63328. cmp = mappingA.originalColumn - mappingB.originalColumn;
  63329. if (cmp !== 0) {
  63330. return cmp;
  63331. }
  63332. return strcmp(mappingA.name, mappingB.name);
  63333. }
  63334. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  63335. /**
  63336. * Strip any JSON XSSI avoidance prefix from the string (as documented
  63337. * in the source maps specification), and then parse the string as
  63338. * JSON.
  63339. */
  63340. function parseSourceMapInput(str) {
  63341. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  63342. }
  63343. exports.parseSourceMapInput = parseSourceMapInput;
  63344. /**
  63345. * Compute the URL of a source given the the source root, the source's
  63346. * URL, and the source map's URL.
  63347. */
  63348. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  63349. sourceURL = sourceURL || '';
  63350. if (sourceRoot) {
  63351. // This follows what Chrome does.
  63352. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  63353. sourceRoot += '/';
  63354. }
  63355. // The spec says:
  63356. // Line 4: An optional source root, useful for relocating source
  63357. // files on a server or removing repeated values in the
  63358. // “sources” entry. This value is prepended to the individual
  63359. // entries in the “source” field.
  63360. sourceURL = sourceRoot + sourceURL;
  63361. }
  63362. // Historically, SourceMapConsumer did not take the sourceMapURL as
  63363. // a parameter. This mode is still somewhat supported, which is why
  63364. // this code block is conditional. However, it's preferable to pass
  63365. // the source map URL to SourceMapConsumer, so that this function
  63366. // can implement the source URL resolution algorithm as outlined in
  63367. // the spec. This block is basically the equivalent of:
  63368. // new URL(sourceURL, sourceMapURL).toString()
  63369. // ... except it avoids using URL, which wasn't available in the
  63370. // older releases of node still supported by this library.
  63371. //
  63372. // The spec says:
  63373. // If the sources are not absolute URLs after prepending of the
  63374. // “sourceRoot”, the sources are resolved relative to the
  63375. // SourceMap (like resolving script src in a html document).
  63376. if (sourceMapURL) {
  63377. var parsed = urlParse(sourceMapURL);
  63378. if (!parsed) {
  63379. throw new Error("sourceMapURL could not be parsed");
  63380. }
  63381. if (parsed.path) {
  63382. // Strip the last path component, but keep the "/".
  63383. var index = parsed.path.lastIndexOf('/');
  63384. if (index >= 0) {
  63385. parsed.path = parsed.path.substring(0, index + 1);
  63386. }
  63387. }
  63388. sourceURL = join(urlGenerate(parsed), sourceURL);
  63389. }
  63390. return normalize(sourceURL);
  63391. }
  63392. exports.computeSourceURL = computeSourceURL;
  63393. }(util$5));
  63394. var arraySet = {};
  63395. /* -*- Mode: js; js-indent-level: 2; -*- */
  63396. /*
  63397. * Copyright 2011 Mozilla Foundation and contributors
  63398. * Licensed under the New BSD license. See LICENSE or:
  63399. * http://opensource.org/licenses/BSD-3-Clause
  63400. */
  63401. var util$4 = util$5;
  63402. var has = Object.prototype.hasOwnProperty;
  63403. var hasNativeMap = typeof Map !== "undefined";
  63404. /**
  63405. * A data structure which is a combination of an array and a set. Adding a new
  63406. * member is O(1), testing for membership is O(1), and finding the index of an
  63407. * element is O(1). Removing elements from the set is not supported. Only
  63408. * strings are supported for membership.
  63409. */
  63410. function ArraySet$2() {
  63411. this._array = [];
  63412. this._set = hasNativeMap ? new Map() : Object.create(null);
  63413. }
  63414. /**
  63415. * Static method for creating ArraySet instances from an existing array.
  63416. */
  63417. ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  63418. var set = new ArraySet$2();
  63419. for (var i = 0, len = aArray.length; i < len; i++) {
  63420. set.add(aArray[i], aAllowDuplicates);
  63421. }
  63422. return set;
  63423. };
  63424. /**
  63425. * Return how many unique items are in this ArraySet. If duplicates have been
  63426. * added, than those do not count towards the size.
  63427. *
  63428. * @returns Number
  63429. */
  63430. ArraySet$2.prototype.size = function ArraySet_size() {
  63431. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  63432. };
  63433. /**
  63434. * Add the given string to this set.
  63435. *
  63436. * @param String aStr
  63437. */
  63438. ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  63439. var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr);
  63440. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  63441. var idx = this._array.length;
  63442. if (!isDuplicate || aAllowDuplicates) {
  63443. this._array.push(aStr);
  63444. }
  63445. if (!isDuplicate) {
  63446. if (hasNativeMap) {
  63447. this._set.set(aStr, idx);
  63448. } else {
  63449. this._set[sStr] = idx;
  63450. }
  63451. }
  63452. };
  63453. /**
  63454. * Is the given string a member of this set?
  63455. *
  63456. * @param String aStr
  63457. */
  63458. ArraySet$2.prototype.has = function ArraySet_has(aStr) {
  63459. if (hasNativeMap) {
  63460. return this._set.has(aStr);
  63461. } else {
  63462. var sStr = util$4.toSetString(aStr);
  63463. return has.call(this._set, sStr);
  63464. }
  63465. };
  63466. /**
  63467. * What is the index of the given string in the array?
  63468. *
  63469. * @param String aStr
  63470. */
  63471. ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) {
  63472. if (hasNativeMap) {
  63473. var idx = this._set.get(aStr);
  63474. if (idx >= 0) {
  63475. return idx;
  63476. }
  63477. } else {
  63478. var sStr = util$4.toSetString(aStr);
  63479. if (has.call(this._set, sStr)) {
  63480. return this._set[sStr];
  63481. }
  63482. }
  63483. throw new Error('"' + aStr + '" is not in the set.');
  63484. };
  63485. /**
  63486. * What is the element at the given index?
  63487. *
  63488. * @param Number aIdx
  63489. */
  63490. ArraySet$2.prototype.at = function ArraySet_at(aIdx) {
  63491. if (aIdx >= 0 && aIdx < this._array.length) {
  63492. return this._array[aIdx];
  63493. }
  63494. throw new Error('No element indexed by ' + aIdx);
  63495. };
  63496. /**
  63497. * Returns the array representation of this set (which has the proper indices
  63498. * indicated by indexOf). Note that this is a copy of the internal array used
  63499. * for storing the members so that no one can mess with internal state.
  63500. */
  63501. ArraySet$2.prototype.toArray = function ArraySet_toArray() {
  63502. return this._array.slice();
  63503. };
  63504. arraySet.ArraySet = ArraySet$2;
  63505. var mappingList = {};
  63506. /* -*- Mode: js; js-indent-level: 2; -*- */
  63507. /*
  63508. * Copyright 2014 Mozilla Foundation and contributors
  63509. * Licensed under the New BSD license. See LICENSE or:
  63510. * http://opensource.org/licenses/BSD-3-Clause
  63511. */
  63512. var util$3 = util$5;
  63513. /**
  63514. * Determine whether mappingB is after mappingA with respect to generated
  63515. * position.
  63516. */
  63517. function generatedPositionAfter(mappingA, mappingB) {
  63518. // Optimized for most common case
  63519. var lineA = mappingA.generatedLine;
  63520. var lineB = mappingB.generatedLine;
  63521. var columnA = mappingA.generatedColumn;
  63522. var columnB = mappingB.generatedColumn;
  63523. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  63524. util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  63525. }
  63526. /**
  63527. * A data structure to provide a sorted view of accumulated mappings in a
  63528. * performance conscious manner. It trades a neglibable overhead in general
  63529. * case for a large speedup in case of mappings being added in order.
  63530. */
  63531. function MappingList$1() {
  63532. this._array = [];
  63533. this._sorted = true;
  63534. // Serves as infimum
  63535. this._last = {generatedLine: -1, generatedColumn: 0};
  63536. }
  63537. /**
  63538. * Iterate through internal items. This method takes the same arguments that
  63539. * `Array.prototype.forEach` takes.
  63540. *
  63541. * NOTE: The order of the mappings is NOT guaranteed.
  63542. */
  63543. MappingList$1.prototype.unsortedForEach =
  63544. function MappingList_forEach(aCallback, aThisArg) {
  63545. this._array.forEach(aCallback, aThisArg);
  63546. };
  63547. /**
  63548. * Add the given source mapping.
  63549. *
  63550. * @param Object aMapping
  63551. */
  63552. MappingList$1.prototype.add = function MappingList_add(aMapping) {
  63553. if (generatedPositionAfter(this._last, aMapping)) {
  63554. this._last = aMapping;
  63555. this._array.push(aMapping);
  63556. } else {
  63557. this._sorted = false;
  63558. this._array.push(aMapping);
  63559. }
  63560. };
  63561. /**
  63562. * Returns the flat, sorted array of mappings. The mappings are sorted by
  63563. * generated position.
  63564. *
  63565. * WARNING: This method returns internal data without copying, for
  63566. * performance. The return value must NOT be mutated, and should be treated as
  63567. * an immutable borrow. If you want to take ownership, you must make your own
  63568. * copy.
  63569. */
  63570. MappingList$1.prototype.toArray = function MappingList_toArray() {
  63571. if (!this._sorted) {
  63572. this._array.sort(util$3.compareByGeneratedPositionsInflated);
  63573. this._sorted = true;
  63574. }
  63575. return this._array;
  63576. };
  63577. mappingList.MappingList = MappingList$1;
  63578. /* -*- Mode: js; js-indent-level: 2; -*- */
  63579. /*
  63580. * Copyright 2011 Mozilla Foundation and contributors
  63581. * Licensed under the New BSD license. See LICENSE or:
  63582. * http://opensource.org/licenses/BSD-3-Clause
  63583. */
  63584. var base64VLQ$1 = base64Vlq;
  63585. var util$2 = util$5;
  63586. var ArraySet$1 = arraySet.ArraySet;
  63587. var MappingList = mappingList.MappingList;
  63588. /**
  63589. * An instance of the SourceMapGenerator represents a source map which is
  63590. * being built incrementally. You may pass an object with the following
  63591. * properties:
  63592. *
  63593. * - file: The filename of the generated source.
  63594. * - sourceRoot: A root for all relative URLs in this source map.
  63595. */
  63596. function SourceMapGenerator$1(aArgs) {
  63597. if (!aArgs) {
  63598. aArgs = {};
  63599. }
  63600. this._file = util$2.getArg(aArgs, 'file', null);
  63601. this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null);
  63602. this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false);
  63603. this._sources = new ArraySet$1();
  63604. this._names = new ArraySet$1();
  63605. this._mappings = new MappingList();
  63606. this._sourcesContents = null;
  63607. }
  63608. SourceMapGenerator$1.prototype._version = 3;
  63609. /**
  63610. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  63611. *
  63612. * @param aSourceMapConsumer The SourceMap.
  63613. */
  63614. SourceMapGenerator$1.fromSourceMap =
  63615. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  63616. var sourceRoot = aSourceMapConsumer.sourceRoot;
  63617. var generator = new SourceMapGenerator$1({
  63618. file: aSourceMapConsumer.file,
  63619. sourceRoot: sourceRoot
  63620. });
  63621. aSourceMapConsumer.eachMapping(function (mapping) {
  63622. var newMapping = {
  63623. generated: {
  63624. line: mapping.generatedLine,
  63625. column: mapping.generatedColumn
  63626. }
  63627. };
  63628. if (mapping.source != null) {
  63629. newMapping.source = mapping.source;
  63630. if (sourceRoot != null) {
  63631. newMapping.source = util$2.relative(sourceRoot, newMapping.source);
  63632. }
  63633. newMapping.original = {
  63634. line: mapping.originalLine,
  63635. column: mapping.originalColumn
  63636. };
  63637. if (mapping.name != null) {
  63638. newMapping.name = mapping.name;
  63639. }
  63640. }
  63641. generator.addMapping(newMapping);
  63642. });
  63643. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  63644. var sourceRelative = sourceFile;
  63645. if (sourceRoot !== null) {
  63646. sourceRelative = util$2.relative(sourceRoot, sourceFile);
  63647. }
  63648. if (!generator._sources.has(sourceRelative)) {
  63649. generator._sources.add(sourceRelative);
  63650. }
  63651. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  63652. if (content != null) {
  63653. generator.setSourceContent(sourceFile, content);
  63654. }
  63655. });
  63656. return generator;
  63657. };
  63658. /**
  63659. * Add a single mapping from original source line and column to the generated
  63660. * source's line and column for this source map being created. The mapping
  63661. * object should have the following properties:
  63662. *
  63663. * - generated: An object with the generated line and column positions.
  63664. * - original: An object with the original line and column positions.
  63665. * - source: The original source file (relative to the sourceRoot).
  63666. * - name: An optional original token name for this mapping.
  63667. */
  63668. SourceMapGenerator$1.prototype.addMapping =
  63669. function SourceMapGenerator_addMapping(aArgs) {
  63670. var generated = util$2.getArg(aArgs, 'generated');
  63671. var original = util$2.getArg(aArgs, 'original', null);
  63672. var source = util$2.getArg(aArgs, 'source', null);
  63673. var name = util$2.getArg(aArgs, 'name', null);
  63674. if (!this._skipValidation) {
  63675. this._validateMapping(generated, original, source, name);
  63676. }
  63677. if (source != null) {
  63678. source = String(source);
  63679. if (!this._sources.has(source)) {
  63680. this._sources.add(source);
  63681. }
  63682. }
  63683. if (name != null) {
  63684. name = String(name);
  63685. if (!this._names.has(name)) {
  63686. this._names.add(name);
  63687. }
  63688. }
  63689. this._mappings.add({
  63690. generatedLine: generated.line,
  63691. generatedColumn: generated.column,
  63692. originalLine: original != null && original.line,
  63693. originalColumn: original != null && original.column,
  63694. source: source,
  63695. name: name
  63696. });
  63697. };
  63698. /**
  63699. * Set the source content for a source file.
  63700. */
  63701. SourceMapGenerator$1.prototype.setSourceContent =
  63702. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  63703. var source = aSourceFile;
  63704. if (this._sourceRoot != null) {
  63705. source = util$2.relative(this._sourceRoot, source);
  63706. }
  63707. if (aSourceContent != null) {
  63708. // Add the source content to the _sourcesContents map.
  63709. // Create a new _sourcesContents map if the property is null.
  63710. if (!this._sourcesContents) {
  63711. this._sourcesContents = Object.create(null);
  63712. }
  63713. this._sourcesContents[util$2.toSetString(source)] = aSourceContent;
  63714. } else if (this._sourcesContents) {
  63715. // Remove the source file from the _sourcesContents map.
  63716. // If the _sourcesContents map is empty, set the property to null.
  63717. delete this._sourcesContents[util$2.toSetString(source)];
  63718. if (Object.keys(this._sourcesContents).length === 0) {
  63719. this._sourcesContents = null;
  63720. }
  63721. }
  63722. };
  63723. /**
  63724. * Applies the mappings of a sub-source-map for a specific source file to the
  63725. * source map being generated. Each mapping to the supplied source file is
  63726. * rewritten using the supplied source map. Note: The resolution for the
  63727. * resulting mappings is the minimium of this map and the supplied map.
  63728. *
  63729. * @param aSourceMapConsumer The source map to be applied.
  63730. * @param aSourceFile Optional. The filename of the source file.
  63731. * If omitted, SourceMapConsumer's file property will be used.
  63732. * @param aSourceMapPath Optional. The dirname of the path to the source map
  63733. * to be applied. If relative, it is relative to the SourceMapConsumer.
  63734. * This parameter is needed when the two source maps aren't in the same
  63735. * directory, and the source map to be applied contains relative source
  63736. * paths. If so, those relative source paths need to be rewritten
  63737. * relative to the SourceMapGenerator.
  63738. */
  63739. SourceMapGenerator$1.prototype.applySourceMap =
  63740. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  63741. var sourceFile = aSourceFile;
  63742. // If aSourceFile is omitted, we will use the file property of the SourceMap
  63743. if (aSourceFile == null) {
  63744. if (aSourceMapConsumer.file == null) {
  63745. throw new Error(
  63746. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  63747. 'or the source map\'s "file" property. Both were omitted.'
  63748. );
  63749. }
  63750. sourceFile = aSourceMapConsumer.file;
  63751. }
  63752. var sourceRoot = this._sourceRoot;
  63753. // Make "sourceFile" relative if an absolute Url is passed.
  63754. if (sourceRoot != null) {
  63755. sourceFile = util$2.relative(sourceRoot, sourceFile);
  63756. }
  63757. // Applying the SourceMap can add and remove items from the sources and
  63758. // the names array.
  63759. var newSources = new ArraySet$1();
  63760. var newNames = new ArraySet$1();
  63761. // Find mappings for the "sourceFile"
  63762. this._mappings.unsortedForEach(function (mapping) {
  63763. if (mapping.source === sourceFile && mapping.originalLine != null) {
  63764. // Check if it can be mapped by the source map, then update the mapping.
  63765. var original = aSourceMapConsumer.originalPositionFor({
  63766. line: mapping.originalLine,
  63767. column: mapping.originalColumn
  63768. });
  63769. if (original.source != null) {
  63770. // Copy mapping
  63771. mapping.source = original.source;
  63772. if (aSourceMapPath != null) {
  63773. mapping.source = util$2.join(aSourceMapPath, mapping.source);
  63774. }
  63775. if (sourceRoot != null) {
  63776. mapping.source = util$2.relative(sourceRoot, mapping.source);
  63777. }
  63778. mapping.originalLine = original.line;
  63779. mapping.originalColumn = original.column;
  63780. if (original.name != null) {
  63781. mapping.name = original.name;
  63782. }
  63783. }
  63784. }
  63785. var source = mapping.source;
  63786. if (source != null && !newSources.has(source)) {
  63787. newSources.add(source);
  63788. }
  63789. var name = mapping.name;
  63790. if (name != null && !newNames.has(name)) {
  63791. newNames.add(name);
  63792. }
  63793. }, this);
  63794. this._sources = newSources;
  63795. this._names = newNames;
  63796. // Copy sourcesContents of applied map.
  63797. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  63798. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  63799. if (content != null) {
  63800. if (aSourceMapPath != null) {
  63801. sourceFile = util$2.join(aSourceMapPath, sourceFile);
  63802. }
  63803. if (sourceRoot != null) {
  63804. sourceFile = util$2.relative(sourceRoot, sourceFile);
  63805. }
  63806. this.setSourceContent(sourceFile, content);
  63807. }
  63808. }, this);
  63809. };
  63810. /**
  63811. * A mapping can have one of the three levels of data:
  63812. *
  63813. * 1. Just the generated position.
  63814. * 2. The Generated position, original position, and original source.
  63815. * 3. Generated and original position, original source, as well as a name
  63816. * token.
  63817. *
  63818. * To maintain consistency, we validate that any new mapping being added falls
  63819. * in to one of these categories.
  63820. */
  63821. SourceMapGenerator$1.prototype._validateMapping =
  63822. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  63823. aName) {
  63824. // When aOriginal is truthy but has empty values for .line and .column,
  63825. // it is most likely a programmer error. In this case we throw a very
  63826. // specific error message to try to guide them the right way.
  63827. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  63828. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  63829. throw new Error(
  63830. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  63831. 'the original mapping entirely and only map the generated position. If so, pass ' +
  63832. 'null for the original mapping instead of an object with empty or null values.'
  63833. );
  63834. }
  63835. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  63836. && aGenerated.line > 0 && aGenerated.column >= 0
  63837. && !aOriginal && !aSource && !aName) {
  63838. // Case 1.
  63839. return;
  63840. }
  63841. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  63842. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  63843. && aGenerated.line > 0 && aGenerated.column >= 0
  63844. && aOriginal.line > 0 && aOriginal.column >= 0
  63845. && aSource) {
  63846. // Cases 2 and 3.
  63847. return;
  63848. }
  63849. else {
  63850. throw new Error('Invalid mapping: ' + JSON.stringify({
  63851. generated: aGenerated,
  63852. source: aSource,
  63853. original: aOriginal,
  63854. name: aName
  63855. }));
  63856. }
  63857. };
  63858. /**
  63859. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  63860. * specified by the source map format.
  63861. */
  63862. SourceMapGenerator$1.prototype._serializeMappings =
  63863. function SourceMapGenerator_serializeMappings() {
  63864. var previousGeneratedColumn = 0;
  63865. var previousGeneratedLine = 1;
  63866. var previousOriginalColumn = 0;
  63867. var previousOriginalLine = 0;
  63868. var previousName = 0;
  63869. var previousSource = 0;
  63870. var result = '';
  63871. var next;
  63872. var mapping;
  63873. var nameIdx;
  63874. var sourceIdx;
  63875. var mappings = this._mappings.toArray();
  63876. for (var i = 0, len = mappings.length; i < len; i++) {
  63877. mapping = mappings[i];
  63878. next = '';
  63879. if (mapping.generatedLine !== previousGeneratedLine) {
  63880. previousGeneratedColumn = 0;
  63881. while (mapping.generatedLine !== previousGeneratedLine) {
  63882. next += ';';
  63883. previousGeneratedLine++;
  63884. }
  63885. }
  63886. else {
  63887. if (i > 0) {
  63888. if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  63889. continue;
  63890. }
  63891. next += ',';
  63892. }
  63893. }
  63894. next += base64VLQ$1.encode(mapping.generatedColumn
  63895. - previousGeneratedColumn);
  63896. previousGeneratedColumn = mapping.generatedColumn;
  63897. if (mapping.source != null) {
  63898. sourceIdx = this._sources.indexOf(mapping.source);
  63899. next += base64VLQ$1.encode(sourceIdx - previousSource);
  63900. previousSource = sourceIdx;
  63901. // lines are stored 0-based in SourceMap spec version 3
  63902. next += base64VLQ$1.encode(mapping.originalLine - 1
  63903. - previousOriginalLine);
  63904. previousOriginalLine = mapping.originalLine - 1;
  63905. next += base64VLQ$1.encode(mapping.originalColumn
  63906. - previousOriginalColumn);
  63907. previousOriginalColumn = mapping.originalColumn;
  63908. if (mapping.name != null) {
  63909. nameIdx = this._names.indexOf(mapping.name);
  63910. next += base64VLQ$1.encode(nameIdx - previousName);
  63911. previousName = nameIdx;
  63912. }
  63913. }
  63914. result += next;
  63915. }
  63916. return result;
  63917. };
  63918. SourceMapGenerator$1.prototype._generateSourcesContent =
  63919. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  63920. return aSources.map(function (source) {
  63921. if (!this._sourcesContents) {
  63922. return null;
  63923. }
  63924. if (aSourceRoot != null) {
  63925. source = util$2.relative(aSourceRoot, source);
  63926. }
  63927. var key = util$2.toSetString(source);
  63928. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  63929. ? this._sourcesContents[key]
  63930. : null;
  63931. }, this);
  63932. };
  63933. /**
  63934. * Externalize the source map.
  63935. */
  63936. SourceMapGenerator$1.prototype.toJSON =
  63937. function SourceMapGenerator_toJSON() {
  63938. var map = {
  63939. version: this._version,
  63940. sources: this._sources.toArray(),
  63941. names: this._names.toArray(),
  63942. mappings: this._serializeMappings()
  63943. };
  63944. if (this._file != null) {
  63945. map.file = this._file;
  63946. }
  63947. if (this._sourceRoot != null) {
  63948. map.sourceRoot = this._sourceRoot;
  63949. }
  63950. if (this._sourcesContents) {
  63951. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  63952. }
  63953. return map;
  63954. };
  63955. /**
  63956. * Render the source map being generated to a string.
  63957. */
  63958. SourceMapGenerator$1.prototype.toString =
  63959. function SourceMapGenerator_toString() {
  63960. return JSON.stringify(this.toJSON());
  63961. };
  63962. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$1;
  63963. var sourceMapConsumer = {};
  63964. var binarySearch$1 = {};
  63965. /* -*- Mode: js; js-indent-level: 2; -*- */
  63966. (function (exports) {
  63967. /*
  63968. * Copyright 2011 Mozilla Foundation and contributors
  63969. * Licensed under the New BSD license. See LICENSE or:
  63970. * http://opensource.org/licenses/BSD-3-Clause
  63971. */
  63972. exports.GREATEST_LOWER_BOUND = 1;
  63973. exports.LEAST_UPPER_BOUND = 2;
  63974. /**
  63975. * Recursive implementation of binary search.
  63976. *
  63977. * @param aLow Indices here and lower do not contain the needle.
  63978. * @param aHigh Indices here and higher do not contain the needle.
  63979. * @param aNeedle The element being searched for.
  63980. * @param aHaystack The non-empty array being searched.
  63981. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  63982. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  63983. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  63984. * closest element that is smaller than or greater than the one we are
  63985. * searching for, respectively, if the exact element cannot be found.
  63986. */
  63987. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  63988. // This function terminates when one of the following is true:
  63989. //
  63990. // 1. We find the exact element we are looking for.
  63991. //
  63992. // 2. We did not find the exact element, but we can return the index of
  63993. // the next-closest element.
  63994. //
  63995. // 3. We did not find the exact element, and there is no next-closest
  63996. // element than the one we are searching for, so we return -1.
  63997. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  63998. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  63999. if (cmp === 0) {
  64000. // Found the element we are looking for.
  64001. return mid;
  64002. }
  64003. else if (cmp > 0) {
  64004. // Our needle is greater than aHaystack[mid].
  64005. if (aHigh - mid > 1) {
  64006. // The element is in the upper half.
  64007. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  64008. }
  64009. // The exact needle element was not found in this haystack. Determine if
  64010. // we are in termination case (3) or (2) and return the appropriate thing.
  64011. if (aBias == exports.LEAST_UPPER_BOUND) {
  64012. return aHigh < aHaystack.length ? aHigh : -1;
  64013. } else {
  64014. return mid;
  64015. }
  64016. }
  64017. else {
  64018. // Our needle is less than aHaystack[mid].
  64019. if (mid - aLow > 1) {
  64020. // The element is in the lower half.
  64021. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  64022. }
  64023. // we are in termination case (3) or (2) and return the appropriate thing.
  64024. if (aBias == exports.LEAST_UPPER_BOUND) {
  64025. return mid;
  64026. } else {
  64027. return aLow < 0 ? -1 : aLow;
  64028. }
  64029. }
  64030. }
  64031. /**
  64032. * This is an implementation of binary search which will always try and return
  64033. * the index of the closest element if there is no exact hit. This is because
  64034. * mappings between original and generated line/col pairs are single points,
  64035. * and there is an implicit region between each of them, so a miss just means
  64036. * that you aren't on the very start of a region.
  64037. *
  64038. * @param aNeedle The element you are looking for.
  64039. * @param aHaystack The array that is being searched.
  64040. * @param aCompare A function which takes the needle and an element in the
  64041. * array and returns -1, 0, or 1 depending on whether the needle is less
  64042. * than, equal to, or greater than the element, respectively.
  64043. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  64044. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  64045. * closest element that is smaller than or greater than the one we are
  64046. * searching for, respectively, if the exact element cannot be found.
  64047. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  64048. */
  64049. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  64050. if (aHaystack.length === 0) {
  64051. return -1;
  64052. }
  64053. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  64054. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  64055. if (index < 0) {
  64056. return -1;
  64057. }
  64058. // We have found either the exact element, or the next-closest element than
  64059. // the one we are searching for. However, there may be more than one such
  64060. // element. Make sure we always return the smallest of these.
  64061. while (index - 1 >= 0) {
  64062. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  64063. break;
  64064. }
  64065. --index;
  64066. }
  64067. return index;
  64068. };
  64069. }(binarySearch$1));
  64070. var quickSort$1 = {};
  64071. /* -*- Mode: js; js-indent-level: 2; -*- */
  64072. /*
  64073. * Copyright 2011 Mozilla Foundation and contributors
  64074. * Licensed under the New BSD license. See LICENSE or:
  64075. * http://opensource.org/licenses/BSD-3-Clause
  64076. */
  64077. // It turns out that some (most?) JavaScript engines don't self-host
  64078. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  64079. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  64080. // custom comparator function, calling back and forth between the VM's C++ and
  64081. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  64082. // worse generated code for the comparator function than would be optimal. In
  64083. // fact, when sorting with a comparator, these costs outweigh the benefits of
  64084. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  64085. // a ~3500ms mean speed-up in `bench/bench.html`.
  64086. /**
  64087. * Swap the elements indexed by `x` and `y` in the array `ary`.
  64088. *
  64089. * @param {Array} ary
  64090. * The array.
  64091. * @param {Number} x
  64092. * The index of the first item.
  64093. * @param {Number} y
  64094. * The index of the second item.
  64095. */
  64096. function swap(ary, x, y) {
  64097. var temp = ary[x];
  64098. ary[x] = ary[y];
  64099. ary[y] = temp;
  64100. }
  64101. /**
  64102. * Returns a random integer within the range `low .. high` inclusive.
  64103. *
  64104. * @param {Number} low
  64105. * The lower bound on the range.
  64106. * @param {Number} high
  64107. * The upper bound on the range.
  64108. */
  64109. function randomIntInRange(low, high) {
  64110. return Math.round(low + (Math.random() * (high - low)));
  64111. }
  64112. /**
  64113. * The Quick Sort algorithm.
  64114. *
  64115. * @param {Array} ary
  64116. * An array to sort.
  64117. * @param {function} comparator
  64118. * Function to use to compare two items.
  64119. * @param {Number} p
  64120. * Start index of the array
  64121. * @param {Number} r
  64122. * End index of the array
  64123. */
  64124. function doQuickSort(ary, comparator, p, r) {
  64125. // If our lower bound is less than our upper bound, we (1) partition the
  64126. // array into two pieces and (2) recurse on each half. If it is not, this is
  64127. // the empty array and our base case.
  64128. if (p < r) {
  64129. // (1) Partitioning.
  64130. //
  64131. // The partitioning chooses a pivot between `p` and `r` and moves all
  64132. // elements that are less than or equal to the pivot to the before it, and
  64133. // all the elements that are greater than it after it. The effect is that
  64134. // once partition is done, the pivot is in the exact place it will be when
  64135. // the array is put in sorted order, and it will not need to be moved
  64136. // again. This runs in O(n) time.
  64137. // Always choose a random pivot so that an input array which is reverse
  64138. // sorted does not cause O(n^2) running time.
  64139. var pivotIndex = randomIntInRange(p, r);
  64140. var i = p - 1;
  64141. swap(ary, pivotIndex, r);
  64142. var pivot = ary[r];
  64143. // Immediately after `j` is incremented in this loop, the following hold
  64144. // true:
  64145. //
  64146. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  64147. //
  64148. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  64149. for (var j = p; j < r; j++) {
  64150. if (comparator(ary[j], pivot) <= 0) {
  64151. i += 1;
  64152. swap(ary, i, j);
  64153. }
  64154. }
  64155. swap(ary, i + 1, j);
  64156. var q = i + 1;
  64157. // (2) Recurse on each half.
  64158. doQuickSort(ary, comparator, p, q - 1);
  64159. doQuickSort(ary, comparator, q + 1, r);
  64160. }
  64161. }
  64162. /**
  64163. * Sort the given array in-place with the given comparator function.
  64164. *
  64165. * @param {Array} ary
  64166. * An array to sort.
  64167. * @param {function} comparator
  64168. * Function to use to compare two items.
  64169. */
  64170. quickSort$1.quickSort = function (ary, comparator) {
  64171. doQuickSort(ary, comparator, 0, ary.length - 1);
  64172. };
  64173. /* -*- Mode: js; js-indent-level: 2; -*- */
  64174. /*
  64175. * Copyright 2011 Mozilla Foundation and contributors
  64176. * Licensed under the New BSD license. See LICENSE or:
  64177. * http://opensource.org/licenses/BSD-3-Clause
  64178. */
  64179. var util$1 = util$5;
  64180. var binarySearch = binarySearch$1;
  64181. var ArraySet = arraySet.ArraySet;
  64182. var base64VLQ = base64Vlq;
  64183. var quickSort = quickSort$1.quickSort;
  64184. function SourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  64185. var sourceMap = aSourceMap;
  64186. if (typeof aSourceMap === 'string') {
  64187. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  64188. }
  64189. return sourceMap.sections != null
  64190. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  64191. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  64192. }
  64193. SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  64194. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  64195. };
  64196. /**
  64197. * The version of the source mapping spec that we are consuming.
  64198. */
  64199. SourceMapConsumer$1.prototype._version = 3;
  64200. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  64201. // parsed mapping coordinates from the source map's "mappings" attribute. They
  64202. // are lazily instantiated, accessed via the `_generatedMappings` and
  64203. // `_originalMappings` getters respectively, and we only parse the mappings
  64204. // and create these arrays once queried for a source location. We jump through
  64205. // these hoops because there can be many thousands of mappings, and parsing
  64206. // them is expensive, so we only want to do it if we must.
  64207. //
  64208. // Each object in the arrays is of the form:
  64209. //
  64210. // {
  64211. // generatedLine: The line number in the generated code,
  64212. // generatedColumn: The column number in the generated code,
  64213. // source: The path to the original source file that generated this
  64214. // chunk of code,
  64215. // originalLine: The line number in the original source that
  64216. // corresponds to this chunk of generated code,
  64217. // originalColumn: The column number in the original source that
  64218. // corresponds to this chunk of generated code,
  64219. // name: The name of the original symbol which generated this chunk of
  64220. // code.
  64221. // }
  64222. //
  64223. // All properties except for `generatedLine` and `generatedColumn` can be
  64224. // `null`.
  64225. //
  64226. // `_generatedMappings` is ordered by the generated positions.
  64227. //
  64228. // `_originalMappings` is ordered by the original positions.
  64229. SourceMapConsumer$1.prototype.__generatedMappings = null;
  64230. Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', {
  64231. configurable: true,
  64232. enumerable: true,
  64233. get: function () {
  64234. if (!this.__generatedMappings) {
  64235. this._parseMappings(this._mappings, this.sourceRoot);
  64236. }
  64237. return this.__generatedMappings;
  64238. }
  64239. });
  64240. SourceMapConsumer$1.prototype.__originalMappings = null;
  64241. Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', {
  64242. configurable: true,
  64243. enumerable: true,
  64244. get: function () {
  64245. if (!this.__originalMappings) {
  64246. this._parseMappings(this._mappings, this.sourceRoot);
  64247. }
  64248. return this.__originalMappings;
  64249. }
  64250. });
  64251. SourceMapConsumer$1.prototype._charIsMappingSeparator =
  64252. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  64253. var c = aStr.charAt(index);
  64254. return c === ";" || c === ",";
  64255. };
  64256. /**
  64257. * Parse the mappings in a string in to a data structure which we can easily
  64258. * query (the ordered arrays in the `this.__generatedMappings` and
  64259. * `this.__originalMappings` properties).
  64260. */
  64261. SourceMapConsumer$1.prototype._parseMappings =
  64262. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  64263. throw new Error("Subclasses must implement _parseMappings");
  64264. };
  64265. SourceMapConsumer$1.GENERATED_ORDER = 1;
  64266. SourceMapConsumer$1.ORIGINAL_ORDER = 2;
  64267. SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1;
  64268. SourceMapConsumer$1.LEAST_UPPER_BOUND = 2;
  64269. /**
  64270. * Iterate over each mapping between an original source/line/column and a
  64271. * generated line/column in this source map.
  64272. *
  64273. * @param Function aCallback
  64274. * The function that is called with each mapping.
  64275. * @param Object aContext
  64276. * Optional. If specified, this object will be the value of `this` every
  64277. * time that `aCallback` is called.
  64278. * @param aOrder
  64279. * Either `SourceMapConsumer.GENERATED_ORDER` or
  64280. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  64281. * iterate over the mappings sorted by the generated file's line/column
  64282. * order or the original's source/line/column order, respectively. Defaults to
  64283. * `SourceMapConsumer.GENERATED_ORDER`.
  64284. */
  64285. SourceMapConsumer$1.prototype.eachMapping =
  64286. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  64287. var context = aContext || null;
  64288. var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;
  64289. var mappings;
  64290. switch (order) {
  64291. case SourceMapConsumer$1.GENERATED_ORDER:
  64292. mappings = this._generatedMappings;
  64293. break;
  64294. case SourceMapConsumer$1.ORIGINAL_ORDER:
  64295. mappings = this._originalMappings;
  64296. break;
  64297. default:
  64298. throw new Error("Unknown order of iteration.");
  64299. }
  64300. var sourceRoot = this.sourceRoot;
  64301. mappings.map(function (mapping) {
  64302. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  64303. source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  64304. return {
  64305. source: source,
  64306. generatedLine: mapping.generatedLine,
  64307. generatedColumn: mapping.generatedColumn,
  64308. originalLine: mapping.originalLine,
  64309. originalColumn: mapping.originalColumn,
  64310. name: mapping.name === null ? null : this._names.at(mapping.name)
  64311. };
  64312. }, this).forEach(aCallback, context);
  64313. };
  64314. /**
  64315. * Returns all generated line and column information for the original source,
  64316. * line, and column provided. If no column is provided, returns all mappings
  64317. * corresponding to a either the line we are searching for or the next
  64318. * closest line that has any mappings. Otherwise, returns all mappings
  64319. * corresponding to the given line and either the column we are searching for
  64320. * or the next closest column that has any offsets.
  64321. *
  64322. * The only argument is an object with the following properties:
  64323. *
  64324. * - source: The filename of the original source.
  64325. * - line: The line number in the original source. The line number is 1-based.
  64326. * - column: Optional. the column number in the original source.
  64327. * The column number is 0-based.
  64328. *
  64329. * and an array of objects is returned, each with the following properties:
  64330. *
  64331. * - line: The line number in the generated source, or null. The
  64332. * line number is 1-based.
  64333. * - column: The column number in the generated source, or null.
  64334. * The column number is 0-based.
  64335. */
  64336. SourceMapConsumer$1.prototype.allGeneratedPositionsFor =
  64337. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  64338. var line = util$1.getArg(aArgs, 'line');
  64339. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  64340. // returns the index of the closest mapping less than the needle. By
  64341. // setting needle.originalColumn to 0, we thus find the last mapping for
  64342. // the given line, provided such a mapping exists.
  64343. var needle = {
  64344. source: util$1.getArg(aArgs, 'source'),
  64345. originalLine: line,
  64346. originalColumn: util$1.getArg(aArgs, 'column', 0)
  64347. };
  64348. needle.source = this._findSourceIndex(needle.source);
  64349. if (needle.source < 0) {
  64350. return [];
  64351. }
  64352. var mappings = [];
  64353. var index = this._findMapping(needle,
  64354. this._originalMappings,
  64355. "originalLine",
  64356. "originalColumn",
  64357. util$1.compareByOriginalPositions,
  64358. binarySearch.LEAST_UPPER_BOUND);
  64359. if (index >= 0) {
  64360. var mapping = this._originalMappings[index];
  64361. if (aArgs.column === undefined) {
  64362. var originalLine = mapping.originalLine;
  64363. // Iterate until either we run out of mappings, or we run into
  64364. // a mapping for a different line than the one we found. Since
  64365. // mappings are sorted, this is guaranteed to find all mappings for
  64366. // the line we found.
  64367. while (mapping && mapping.originalLine === originalLine) {
  64368. mappings.push({
  64369. line: util$1.getArg(mapping, 'generatedLine', null),
  64370. column: util$1.getArg(mapping, 'generatedColumn', null),
  64371. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  64372. });
  64373. mapping = this._originalMappings[++index];
  64374. }
  64375. } else {
  64376. var originalColumn = mapping.originalColumn;
  64377. // Iterate until either we run out of mappings, or we run into
  64378. // a mapping for a different line than the one we were searching for.
  64379. // Since mappings are sorted, this is guaranteed to find all mappings for
  64380. // the line we are searching for.
  64381. while (mapping &&
  64382. mapping.originalLine === line &&
  64383. mapping.originalColumn == originalColumn) {
  64384. mappings.push({
  64385. line: util$1.getArg(mapping, 'generatedLine', null),
  64386. column: util$1.getArg(mapping, 'generatedColumn', null),
  64387. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  64388. });
  64389. mapping = this._originalMappings[++index];
  64390. }
  64391. }
  64392. }
  64393. return mappings;
  64394. };
  64395. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1;
  64396. /**
  64397. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  64398. * query for information about the original file positions by giving it a file
  64399. * position in the generated source.
  64400. *
  64401. * The first parameter is the raw source map (either as a JSON string, or
  64402. * already parsed to an object). According to the spec, source maps have the
  64403. * following attributes:
  64404. *
  64405. * - version: Which version of the source map spec this map is following.
  64406. * - sources: An array of URLs to the original source files.
  64407. * - names: An array of identifiers which can be referrenced by individual mappings.
  64408. * - sourceRoot: Optional. The URL root from which all sources are relative.
  64409. * - sourcesContent: Optional. An array of contents of the original source files.
  64410. * - mappings: A string of base64 VLQs which contain the actual mappings.
  64411. * - file: Optional. The generated file this source map is associated with.
  64412. *
  64413. * Here is an example source map, taken from the source map spec[0]:
  64414. *
  64415. * {
  64416. * version : 3,
  64417. * file: "out.js",
  64418. * sourceRoot : "",
  64419. * sources: ["foo.js", "bar.js"],
  64420. * names: ["src", "maps", "are", "fun"],
  64421. * mappings: "AA,AB;;ABCDE;"
  64422. * }
  64423. *
  64424. * The second parameter, if given, is a string whose value is the URL
  64425. * at which the source map was found. This URL is used to compute the
  64426. * sources array.
  64427. *
  64428. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  64429. */
  64430. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  64431. var sourceMap = aSourceMap;
  64432. if (typeof aSourceMap === 'string') {
  64433. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  64434. }
  64435. var version = util$1.getArg(sourceMap, 'version');
  64436. var sources = util$1.getArg(sourceMap, 'sources');
  64437. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  64438. // requires the array) to play nice here.
  64439. var names = util$1.getArg(sourceMap, 'names', []);
  64440. var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
  64441. var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
  64442. var mappings = util$1.getArg(sourceMap, 'mappings');
  64443. var file = util$1.getArg(sourceMap, 'file', null);
  64444. // Once again, Sass deviates from the spec and supplies the version as a
  64445. // string rather than a number, so we use loose equality checking here.
  64446. if (version != this._version) {
  64447. throw new Error('Unsupported version: ' + version);
  64448. }
  64449. if (sourceRoot) {
  64450. sourceRoot = util$1.normalize(sourceRoot);
  64451. }
  64452. sources = sources
  64453. .map(String)
  64454. // Some source maps produce relative source paths like "./foo.js" instead of
  64455. // "foo.js". Normalize these first so that future comparisons will succeed.
  64456. // See bugzil.la/1090768.
  64457. .map(util$1.normalize)
  64458. // Always ensure that absolute sources are internally stored relative to
  64459. // the source root, if the source root is absolute. Not doing this would
  64460. // be particularly problematic when the source root is a prefix of the
  64461. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  64462. .map(function (source) {
  64463. return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
  64464. ? util$1.relative(sourceRoot, source)
  64465. : source;
  64466. });
  64467. // Pass `true` below to allow duplicate names and sources. While source maps
  64468. // are intended to be compressed and deduplicated, the TypeScript compiler
  64469. // sometimes generates source maps with duplicates in them. See Github issue
  64470. // #72 and bugzil.la/889492.
  64471. this._names = ArraySet.fromArray(names.map(String), true);
  64472. this._sources = ArraySet.fromArray(sources, true);
  64473. this._absoluteSources = this._sources.toArray().map(function (s) {
  64474. return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
  64475. });
  64476. this.sourceRoot = sourceRoot;
  64477. this.sourcesContent = sourcesContent;
  64478. this._mappings = mappings;
  64479. this._sourceMapURL = aSourceMapURL;
  64480. this.file = file;
  64481. }
  64482. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  64483. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1;
  64484. /**
  64485. * Utility function to find the index of a source. Returns -1 if not
  64486. * found.
  64487. */
  64488. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  64489. var relativeSource = aSource;
  64490. if (this.sourceRoot != null) {
  64491. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  64492. }
  64493. if (this._sources.has(relativeSource)) {
  64494. return this._sources.indexOf(relativeSource);
  64495. }
  64496. // Maybe aSource is an absolute URL as returned by |sources|. In
  64497. // this case we can't simply undo the transform.
  64498. var i;
  64499. for (i = 0; i < this._absoluteSources.length; ++i) {
  64500. if (this._absoluteSources[i] == aSource) {
  64501. return i;
  64502. }
  64503. }
  64504. return -1;
  64505. };
  64506. /**
  64507. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  64508. *
  64509. * @param SourceMapGenerator aSourceMap
  64510. * The source map that will be consumed.
  64511. * @param String aSourceMapURL
  64512. * The URL at which the source map can be found (optional)
  64513. * @returns BasicSourceMapConsumer
  64514. */
  64515. BasicSourceMapConsumer.fromSourceMap =
  64516. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  64517. var smc = Object.create(BasicSourceMapConsumer.prototype);
  64518. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  64519. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  64520. smc.sourceRoot = aSourceMap._sourceRoot;
  64521. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  64522. smc.sourceRoot);
  64523. smc.file = aSourceMap._file;
  64524. smc._sourceMapURL = aSourceMapURL;
  64525. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  64526. return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  64527. });
  64528. // Because we are modifying the entries (by converting string sources and
  64529. // names to indices into the sources and names ArraySets), we have to make
  64530. // a copy of the entry or else bad things happen. Shared mutable state
  64531. // strikes again! See github issue #191.
  64532. var generatedMappings = aSourceMap._mappings.toArray().slice();
  64533. var destGeneratedMappings = smc.__generatedMappings = [];
  64534. var destOriginalMappings = smc.__originalMappings = [];
  64535. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  64536. var srcMapping = generatedMappings[i];
  64537. var destMapping = new Mapping;
  64538. destMapping.generatedLine = srcMapping.generatedLine;
  64539. destMapping.generatedColumn = srcMapping.generatedColumn;
  64540. if (srcMapping.source) {
  64541. destMapping.source = sources.indexOf(srcMapping.source);
  64542. destMapping.originalLine = srcMapping.originalLine;
  64543. destMapping.originalColumn = srcMapping.originalColumn;
  64544. if (srcMapping.name) {
  64545. destMapping.name = names.indexOf(srcMapping.name);
  64546. }
  64547. destOriginalMappings.push(destMapping);
  64548. }
  64549. destGeneratedMappings.push(destMapping);
  64550. }
  64551. quickSort(smc.__originalMappings, util$1.compareByOriginalPositions);
  64552. return smc;
  64553. };
  64554. /**
  64555. * The version of the source mapping spec that we are consuming.
  64556. */
  64557. BasicSourceMapConsumer.prototype._version = 3;
  64558. /**
  64559. * The list of original sources.
  64560. */
  64561. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  64562. get: function () {
  64563. return this._absoluteSources.slice();
  64564. }
  64565. });
  64566. /**
  64567. * Provide the JIT with a nice shape / hidden class.
  64568. */
  64569. function Mapping() {
  64570. this.generatedLine = 0;
  64571. this.generatedColumn = 0;
  64572. this.source = null;
  64573. this.originalLine = null;
  64574. this.originalColumn = null;
  64575. this.name = null;
  64576. }
  64577. /**
  64578. * Parse the mappings in a string in to a data structure which we can easily
  64579. * query (the ordered arrays in the `this.__generatedMappings` and
  64580. * `this.__originalMappings` properties).
  64581. */
  64582. BasicSourceMapConsumer.prototype._parseMappings =
  64583. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  64584. var generatedLine = 1;
  64585. var previousGeneratedColumn = 0;
  64586. var previousOriginalLine = 0;
  64587. var previousOriginalColumn = 0;
  64588. var previousSource = 0;
  64589. var previousName = 0;
  64590. var length = aStr.length;
  64591. var index = 0;
  64592. var cachedSegments = {};
  64593. var temp = {};
  64594. var originalMappings = [];
  64595. var generatedMappings = [];
  64596. var mapping, str, segment, end, value;
  64597. while (index < length) {
  64598. if (aStr.charAt(index) === ';') {
  64599. generatedLine++;
  64600. index++;
  64601. previousGeneratedColumn = 0;
  64602. }
  64603. else if (aStr.charAt(index) === ',') {
  64604. index++;
  64605. }
  64606. else {
  64607. mapping = new Mapping();
  64608. mapping.generatedLine = generatedLine;
  64609. // Because each offset is encoded relative to the previous one,
  64610. // many segments often have the same encoding. We can exploit this
  64611. // fact by caching the parsed variable length fields of each segment,
  64612. // allowing us to avoid a second parse if we encounter the same
  64613. // segment again.
  64614. for (end = index; end < length; end++) {
  64615. if (this._charIsMappingSeparator(aStr, end)) {
  64616. break;
  64617. }
  64618. }
  64619. str = aStr.slice(index, end);
  64620. segment = cachedSegments[str];
  64621. if (segment) {
  64622. index += str.length;
  64623. } else {
  64624. segment = [];
  64625. while (index < end) {
  64626. base64VLQ.decode(aStr, index, temp);
  64627. value = temp.value;
  64628. index = temp.rest;
  64629. segment.push(value);
  64630. }
  64631. if (segment.length === 2) {
  64632. throw new Error('Found a source, but no line and column');
  64633. }
  64634. if (segment.length === 3) {
  64635. throw new Error('Found a source and line, but no column');
  64636. }
  64637. cachedSegments[str] = segment;
  64638. }
  64639. // Generated column.
  64640. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  64641. previousGeneratedColumn = mapping.generatedColumn;
  64642. if (segment.length > 1) {
  64643. // Original source.
  64644. mapping.source = previousSource + segment[1];
  64645. previousSource += segment[1];
  64646. // Original line.
  64647. mapping.originalLine = previousOriginalLine + segment[2];
  64648. previousOriginalLine = mapping.originalLine;
  64649. // Lines are stored 0-based
  64650. mapping.originalLine += 1;
  64651. // Original column.
  64652. mapping.originalColumn = previousOriginalColumn + segment[3];
  64653. previousOriginalColumn = mapping.originalColumn;
  64654. if (segment.length > 4) {
  64655. // Original name.
  64656. mapping.name = previousName + segment[4];
  64657. previousName += segment[4];
  64658. }
  64659. }
  64660. generatedMappings.push(mapping);
  64661. if (typeof mapping.originalLine === 'number') {
  64662. originalMappings.push(mapping);
  64663. }
  64664. }
  64665. }
  64666. quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  64667. this.__generatedMappings = generatedMappings;
  64668. quickSort(originalMappings, util$1.compareByOriginalPositions);
  64669. this.__originalMappings = originalMappings;
  64670. };
  64671. /**
  64672. * Find the mapping that best matches the hypothetical "needle" mapping that
  64673. * we are searching for in the given "haystack" of mappings.
  64674. */
  64675. BasicSourceMapConsumer.prototype._findMapping =
  64676. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  64677. aColumnName, aComparator, aBias) {
  64678. // To return the position we are searching for, we must first find the
  64679. // mapping for the given position and then return the opposite position it
  64680. // points to. Because the mappings are sorted, we can use binary search to
  64681. // find the best mapping.
  64682. if (aNeedle[aLineName] <= 0) {
  64683. throw new TypeError('Line must be greater than or equal to 1, got '
  64684. + aNeedle[aLineName]);
  64685. }
  64686. if (aNeedle[aColumnName] < 0) {
  64687. throw new TypeError('Column must be greater than or equal to 0, got '
  64688. + aNeedle[aColumnName]);
  64689. }
  64690. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  64691. };
  64692. /**
  64693. * Compute the last column for each generated mapping. The last column is
  64694. * inclusive.
  64695. */
  64696. BasicSourceMapConsumer.prototype.computeColumnSpans =
  64697. function SourceMapConsumer_computeColumnSpans() {
  64698. for (var index = 0; index < this._generatedMappings.length; ++index) {
  64699. var mapping = this._generatedMappings[index];
  64700. // Mappings do not contain a field for the last generated columnt. We
  64701. // can come up with an optimistic estimate, however, by assuming that
  64702. // mappings are contiguous (i.e. given two consecutive mappings, the
  64703. // first mapping ends where the second one starts).
  64704. if (index + 1 < this._generatedMappings.length) {
  64705. var nextMapping = this._generatedMappings[index + 1];
  64706. if (mapping.generatedLine === nextMapping.generatedLine) {
  64707. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  64708. continue;
  64709. }
  64710. }
  64711. // The last mapping for each line spans the entire line.
  64712. mapping.lastGeneratedColumn = Infinity;
  64713. }
  64714. };
  64715. /**
  64716. * Returns the original source, line, and column information for the generated
  64717. * source's line and column positions provided. The only argument is an object
  64718. * with the following properties:
  64719. *
  64720. * - line: The line number in the generated source. The line number
  64721. * is 1-based.
  64722. * - column: The column number in the generated source. The column
  64723. * number is 0-based.
  64724. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  64725. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  64726. * closest element that is smaller than or greater than the one we are
  64727. * searching for, respectively, if the exact element cannot be found.
  64728. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  64729. *
  64730. * and an object is returned with the following properties:
  64731. *
  64732. * - source: The original source file, or null.
  64733. * - line: The line number in the original source, or null. The
  64734. * line number is 1-based.
  64735. * - column: The column number in the original source, or null. The
  64736. * column number is 0-based.
  64737. * - name: The original identifier, or null.
  64738. */
  64739. BasicSourceMapConsumer.prototype.originalPositionFor =
  64740. function SourceMapConsumer_originalPositionFor(aArgs) {
  64741. var needle = {
  64742. generatedLine: util$1.getArg(aArgs, 'line'),
  64743. generatedColumn: util$1.getArg(aArgs, 'column')
  64744. };
  64745. var index = this._findMapping(
  64746. needle,
  64747. this._generatedMappings,
  64748. "generatedLine",
  64749. "generatedColumn",
  64750. util$1.compareByGeneratedPositionsDeflated,
  64751. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  64752. );
  64753. if (index >= 0) {
  64754. var mapping = this._generatedMappings[index];
  64755. if (mapping.generatedLine === needle.generatedLine) {
  64756. var source = util$1.getArg(mapping, 'source', null);
  64757. if (source !== null) {
  64758. source = this._sources.at(source);
  64759. source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  64760. }
  64761. var name = util$1.getArg(mapping, 'name', null);
  64762. if (name !== null) {
  64763. name = this._names.at(name);
  64764. }
  64765. return {
  64766. source: source,
  64767. line: util$1.getArg(mapping, 'originalLine', null),
  64768. column: util$1.getArg(mapping, 'originalColumn', null),
  64769. name: name
  64770. };
  64771. }
  64772. }
  64773. return {
  64774. source: null,
  64775. line: null,
  64776. column: null,
  64777. name: null
  64778. };
  64779. };
  64780. /**
  64781. * Return true if we have the source content for every source in the source
  64782. * map, false otherwise.
  64783. */
  64784. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  64785. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  64786. if (!this.sourcesContent) {
  64787. return false;
  64788. }
  64789. return this.sourcesContent.length >= this._sources.size() &&
  64790. !this.sourcesContent.some(function (sc) { return sc == null; });
  64791. };
  64792. /**
  64793. * Returns the original source content. The only argument is the url of the
  64794. * original source file. Returns null if no original source content is
  64795. * available.
  64796. */
  64797. BasicSourceMapConsumer.prototype.sourceContentFor =
  64798. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  64799. if (!this.sourcesContent) {
  64800. return null;
  64801. }
  64802. var index = this._findSourceIndex(aSource);
  64803. if (index >= 0) {
  64804. return this.sourcesContent[index];
  64805. }
  64806. var relativeSource = aSource;
  64807. if (this.sourceRoot != null) {
  64808. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  64809. }
  64810. var url;
  64811. if (this.sourceRoot != null
  64812. && (url = util$1.urlParse(this.sourceRoot))) {
  64813. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  64814. // many users. We can help them out when they expect file:// URIs to
  64815. // behave like it would if they were running a local HTTP server. See
  64816. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  64817. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  64818. if (url.scheme == "file"
  64819. && this._sources.has(fileUriAbsPath)) {
  64820. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  64821. }
  64822. if ((!url.path || url.path == "/")
  64823. && this._sources.has("/" + relativeSource)) {
  64824. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  64825. }
  64826. }
  64827. // This function is used recursively from
  64828. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  64829. // don't want to throw if we can't find the source - we just want to
  64830. // return null, so we provide a flag to exit gracefully.
  64831. if (nullOnMissing) {
  64832. return null;
  64833. }
  64834. else {
  64835. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  64836. }
  64837. };
  64838. /**
  64839. * Returns the generated line and column information for the original source,
  64840. * line, and column positions provided. The only argument is an object with
  64841. * the following properties:
  64842. *
  64843. * - source: The filename of the original source.
  64844. * - line: The line number in the original source. The line number
  64845. * is 1-based.
  64846. * - column: The column number in the original source. The column
  64847. * number is 0-based.
  64848. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  64849. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  64850. * closest element that is smaller than or greater than the one we are
  64851. * searching for, respectively, if the exact element cannot be found.
  64852. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  64853. *
  64854. * and an object is returned with the following properties:
  64855. *
  64856. * - line: The line number in the generated source, or null. The
  64857. * line number is 1-based.
  64858. * - column: The column number in the generated source, or null.
  64859. * The column number is 0-based.
  64860. */
  64861. BasicSourceMapConsumer.prototype.generatedPositionFor =
  64862. function SourceMapConsumer_generatedPositionFor(aArgs) {
  64863. var source = util$1.getArg(aArgs, 'source');
  64864. source = this._findSourceIndex(source);
  64865. if (source < 0) {
  64866. return {
  64867. line: null,
  64868. column: null,
  64869. lastColumn: null
  64870. };
  64871. }
  64872. var needle = {
  64873. source: source,
  64874. originalLine: util$1.getArg(aArgs, 'line'),
  64875. originalColumn: util$1.getArg(aArgs, 'column')
  64876. };
  64877. var index = this._findMapping(
  64878. needle,
  64879. this._originalMappings,
  64880. "originalLine",
  64881. "originalColumn",
  64882. util$1.compareByOriginalPositions,
  64883. util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  64884. );
  64885. if (index >= 0) {
  64886. var mapping = this._originalMappings[index];
  64887. if (mapping.source === needle.source) {
  64888. return {
  64889. line: util$1.getArg(mapping, 'generatedLine', null),
  64890. column: util$1.getArg(mapping, 'generatedColumn', null),
  64891. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  64892. };
  64893. }
  64894. }
  64895. return {
  64896. line: null,
  64897. column: null,
  64898. lastColumn: null
  64899. };
  64900. };
  64901. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  64902. /**
  64903. * An IndexedSourceMapConsumer instance represents a parsed source map which
  64904. * we can query for information. It differs from BasicSourceMapConsumer in
  64905. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  64906. * input.
  64907. *
  64908. * The first parameter is a raw source map (either as a JSON string, or already
  64909. * parsed to an object). According to the spec for indexed source maps, they
  64910. * have the following attributes:
  64911. *
  64912. * - version: Which version of the source map spec this map is following.
  64913. * - file: Optional. The generated file this source map is associated with.
  64914. * - sections: A list of section definitions.
  64915. *
  64916. * Each value under the "sections" field has two fields:
  64917. * - offset: The offset into the original specified at which this section
  64918. * begins to apply, defined as an object with a "line" and "column"
  64919. * field.
  64920. * - map: A source map definition. This source map could also be indexed,
  64921. * but doesn't have to be.
  64922. *
  64923. * Instead of the "map" field, it's also possible to have a "url" field
  64924. * specifying a URL to retrieve a source map from, but that's currently
  64925. * unsupported.
  64926. *
  64927. * Here's an example source map, taken from the source map spec[0], but
  64928. * modified to omit a section which uses the "url" field.
  64929. *
  64930. * {
  64931. * version : 3,
  64932. * file: "app.js",
  64933. * sections: [{
  64934. * offset: {line:100, column:10},
  64935. * map: {
  64936. * version : 3,
  64937. * file: "section.js",
  64938. * sources: ["foo.js", "bar.js"],
  64939. * names: ["src", "maps", "are", "fun"],
  64940. * mappings: "AAAA,E;;ABCDE;"
  64941. * }
  64942. * }],
  64943. * }
  64944. *
  64945. * The second parameter, if given, is a string whose value is the URL
  64946. * at which the source map was found. This URL is used to compute the
  64947. * sources array.
  64948. *
  64949. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  64950. */
  64951. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  64952. var sourceMap = aSourceMap;
  64953. if (typeof aSourceMap === 'string') {
  64954. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  64955. }
  64956. var version = util$1.getArg(sourceMap, 'version');
  64957. var sections = util$1.getArg(sourceMap, 'sections');
  64958. if (version != this._version) {
  64959. throw new Error('Unsupported version: ' + version);
  64960. }
  64961. this._sources = new ArraySet();
  64962. this._names = new ArraySet();
  64963. var lastOffset = {
  64964. line: -1,
  64965. column: 0
  64966. };
  64967. this._sections = sections.map(function (s) {
  64968. if (s.url) {
  64969. // The url field will require support for asynchronicity.
  64970. // See https://github.com/mozilla/source-map/issues/16
  64971. throw new Error('Support for url field in sections not implemented.');
  64972. }
  64973. var offset = util$1.getArg(s, 'offset');
  64974. var offsetLine = util$1.getArg(offset, 'line');
  64975. var offsetColumn = util$1.getArg(offset, 'column');
  64976. if (offsetLine < lastOffset.line ||
  64977. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  64978. throw new Error('Section offsets must be ordered and non-overlapping.');
  64979. }
  64980. lastOffset = offset;
  64981. return {
  64982. generatedOffset: {
  64983. // The offset fields are 0-based, but we use 1-based indices when
  64984. // encoding/decoding from VLQ.
  64985. generatedLine: offsetLine + 1,
  64986. generatedColumn: offsetColumn + 1
  64987. },
  64988. consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL)
  64989. }
  64990. });
  64991. }
  64992. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
  64993. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1;
  64994. /**
  64995. * The version of the source mapping spec that we are consuming.
  64996. */
  64997. IndexedSourceMapConsumer.prototype._version = 3;
  64998. /**
  64999. * The list of original sources.
  65000. */
  65001. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  65002. get: function () {
  65003. var sources = [];
  65004. for (var i = 0; i < this._sections.length; i++) {
  65005. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  65006. sources.push(this._sections[i].consumer.sources[j]);
  65007. }
  65008. }
  65009. return sources;
  65010. }
  65011. });
  65012. /**
  65013. * Returns the original source, line, and column information for the generated
  65014. * source's line and column positions provided. The only argument is an object
  65015. * with the following properties:
  65016. *
  65017. * - line: The line number in the generated source. The line number
  65018. * is 1-based.
  65019. * - column: The column number in the generated source. The column
  65020. * number is 0-based.
  65021. *
  65022. * and an object is returned with the following properties:
  65023. *
  65024. * - source: The original source file, or null.
  65025. * - line: The line number in the original source, or null. The
  65026. * line number is 1-based.
  65027. * - column: The column number in the original source, or null. The
  65028. * column number is 0-based.
  65029. * - name: The original identifier, or null.
  65030. */
  65031. IndexedSourceMapConsumer.prototype.originalPositionFor =
  65032. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  65033. var needle = {
  65034. generatedLine: util$1.getArg(aArgs, 'line'),
  65035. generatedColumn: util$1.getArg(aArgs, 'column')
  65036. };
  65037. // Find the section containing the generated position we're trying to map
  65038. // to an original position.
  65039. var sectionIndex = binarySearch.search(needle, this._sections,
  65040. function(needle, section) {
  65041. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  65042. if (cmp) {
  65043. return cmp;
  65044. }
  65045. return (needle.generatedColumn -
  65046. section.generatedOffset.generatedColumn);
  65047. });
  65048. var section = this._sections[sectionIndex];
  65049. if (!section) {
  65050. return {
  65051. source: null,
  65052. line: null,
  65053. column: null,
  65054. name: null
  65055. };
  65056. }
  65057. return section.consumer.originalPositionFor({
  65058. line: needle.generatedLine -
  65059. (section.generatedOffset.generatedLine - 1),
  65060. column: needle.generatedColumn -
  65061. (section.generatedOffset.generatedLine === needle.generatedLine
  65062. ? section.generatedOffset.generatedColumn - 1
  65063. : 0),
  65064. bias: aArgs.bias
  65065. });
  65066. };
  65067. /**
  65068. * Return true if we have the source content for every source in the source
  65069. * map, false otherwise.
  65070. */
  65071. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  65072. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  65073. return this._sections.every(function (s) {
  65074. return s.consumer.hasContentsOfAllSources();
  65075. });
  65076. };
  65077. /**
  65078. * Returns the original source content. The only argument is the url of the
  65079. * original source file. Returns null if no original source content is
  65080. * available.
  65081. */
  65082. IndexedSourceMapConsumer.prototype.sourceContentFor =
  65083. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  65084. for (var i = 0; i < this._sections.length; i++) {
  65085. var section = this._sections[i];
  65086. var content = section.consumer.sourceContentFor(aSource, true);
  65087. if (content) {
  65088. return content;
  65089. }
  65090. }
  65091. if (nullOnMissing) {
  65092. return null;
  65093. }
  65094. else {
  65095. throw new Error('"' + aSource + '" is not in the SourceMap.');
  65096. }
  65097. };
  65098. /**
  65099. * Returns the generated line and column information for the original source,
  65100. * line, and column positions provided. The only argument is an object with
  65101. * the following properties:
  65102. *
  65103. * - source: The filename of the original source.
  65104. * - line: The line number in the original source. The line number
  65105. * is 1-based.
  65106. * - column: The column number in the original source. The column
  65107. * number is 0-based.
  65108. *
  65109. * and an object is returned with the following properties:
  65110. *
  65111. * - line: The line number in the generated source, or null. The
  65112. * line number is 1-based.
  65113. * - column: The column number in the generated source, or null.
  65114. * The column number is 0-based.
  65115. */
  65116. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  65117. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  65118. for (var i = 0; i < this._sections.length; i++) {
  65119. var section = this._sections[i];
  65120. // Only consider this section if the requested source is in the list of
  65121. // sources of the consumer.
  65122. if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) {
  65123. continue;
  65124. }
  65125. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  65126. if (generatedPosition) {
  65127. var ret = {
  65128. line: generatedPosition.line +
  65129. (section.generatedOffset.generatedLine - 1),
  65130. column: generatedPosition.column +
  65131. (section.generatedOffset.generatedLine === generatedPosition.line
  65132. ? section.generatedOffset.generatedColumn - 1
  65133. : 0)
  65134. };
  65135. return ret;
  65136. }
  65137. }
  65138. return {
  65139. line: null,
  65140. column: null
  65141. };
  65142. };
  65143. /**
  65144. * Parse the mappings in a string in to a data structure which we can easily
  65145. * query (the ordered arrays in the `this.__generatedMappings` and
  65146. * `this.__originalMappings` properties).
  65147. */
  65148. IndexedSourceMapConsumer.prototype._parseMappings =
  65149. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  65150. this.__generatedMappings = [];
  65151. this.__originalMappings = [];
  65152. for (var i = 0; i < this._sections.length; i++) {
  65153. var section = this._sections[i];
  65154. var sectionMappings = section.consumer._generatedMappings;
  65155. for (var j = 0; j < sectionMappings.length; j++) {
  65156. var mapping = sectionMappings[j];
  65157. var source = section.consumer._sources.at(mapping.source);
  65158. source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  65159. this._sources.add(source);
  65160. source = this._sources.indexOf(source);
  65161. var name = null;
  65162. if (mapping.name) {
  65163. name = section.consumer._names.at(mapping.name);
  65164. this._names.add(name);
  65165. name = this._names.indexOf(name);
  65166. }
  65167. // The mappings coming from the consumer for the section have
  65168. // generated positions relative to the start of the section, so we
  65169. // need to offset them to be relative to the start of the concatenated
  65170. // generated file.
  65171. var adjustedMapping = {
  65172. source: source,
  65173. generatedLine: mapping.generatedLine +
  65174. (section.generatedOffset.generatedLine - 1),
  65175. generatedColumn: mapping.generatedColumn +
  65176. (section.generatedOffset.generatedLine === mapping.generatedLine
  65177. ? section.generatedOffset.generatedColumn - 1
  65178. : 0),
  65179. originalLine: mapping.originalLine,
  65180. originalColumn: mapping.originalColumn,
  65181. name: name
  65182. };
  65183. this.__generatedMappings.push(adjustedMapping);
  65184. if (typeof adjustedMapping.originalLine === 'number') {
  65185. this.__originalMappings.push(adjustedMapping);
  65186. }
  65187. }
  65188. }
  65189. quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  65190. quickSort(this.__originalMappings, util$1.compareByOriginalPositions);
  65191. };
  65192. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  65193. /* -*- Mode: js; js-indent-level: 2; -*- */
  65194. /*
  65195. * Copyright 2011 Mozilla Foundation and contributors
  65196. * Licensed under the New BSD license. See LICENSE or:
  65197. * http://opensource.org/licenses/BSD-3-Clause
  65198. */
  65199. var SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
  65200. var util = util$5;
  65201. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  65202. // operating systems these days (capturing the result).
  65203. var REGEX_NEWLINE = /(\r?\n)/;
  65204. // Newline character code for charCodeAt() comparisons
  65205. var NEWLINE_CODE = 10;
  65206. // Private symbol for identifying `SourceNode`s when multiple versions of
  65207. // the source-map library are loaded. This MUST NOT CHANGE across
  65208. // versions!
  65209. var isSourceNode = "$$$isSourceNode$$$";
  65210. /**
  65211. * SourceNodes provide a way to abstract over interpolating/concatenating
  65212. * snippets of generated JavaScript source code while maintaining the line and
  65213. * column information associated with the original source code.
  65214. *
  65215. * @param aLine The original line number.
  65216. * @param aColumn The original column number.
  65217. * @param aSource The original source's filename.
  65218. * @param aChunks Optional. An array of strings which are snippets of
  65219. * generated JS, or other SourceNodes.
  65220. * @param aName The original identifier.
  65221. */
  65222. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  65223. this.children = [];
  65224. this.sourceContents = {};
  65225. this.line = aLine == null ? null : aLine;
  65226. this.column = aColumn == null ? null : aColumn;
  65227. this.source = aSource == null ? null : aSource;
  65228. this.name = aName == null ? null : aName;
  65229. this[isSourceNode] = true;
  65230. if (aChunks != null) this.add(aChunks);
  65231. }
  65232. /**
  65233. * Creates a SourceNode from generated code and a SourceMapConsumer.
  65234. *
  65235. * @param aGeneratedCode The generated code
  65236. * @param aSourceMapConsumer The SourceMap for the generated code
  65237. * @param aRelativePath Optional. The path that relative sources in the
  65238. * SourceMapConsumer should be relative to.
  65239. */
  65240. SourceNode.fromStringWithSourceMap =
  65241. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  65242. // The SourceNode we want to fill with the generated code
  65243. // and the SourceMap
  65244. var node = new SourceNode();
  65245. // All even indices of this array are one line of the generated code,
  65246. // while all odd indices are the newlines between two adjacent lines
  65247. // (since `REGEX_NEWLINE` captures its match).
  65248. // Processed fragments are accessed by calling `shiftNextLine`.
  65249. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  65250. var remainingLinesIndex = 0;
  65251. var shiftNextLine = function() {
  65252. var lineContents = getNextLine();
  65253. // The last line of a file might not have a newline.
  65254. var newLine = getNextLine() || "";
  65255. return lineContents + newLine;
  65256. function getNextLine() {
  65257. return remainingLinesIndex < remainingLines.length ?
  65258. remainingLines[remainingLinesIndex++] : undefined;
  65259. }
  65260. };
  65261. // We need to remember the position of "remainingLines"
  65262. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  65263. // The generate SourceNodes we need a code range.
  65264. // To extract it current and last mapping is used.
  65265. // Here we store the last mapping.
  65266. var lastMapping = null;
  65267. aSourceMapConsumer.eachMapping(function (mapping) {
  65268. if (lastMapping !== null) {
  65269. // We add the code from "lastMapping" to "mapping":
  65270. // First check if there is a new line in between.
  65271. if (lastGeneratedLine < mapping.generatedLine) {
  65272. // Associate first line with "lastMapping"
  65273. addMappingWithCode(lastMapping, shiftNextLine());
  65274. lastGeneratedLine++;
  65275. lastGeneratedColumn = 0;
  65276. // The remaining code is added without mapping
  65277. } else {
  65278. // There is no new line in between.
  65279. // Associate the code between "lastGeneratedColumn" and
  65280. // "mapping.generatedColumn" with "lastMapping"
  65281. var nextLine = remainingLines[remainingLinesIndex] || '';
  65282. var code = nextLine.substr(0, mapping.generatedColumn -
  65283. lastGeneratedColumn);
  65284. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  65285. lastGeneratedColumn);
  65286. lastGeneratedColumn = mapping.generatedColumn;
  65287. addMappingWithCode(lastMapping, code);
  65288. // No more remaining code, continue
  65289. lastMapping = mapping;
  65290. return;
  65291. }
  65292. }
  65293. // We add the generated code until the first mapping
  65294. // to the SourceNode without any mapping.
  65295. // Each line is added as separate string.
  65296. while (lastGeneratedLine < mapping.generatedLine) {
  65297. node.add(shiftNextLine());
  65298. lastGeneratedLine++;
  65299. }
  65300. if (lastGeneratedColumn < mapping.generatedColumn) {
  65301. var nextLine = remainingLines[remainingLinesIndex] || '';
  65302. node.add(nextLine.substr(0, mapping.generatedColumn));
  65303. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  65304. lastGeneratedColumn = mapping.generatedColumn;
  65305. }
  65306. lastMapping = mapping;
  65307. }, this);
  65308. // We have processed all mappings.
  65309. if (remainingLinesIndex < remainingLines.length) {
  65310. if (lastMapping) {
  65311. // Associate the remaining code in the current line with "lastMapping"
  65312. addMappingWithCode(lastMapping, shiftNextLine());
  65313. }
  65314. // and add the remaining lines without any mapping
  65315. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  65316. }
  65317. // Copy sourcesContent into SourceNode
  65318. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  65319. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  65320. if (content != null) {
  65321. if (aRelativePath != null) {
  65322. sourceFile = util.join(aRelativePath, sourceFile);
  65323. }
  65324. node.setSourceContent(sourceFile, content);
  65325. }
  65326. });
  65327. return node;
  65328. function addMappingWithCode(mapping, code) {
  65329. if (mapping === null || mapping.source === undefined) {
  65330. node.add(code);
  65331. } else {
  65332. var source = aRelativePath
  65333. ? util.join(aRelativePath, mapping.source)
  65334. : mapping.source;
  65335. node.add(new SourceNode(mapping.originalLine,
  65336. mapping.originalColumn,
  65337. source,
  65338. code,
  65339. mapping.name));
  65340. }
  65341. }
  65342. };
  65343. /**
  65344. * Add a chunk of generated JS to this source node.
  65345. *
  65346. * @param aChunk A string snippet of generated JS code, another instance of
  65347. * SourceNode, or an array where each member is one of those things.
  65348. */
  65349. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  65350. if (Array.isArray(aChunk)) {
  65351. aChunk.forEach(function (chunk) {
  65352. this.add(chunk);
  65353. }, this);
  65354. }
  65355. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  65356. if (aChunk) {
  65357. this.children.push(aChunk);
  65358. }
  65359. }
  65360. else {
  65361. throw new TypeError(
  65362. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  65363. );
  65364. }
  65365. return this;
  65366. };
  65367. /**
  65368. * Add a chunk of generated JS to the beginning of this source node.
  65369. *
  65370. * @param aChunk A string snippet of generated JS code, another instance of
  65371. * SourceNode, or an array where each member is one of those things.
  65372. */
  65373. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  65374. if (Array.isArray(aChunk)) {
  65375. for (var i = aChunk.length-1; i >= 0; i--) {
  65376. this.prepend(aChunk[i]);
  65377. }
  65378. }
  65379. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  65380. this.children.unshift(aChunk);
  65381. }
  65382. else {
  65383. throw new TypeError(
  65384. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  65385. );
  65386. }
  65387. return this;
  65388. };
  65389. /**
  65390. * Walk over the tree of JS snippets in this node and its children. The
  65391. * walking function is called once for each snippet of JS and is passed that
  65392. * snippet and the its original associated source's line/column location.
  65393. *
  65394. * @param aFn The traversal function.
  65395. */
  65396. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  65397. var chunk;
  65398. for (var i = 0, len = this.children.length; i < len; i++) {
  65399. chunk = this.children[i];
  65400. if (chunk[isSourceNode]) {
  65401. chunk.walk(aFn);
  65402. }
  65403. else {
  65404. if (chunk !== '') {
  65405. aFn(chunk, { source: this.source,
  65406. line: this.line,
  65407. column: this.column,
  65408. name: this.name });
  65409. }
  65410. }
  65411. }
  65412. };
  65413. /**
  65414. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  65415. * each of `this.children`.
  65416. *
  65417. * @param aSep The separator.
  65418. */
  65419. SourceNode.prototype.join = function SourceNode_join(aSep) {
  65420. var newChildren;
  65421. var i;
  65422. var len = this.children.length;
  65423. if (len > 0) {
  65424. newChildren = [];
  65425. for (i = 0; i < len-1; i++) {
  65426. newChildren.push(this.children[i]);
  65427. newChildren.push(aSep);
  65428. }
  65429. newChildren.push(this.children[i]);
  65430. this.children = newChildren;
  65431. }
  65432. return this;
  65433. };
  65434. /**
  65435. * Call String.prototype.replace on the very right-most source snippet. Useful
  65436. * for trimming whitespace from the end of a source node, etc.
  65437. *
  65438. * @param aPattern The pattern to replace.
  65439. * @param aReplacement The thing to replace the pattern with.
  65440. */
  65441. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  65442. var lastChild = this.children[this.children.length - 1];
  65443. if (lastChild[isSourceNode]) {
  65444. lastChild.replaceRight(aPattern, aReplacement);
  65445. }
  65446. else if (typeof lastChild === 'string') {
  65447. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  65448. }
  65449. else {
  65450. this.children.push(''.replace(aPattern, aReplacement));
  65451. }
  65452. return this;
  65453. };
  65454. /**
  65455. * Set the source content for a source file. This will be added to the SourceMapGenerator
  65456. * in the sourcesContent field.
  65457. *
  65458. * @param aSourceFile The filename of the source file
  65459. * @param aSourceContent The content of the source file
  65460. */
  65461. SourceNode.prototype.setSourceContent =
  65462. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  65463. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  65464. };
  65465. /**
  65466. * Walk over the tree of SourceNodes. The walking function is called for each
  65467. * source file content and is passed the filename and source content.
  65468. *
  65469. * @param aFn The traversal function.
  65470. */
  65471. SourceNode.prototype.walkSourceContents =
  65472. function SourceNode_walkSourceContents(aFn) {
  65473. for (var i = 0, len = this.children.length; i < len; i++) {
  65474. if (this.children[i][isSourceNode]) {
  65475. this.children[i].walkSourceContents(aFn);
  65476. }
  65477. }
  65478. var sources = Object.keys(this.sourceContents);
  65479. for (var i = 0, len = sources.length; i < len; i++) {
  65480. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  65481. }
  65482. };
  65483. /**
  65484. * Return the string representation of this source node. Walks over the tree
  65485. * and concatenates all the various snippets together to one string.
  65486. */
  65487. SourceNode.prototype.toString = function SourceNode_toString() {
  65488. var str = "";
  65489. this.walk(function (chunk) {
  65490. str += chunk;
  65491. });
  65492. return str;
  65493. };
  65494. /**
  65495. * Returns the string representation of this source node along with a source
  65496. * map.
  65497. */
  65498. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  65499. var generated = {
  65500. code: "",
  65501. line: 1,
  65502. column: 0
  65503. };
  65504. var map = new SourceMapGenerator(aArgs);
  65505. var sourceMappingActive = false;
  65506. var lastOriginalSource = null;
  65507. var lastOriginalLine = null;
  65508. var lastOriginalColumn = null;
  65509. var lastOriginalName = null;
  65510. this.walk(function (chunk, original) {
  65511. generated.code += chunk;
  65512. if (original.source !== null
  65513. && original.line !== null
  65514. && original.column !== null) {
  65515. if(lastOriginalSource !== original.source
  65516. || lastOriginalLine !== original.line
  65517. || lastOriginalColumn !== original.column
  65518. || lastOriginalName !== original.name) {
  65519. map.addMapping({
  65520. source: original.source,
  65521. original: {
  65522. line: original.line,
  65523. column: original.column
  65524. },
  65525. generated: {
  65526. line: generated.line,
  65527. column: generated.column
  65528. },
  65529. name: original.name
  65530. });
  65531. }
  65532. lastOriginalSource = original.source;
  65533. lastOriginalLine = original.line;
  65534. lastOriginalColumn = original.column;
  65535. lastOriginalName = original.name;
  65536. sourceMappingActive = true;
  65537. } else if (sourceMappingActive) {
  65538. map.addMapping({
  65539. generated: {
  65540. line: generated.line,
  65541. column: generated.column
  65542. }
  65543. });
  65544. lastOriginalSource = null;
  65545. sourceMappingActive = false;
  65546. }
  65547. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  65548. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  65549. generated.line++;
  65550. generated.column = 0;
  65551. // Mappings end at eol
  65552. if (idx + 1 === length) {
  65553. lastOriginalSource = null;
  65554. sourceMappingActive = false;
  65555. } else if (sourceMappingActive) {
  65556. map.addMapping({
  65557. source: original.source,
  65558. original: {
  65559. line: original.line,
  65560. column: original.column
  65561. },
  65562. generated: {
  65563. line: generated.line,
  65564. column: generated.column
  65565. },
  65566. name: original.name
  65567. });
  65568. }
  65569. } else {
  65570. generated.column++;
  65571. }
  65572. }
  65573. });
  65574. this.walkSourceContents(function (sourceFile, sourceContent) {
  65575. map.setSourceContent(sourceFile, sourceContent);
  65576. });
  65577. return { code: generated.code, map: map };
  65578. };
  65579. /*
  65580. * Copyright 2009-2011 Mozilla Foundation and contributors
  65581. * Licensed under the New BSD license. See LICENSE.txt or:
  65582. * http://opensource.org/licenses/BSD-3-Clause
  65583. */
  65584. var SourceMapConsumer = sourceMapConsumer.SourceMapConsumer;
  65585. let offset;
  65586. try {
  65587. new Function('throw new Error(1)')();
  65588. }
  65589. catch (e) {
  65590. // in Node 12, stack traces account for the function wrapper.
  65591. // in Node 13 and later, the function wrapper adds two lines,
  65592. // which must be subtracted to generate a valid mapping
  65593. const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]);
  65594. offset = match ? +match[1] - 1 : 0;
  65595. }
  65596. function ssrRewriteStacktrace(stack, moduleGraph) {
  65597. return stack
  65598. .split('\n')
  65599. .map((line) => {
  65600. return line.replace(/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, (input, varName, url, line, column) => {
  65601. var _a;
  65602. if (!url)
  65603. return input;
  65604. const mod = moduleGraph.urlToModuleMap.get(url);
  65605. const rawSourceMap = (_a = mod === null || mod === void 0 ? void 0 : mod.ssrTransformResult) === null || _a === void 0 ? void 0 : _a.map;
  65606. if (!rawSourceMap) {
  65607. return input;
  65608. }
  65609. const consumer = new SourceMapConsumer(rawSourceMap);
  65610. const pos = consumer.originalPositionFor({
  65611. line: Number(line) - offset,
  65612. column: Number(column),
  65613. bias: SourceMapConsumer.LEAST_UPPER_BOUND
  65614. });
  65615. if (!pos.source) {
  65616. return input;
  65617. }
  65618. const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}`;
  65619. if (!varName || varName === 'eval') {
  65620. return ` at ${source}`;
  65621. }
  65622. else {
  65623. return ` at ${varName} (${source})`;
  65624. }
  65625. });
  65626. })
  65627. .join('\n');
  65628. }
  65629. function rebindErrorStacktrace(e, stacktrace) {
  65630. const { configurable, writable } = Object.getOwnPropertyDescriptor(e, 'stack');
  65631. if (configurable) {
  65632. Object.defineProperty(e, 'stack', {
  65633. value: stacktrace,
  65634. enumerable: true,
  65635. configurable: true,
  65636. writable: true
  65637. });
  65638. }
  65639. else if (writable) {
  65640. e.stack = stacktrace;
  65641. }
  65642. }
  65643. const pendingModules = new Map();
  65644. const pendingImports = new Map();
  65645. async function ssrLoadModule(url, server, context = { global }, urlStack = []) {
  65646. url = unwrapId$1(url);
  65647. // when we instantiate multiple dependency modules in parallel, they may
  65648. // point to shared modules. We need to avoid duplicate instantiation attempts
  65649. // by register every module as pending synchronously so that all subsequent
  65650. // request to that module are simply waiting on the same promise.
  65651. const pending = pendingModules.get(url);
  65652. if (pending) {
  65653. return pending;
  65654. }
  65655. const modulePromise = instantiateModule(url, server, context, urlStack);
  65656. pendingModules.set(url, modulePromise);
  65657. modulePromise
  65658. .catch(() => {
  65659. pendingImports.delete(url);
  65660. })
  65661. .finally(() => {
  65662. pendingModules.delete(url);
  65663. });
  65664. return modulePromise;
  65665. }
  65666. async function instantiateModule(url, server, context = { global }, urlStack = []) {
  65667. const { moduleGraph } = server;
  65668. const mod = await moduleGraph.ensureEntryFromUrl(url);
  65669. if (mod.ssrModule) {
  65670. return mod.ssrModule;
  65671. }
  65672. const result = mod.ssrTransformResult ||
  65673. (await transformRequest(url, server, { ssr: true }));
  65674. if (!result) {
  65675. // TODO more info? is this even necessary?
  65676. throw new Error(`failed to load module for ssr: ${url}`);
  65677. }
  65678. const ssrModule = {
  65679. [Symbol.toStringTag]: 'Module'
  65680. };
  65681. Object.defineProperty(ssrModule, '__esModule', { value: true });
  65682. // Tolerate circular imports by ensuring the module can be
  65683. // referenced before it's been instantiated.
  65684. mod.ssrModule = ssrModule;
  65685. const ssrImportMeta = { url };
  65686. urlStack = urlStack.concat(url);
  65687. const isCircular = (url) => urlStack.includes(url);
  65688. // Since dynamic imports can happen in parallel, we need to
  65689. // account for multiple pending deps and duplicate imports.
  65690. const pendingDeps = [];
  65691. const ssrImport = async (dep) => {
  65692. var _a, _b;
  65693. if (dep[0] !== '.' && dep[0] !== '/') {
  65694. return nodeRequire(dep, mod.file, server.config.root);
  65695. }
  65696. dep = unwrapId$1(dep);
  65697. if (!isCircular(dep) && !((_a = pendingImports.get(dep)) === null || _a === void 0 ? void 0 : _a.some(isCircular))) {
  65698. pendingDeps.push(dep);
  65699. if (pendingDeps.length === 1) {
  65700. pendingImports.set(url, pendingDeps);
  65701. }
  65702. await ssrLoadModule(dep, server, context, urlStack);
  65703. if (pendingDeps.length === 1) {
  65704. pendingImports.delete(url);
  65705. }
  65706. else {
  65707. pendingDeps.splice(pendingDeps.indexOf(dep), 1);
  65708. }
  65709. }
  65710. return (_b = moduleGraph.urlToModuleMap.get(dep)) === null || _b === void 0 ? void 0 : _b.ssrModule;
  65711. };
  65712. const ssrDynamicImport = (dep) => {
  65713. // #3087 dynamic import vars is ignored at rewrite import path,
  65714. // so here need process relative path
  65715. if (dep[0] === '.') {
  65716. dep = path__default.posix.resolve(path__default.dirname(url), dep);
  65717. }
  65718. return ssrImport(dep);
  65719. };
  65720. function ssrExportAll(sourceModule) {
  65721. for (const key in sourceModule) {
  65722. if (key !== 'default') {
  65723. Object.defineProperty(ssrModule, key, {
  65724. enumerable: true,
  65725. configurable: true,
  65726. get() {
  65727. return sourceModule[key];
  65728. }
  65729. });
  65730. }
  65731. }
  65732. }
  65733. try {
  65734. // eslint-disable-next-line @typescript-eslint/no-empty-function
  65735. const AsyncFunction = async function () { }.constructor;
  65736. const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`);
  65737. await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll);
  65738. }
  65739. catch (e) {
  65740. const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph);
  65741. rebindErrorStacktrace(e, stacktrace);
  65742. server.config.logger.error(`Error when evaluating SSR module ${url}:\n${stacktrace}`, {
  65743. timestamp: true,
  65744. clear: server.config.clearScreen,
  65745. error: e
  65746. });
  65747. throw e;
  65748. }
  65749. return Object.freeze(ssrModule);
  65750. }
  65751. function nodeRequire(id, importer, root) {
  65752. const mod = require(resolve(id, importer, root));
  65753. const defaultExport = mod.__esModule ? mod.default : mod;
  65754. // rollup-style default import interop for cjs
  65755. return new Proxy(mod, {
  65756. get(mod, prop) {
  65757. if (prop === 'default')
  65758. return defaultExport;
  65759. return mod[prop];
  65760. }
  65761. });
  65762. }
  65763. const resolveCache = new Map();
  65764. function resolve(id, importer, root) {
  65765. const key = id + importer + root;
  65766. const cached = resolveCache.get(key);
  65767. if (cached) {
  65768. return cached;
  65769. }
  65770. const resolveDir = importer && fs__default.existsSync(cleanUrl(importer))
  65771. ? path__default.dirname(importer)
  65772. : root;
  65773. const resolved = resolveFrom$3(id, resolveDir, true);
  65774. resolveCache.set(key, resolved);
  65775. return resolved;
  65776. }
  65777. /**
  65778. * The amount to wait for requests to register newly found dependencies before triggering
  65779. * a re-bundle + page reload
  65780. */
  65781. const debounceMs = 100;
  65782. function createMissingImporterRegisterFn(server) {
  65783. const { logger } = server.config;
  65784. let knownOptimized = server._optimizeDepsMetadata.optimized;
  65785. let currentMissing = {};
  65786. let handle;
  65787. let pendingResolve = null;
  65788. async function rerun(ssr) {
  65789. const newDeps = currentMissing;
  65790. currentMissing = {};
  65791. logger.info(source.yellow(`new dependencies found: ${Object.keys(newDeps).join(', ')}, updating...`), {
  65792. timestamp: true
  65793. });
  65794. for (const id in knownOptimized) {
  65795. newDeps[id] = knownOptimized[id].src;
  65796. }
  65797. try {
  65798. // Nullify previous metadata so that the resolver won't
  65799. // resolve to optimized files during the optimizer re-run
  65800. server._isRunningOptimizer = true;
  65801. server._optimizeDepsMetadata = null;
  65802. const newData = (server._optimizeDepsMetadata = await optimizeDeps(server.config, true, false, newDeps, ssr));
  65803. knownOptimized = newData.optimized;
  65804. // update ssr externals
  65805. server._ssrExternals = resolveSSRExternal(server.config, Object.keys(knownOptimized));
  65806. logger.info(source.greenBright(`✨ dependencies updated, reloading page...`), { timestamp: true });
  65807. }
  65808. catch (e) {
  65809. logger.error(source.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true, error: e });
  65810. }
  65811. finally {
  65812. server._isRunningOptimizer = false;
  65813. pendingResolve && pendingResolve();
  65814. server._pendingReload = pendingResolve = null;
  65815. }
  65816. // Cached transform results have stale imports (resolved to
  65817. // old locations) so they need to be invalidated before the page is
  65818. // reloaded.
  65819. server.moduleGraph.invalidateAll();
  65820. server.ws.send({
  65821. type: 'full-reload',
  65822. path: '*'
  65823. });
  65824. }
  65825. return function registerMissingImport(id, resolved, ssr) {
  65826. if (!knownOptimized[id]) {
  65827. currentMissing[id] = resolved;
  65828. if (handle)
  65829. clearTimeout(handle);
  65830. handle = setTimeout(() => rerun(ssr), debounceMs);
  65831. server._pendingReload = new Promise((r) => {
  65832. pendingResolve = r;
  65833. });
  65834. }
  65835. };
  65836. }
  65837. // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
  65838. const ROOT_FILES = [
  65839. // '.git',
  65840. // https://pnpm.js.org/workspaces/
  65841. 'pnpm-workspace.yaml'
  65842. // https://rushjs.io/pages/advanced/config_files/
  65843. // 'rush.json',
  65844. // https://nx.dev/latest/react/getting-started/nx-setup
  65845. // 'workspace.json',
  65846. // 'nx.json'
  65847. ];
  65848. // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
  65849. // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
  65850. function hasWorkspacePackageJSON(root) {
  65851. const path = path$w.join(root, 'package.json');
  65852. try {
  65853. fs__default.accessSync(path, fs__default.constants.R_OK);
  65854. }
  65855. catch {
  65856. return false;
  65857. }
  65858. const content = JSON.parse(fs__default.readFileSync(path, 'utf-8')) || {};
  65859. return !!content.workspaces;
  65860. }
  65861. function hasRootFile(root) {
  65862. return ROOT_FILES.some((file) => fs__default.existsSync(path$w.join(root, file)));
  65863. }
  65864. function hasPackageJSON(root) {
  65865. const path = path$w.join(root, 'package.json');
  65866. return fs__default.existsSync(path);
  65867. }
  65868. /**
  65869. * Search up for the nearest `package.json`
  65870. */
  65871. function searchForPackageRoot(current, root = current) {
  65872. if (hasPackageJSON(current))
  65873. return current;
  65874. const dir = path$w.dirname(current);
  65875. // reach the fs root
  65876. if (!dir || dir === current)
  65877. return root;
  65878. return searchForPackageRoot(dir, root);
  65879. }
  65880. /**
  65881. * Search up for the nearest workspace root
  65882. */
  65883. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  65884. if (hasRootFile(current))
  65885. return current;
  65886. if (hasWorkspacePackageJSON(current))
  65887. return current;
  65888. const dir = path$w.dirname(current);
  65889. // reach the fs root
  65890. if (!dir || dir === current)
  65891. return root;
  65892. return searchForWorkspaceRoot(dir, root);
  65893. }
  65894. async function createServer(inlineConfig = {}) {
  65895. const config = await resolveConfig(inlineConfig, 'serve', 'development');
  65896. const root = config.root;
  65897. const serverConfig = config.server;
  65898. const httpsOptions = await resolveHttpsConfig(config);
  65899. let { middlewareMode } = serverConfig;
  65900. if (middlewareMode === true) {
  65901. middlewareMode = 'ssr';
  65902. }
  65903. const middlewares = connect();
  65904. const httpServer = middlewareMode
  65905. ? null
  65906. : await resolveHttpServer(serverConfig, middlewares, httpsOptions);
  65907. const ws = createWebSocketServer(httpServer, config, httpsOptions);
  65908. const { ignored = [], ...watchOptions } = serverConfig.watch || {};
  65909. const watcher = chokidar.watch(path__default.resolve(root), {
  65910. ignored: [
  65911. '**/node_modules/**',
  65912. '**/.git/**',
  65913. ...(Array.isArray(ignored) ? ignored : [ignored])
  65914. ],
  65915. ignoreInitial: true,
  65916. ignorePermissionErrors: true,
  65917. disableGlobbing: true,
  65918. ...watchOptions
  65919. });
  65920. const plugins = config.plugins;
  65921. const container = await createPluginContainer(config, watcher);
  65922. const moduleGraph = new ModuleGraph(container);
  65923. const closeHttpServer = createServerCloseFn(httpServer);
  65924. // eslint-disable-next-line prefer-const
  65925. let exitProcess;
  65926. const server = {
  65927. config: config,
  65928. middlewares,
  65929. get app() {
  65930. config.logger.warn(`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`);
  65931. return middlewares;
  65932. },
  65933. httpServer,
  65934. watcher,
  65935. pluginContainer: container,
  65936. ws,
  65937. moduleGraph,
  65938. transformWithEsbuild,
  65939. transformRequest(url, options) {
  65940. return transformRequest(url, server, options);
  65941. },
  65942. transformIndexHtml: null,
  65943. ssrLoadModule(url) {
  65944. if (!server._ssrExternals) {
  65945. server._ssrExternals = resolveSSRExternal(config, server._optimizeDepsMetadata
  65946. ? Object.keys(server._optimizeDepsMetadata.optimized)
  65947. : []);
  65948. }
  65949. return ssrLoadModule(url, server);
  65950. },
  65951. ssrFixStacktrace(e) {
  65952. if (e.stack) {
  65953. const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph);
  65954. rebindErrorStacktrace(e, stacktrace);
  65955. }
  65956. },
  65957. listen(port, isRestart) {
  65958. return startServer(server, port, isRestart);
  65959. },
  65960. async close() {
  65961. process.off('SIGTERM', exitProcess);
  65962. if (!middlewareMode && process.env.CI !== 'true') {
  65963. process.stdin.off('end', exitProcess);
  65964. }
  65965. await Promise.all([
  65966. watcher.close(),
  65967. ws.close(),
  65968. container.close(),
  65969. closeHttpServer()
  65970. ]);
  65971. },
  65972. _optimizeDepsMetadata: null,
  65973. _ssrExternals: null,
  65974. _globImporters: {},
  65975. _isRunningOptimizer: false,
  65976. _registerMissingImport: null,
  65977. _pendingReload: null
  65978. };
  65979. server.transformIndexHtml = createDevHtmlTransformFn(server);
  65980. exitProcess = async () => {
  65981. try {
  65982. await server.close();
  65983. }
  65984. finally {
  65985. process.exit(0);
  65986. }
  65987. };
  65988. process.once('SIGTERM', exitProcess);
  65989. if (!middlewareMode && process.env.CI !== 'true') {
  65990. process.stdin.on('end', exitProcess);
  65991. }
  65992. watcher.on('change', async (file) => {
  65993. file = normalizePath$4(file);
  65994. // invalidate module graph cache on file change
  65995. moduleGraph.onFileChange(file);
  65996. if (serverConfig.hmr !== false) {
  65997. try {
  65998. await handleHMRUpdate(file, server);
  65999. }
  66000. catch (err) {
  66001. ws.send({
  66002. type: 'error',
  66003. err: prepareError(err)
  66004. });
  66005. }
  66006. }
  66007. });
  66008. watcher.on('add', (file) => {
  66009. handleFileAddUnlink(normalizePath$4(file), server);
  66010. });
  66011. watcher.on('unlink', (file) => {
  66012. handleFileAddUnlink(normalizePath$4(file), server, true);
  66013. });
  66014. if (!middlewareMode && httpServer) {
  66015. httpServer.once('listening', () => {
  66016. // update actual port since this may be different from initial value
  66017. serverConfig.port = httpServer.address().port;
  66018. });
  66019. }
  66020. // apply server configuration hooks from plugins
  66021. const postHooks = [];
  66022. for (const plugin of plugins) {
  66023. if (plugin.configureServer) {
  66024. postHooks.push(await plugin.configureServer(server));
  66025. }
  66026. }
  66027. // Internal middlewares ------------------------------------------------------
  66028. // request timer
  66029. if (process.env.DEBUG) {
  66030. middlewares.use(timeMiddleware(root));
  66031. }
  66032. // cors (enabled by default)
  66033. const { cors } = serverConfig;
  66034. if (cors !== false) {
  66035. middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors));
  66036. }
  66037. // proxy
  66038. const { proxy } = serverConfig;
  66039. if (proxy) {
  66040. middlewares.use(proxyMiddleware(httpServer, config));
  66041. }
  66042. // base
  66043. if (config.base !== '/') {
  66044. middlewares.use(baseMiddleware(server));
  66045. }
  66046. // open in editor support
  66047. middlewares.use('/__open-in-editor', launchEditorMiddleware());
  66048. // hmr reconnect ping
  66049. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  66050. middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) {
  66051. res.end('pong');
  66052. });
  66053. // serve static files under /public
  66054. // this applies before the transform middleware so that these files are served
  66055. // as-is without transforms.
  66056. if (config.publicDir) {
  66057. middlewares.use(servePublicMiddleware(config.publicDir));
  66058. }
  66059. // main transform middleware
  66060. middlewares.use(transformMiddleware(server));
  66061. // serve static files
  66062. middlewares.use(serveRawFsMiddleware(server));
  66063. middlewares.use(serveStaticMiddleware(root, config));
  66064. // spa fallback
  66065. if (!middlewareMode || middlewareMode === 'html') {
  66066. middlewares.use(history({
  66067. logger: createDebugger('vite:spa-fallback'),
  66068. // support /dir/ without explicit index.html
  66069. rewrites: [
  66070. {
  66071. from: /\/$/,
  66072. to({ parsedUrl }) {
  66073. const rewritten = parsedUrl.pathname + 'index.html';
  66074. if (fs__default.existsSync(path__default.join(root, rewritten))) {
  66075. return rewritten;
  66076. }
  66077. else {
  66078. return `/index.html`;
  66079. }
  66080. }
  66081. }
  66082. ]
  66083. }));
  66084. }
  66085. // run post config hooks
  66086. // This is applied before the html middleware so that user middleware can
  66087. // serve custom content instead of index.html.
  66088. postHooks.forEach((fn) => fn && fn());
  66089. if (!middlewareMode || middlewareMode === 'html') {
  66090. // transform index.html
  66091. middlewares.use(indexHtmlMiddleware(server));
  66092. // handle 404s
  66093. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  66094. middlewares.use(function vite404Middleware(_, res) {
  66095. res.statusCode = 404;
  66096. res.end();
  66097. });
  66098. }
  66099. // error handler
  66100. middlewares.use(errorMiddleware(server, !!middlewareMode));
  66101. const runOptimize = async () => {
  66102. if (config.cacheDir) {
  66103. server._isRunningOptimizer = true;
  66104. try {
  66105. server._optimizeDepsMetadata = await optimizeDeps(config);
  66106. }
  66107. finally {
  66108. server._isRunningOptimizer = false;
  66109. }
  66110. server._registerMissingImport = createMissingImporterRegisterFn(server);
  66111. }
  66112. };
  66113. if (!middlewareMode && httpServer) {
  66114. let isOptimized = false;
  66115. // overwrite listen to run optimizer before server start
  66116. const listen = httpServer.listen.bind(httpServer);
  66117. httpServer.listen = (async (port, ...args) => {
  66118. if (!isOptimized) {
  66119. try {
  66120. await container.buildStart({});
  66121. await runOptimize();
  66122. isOptimized = true;
  66123. }
  66124. catch (e) {
  66125. httpServer.emit('error', e);
  66126. return;
  66127. }
  66128. }
  66129. return listen(port, ...args);
  66130. });
  66131. }
  66132. else {
  66133. await container.buildStart({});
  66134. await runOptimize();
  66135. }
  66136. return server;
  66137. }
  66138. async function startServer(server, inlinePort, isRestart = false) {
  66139. const httpServer = server.httpServer;
  66140. if (!httpServer) {
  66141. throw new Error('Cannot call server.listen in middleware mode.');
  66142. }
  66143. const options = server.config.server;
  66144. const port = inlinePort || options.port || 3000;
  66145. const hostname = resolveHostname(options.host);
  66146. const protocol = options.https ? 'https' : 'http';
  66147. const info = server.config.logger.info;
  66148. const base = server.config.base;
  66149. const serverPort = await httpServerStart(httpServer, {
  66150. port,
  66151. strictPort: options.strictPort,
  66152. host: hostname.host,
  66153. logger: server.config.logger
  66154. });
  66155. info(source.cyan(`\n vite v${require('vite/package.json').version}`) +
  66156. source.green(` dev server running at:\n`), {
  66157. clear: !server.config.logger.hasWarned
  66158. });
  66159. printServerUrls(hostname, protocol, serverPort, base, info);
  66160. // @ts-ignore
  66161. if (global.__vite_start_time) {
  66162. info(source.cyan(
  66163. // @ts-ignore
  66164. `\n ready in ${Date.now() - global.__vite_start_time}ms.\n`));
  66165. }
  66166. // @ts-ignore
  66167. const profileSession = global.__vite_profile_session;
  66168. if (profileSession) {
  66169. profileSession.post('Profiler.stop', (err, { profile }) => {
  66170. // Write profile to disk, upload, etc.
  66171. if (!err) {
  66172. const outPath = path__default.resolve('./vite-profile.cpuprofile');
  66173. fs__default.writeFileSync(outPath, JSON.stringify(profile));
  66174. info(source.yellow(` CPU profile written to ${source.white.dim(outPath)}\n`));
  66175. }
  66176. else {
  66177. throw err;
  66178. }
  66179. });
  66180. }
  66181. if (options.open && !isRestart) {
  66182. const path = typeof options.open === 'string' ? options.open : base;
  66183. openBrowser(`${protocol}://${hostname.name}:${serverPort}${path}`, true, server.config.logger);
  66184. }
  66185. return server;
  66186. }
  66187. function createServerCloseFn(server) {
  66188. if (!server) {
  66189. return () => { };
  66190. }
  66191. let hasListened = false;
  66192. const openSockets = new Set();
  66193. server.on('connection', (socket) => {
  66194. openSockets.add(socket);
  66195. socket.on('close', () => {
  66196. openSockets.delete(socket);
  66197. });
  66198. });
  66199. server.once('listening', () => {
  66200. hasListened = true;
  66201. });
  66202. return () => new Promise((resolve, reject) => {
  66203. openSockets.forEach((s) => s.destroy());
  66204. if (hasListened) {
  66205. server.close((err) => {
  66206. if (err) {
  66207. reject(err);
  66208. }
  66209. else {
  66210. resolve();
  66211. }
  66212. });
  66213. }
  66214. else {
  66215. resolve();
  66216. }
  66217. });
  66218. }
  66219. function resolvedAllowDir(root, dir) {
  66220. return ensureLeadingSlash(normalizePath$4(path__default.resolve(root, dir)));
  66221. }
  66222. function resolveServerOptions(root, raw) {
  66223. var _a, _b;
  66224. const server = raw || {};
  66225. let allowDirs = (_a = server.fs) === null || _a === void 0 ? void 0 : _a.allow;
  66226. if (!allowDirs) {
  66227. allowDirs = [searchForWorkspaceRoot(root)];
  66228. }
  66229. allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
  66230. // only push client dir when vite itself is outside-of-root
  66231. const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
  66232. if (!allowDirs.some((i) => resolvedClientDir.startsWith(i))) {
  66233. allowDirs.push(resolvedClientDir);
  66234. }
  66235. server.fs = {
  66236. // TODO: make strict by default
  66237. strict: (_b = server.fs) === null || _b === void 0 ? void 0 : _b.strict,
  66238. allow: allowDirs
  66239. };
  66240. return server;
  66241. }
  66242. var index = {
  66243. __proto__: null,
  66244. createServer: createServer,
  66245. resolveServerOptions: resolveServerOptions
  66246. };
  66247. const noop = () => null;
  66248. function matches(pattern, importee) {
  66249. if (pattern instanceof RegExp) {
  66250. return pattern.test(importee);
  66251. }
  66252. if (importee.length < pattern.length) {
  66253. return false;
  66254. }
  66255. if (importee === pattern) {
  66256. return true;
  66257. }
  66258. const importeeStartsWithKey = importee.indexOf(pattern) === 0;
  66259. const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/';
  66260. return importeeStartsWithKey && importeeHasSlashAfterKey;
  66261. }
  66262. function normalizeId(id) {
  66263. return id;
  66264. }
  66265. function getEntries({ entries }) {
  66266. if (!entries) {
  66267. return [];
  66268. }
  66269. if (Array.isArray(entries)) {
  66270. return entries;
  66271. }
  66272. return Object.entries(entries).map(([key, value]) => {
  66273. return { find: key, replacement: value };
  66274. });
  66275. }
  66276. function getCustomResolver({ customResolver }, options) {
  66277. if (typeof customResolver === 'function') {
  66278. return customResolver;
  66279. }
  66280. if (customResolver && typeof customResolver.resolveId === 'function') {
  66281. return customResolver.resolveId;
  66282. }
  66283. if (typeof options.customResolver === 'function') {
  66284. return options.customResolver;
  66285. }
  66286. if (options.customResolver && typeof options.customResolver.resolveId === 'function') {
  66287. return options.customResolver.resolveId;
  66288. }
  66289. return null;
  66290. }
  66291. function alias(options = {}) {
  66292. const entries = getEntries(options);
  66293. if (entries.length === 0) {
  66294. return {
  66295. name: 'alias',
  66296. resolveId: noop
  66297. };
  66298. }
  66299. return {
  66300. name: 'alias',
  66301. buildStart(inputOptions) {
  66302. return Promise.all([...entries, options].map(({ customResolver }) => customResolver &&
  66303. typeof customResolver === 'object' &&
  66304. typeof customResolver.buildStart === 'function' &&
  66305. customResolver.buildStart.call(this, inputOptions))).then(() => {
  66306. // enforce void return value
  66307. });
  66308. },
  66309. resolveId(importee, importer) {
  66310. const importeeId = normalizeId(importee);
  66311. const importerId = normalizeId(importer);
  66312. // First match is supposed to be the correct one
  66313. const matchedEntry = entries.find((entry) => matches(entry.find, importeeId));
  66314. if (!matchedEntry || !importerId) {
  66315. return null;
  66316. }
  66317. const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement));
  66318. const customResolver = getCustomResolver(matchedEntry, options);
  66319. if (customResolver) {
  66320. return customResolver.call(this, updatedId, importerId, {});
  66321. }
  66322. return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => {
  66323. let finalResult = resolved;
  66324. if (!finalResult) {
  66325. finalResult = { id: updatedId };
  66326. }
  66327. return finalResult;
  66328. });
  66329. }
  66330. };
  66331. }
  66332. /**
  66333. * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js
  66334. *
  66335. * This source code is licensed under the MIT license found in the
  66336. * LICENSE file at
  66337. * https://github.com/rollup/plugins/blob/master/LICENSE
  66338. */
  66339. // Custom json filter for vite
  66340. const jsonExtRE = /\.json($|\?)(?!commonjs-proxy)/;
  66341. function jsonPlugin(options = {}, isBuild) {
  66342. return {
  66343. name: 'vite:json',
  66344. transform(json, id) {
  66345. if (!jsonExtRE.test(id))
  66346. return null;
  66347. if (SPECIAL_QUERY_RE.test(id))
  66348. return null;
  66349. try {
  66350. if (options.stringify) {
  66351. if (isBuild) {
  66352. return {
  66353. // during build, parse then double-stringify to remove all
  66354. // unnecessary whitespaces to reduce bundle size.
  66355. code: `export default JSON.parse(${JSON.stringify(JSON.stringify(JSON.parse(json)))})`,
  66356. map: { mappings: '' }
  66357. };
  66358. }
  66359. else {
  66360. return `export default JSON.parse(${JSON.stringify(json)})`;
  66361. }
  66362. }
  66363. const parsed = JSON.parse(json);
  66364. return {
  66365. code: dataToEsm(parsed, {
  66366. preferConst: true,
  66367. namedExports: options.namedExports
  66368. }),
  66369. map: { mappings: '' }
  66370. };
  66371. }
  66372. catch (e) {
  66373. const errorMessageList = /[\d]+/.exec(e.message);
  66374. const position = errorMessageList && parseInt(errorMessageList[0], 10);
  66375. const msg = position
  66376. ? `, invalid JSON syntax found at line ${position}`
  66377. : `.`;
  66378. this.error(`Failed to parse JSON file` + msg, e.idx);
  66379. }
  66380. }
  66381. };
  66382. }
  66383. const isDebug = !!process.env.DEBUG;
  66384. const debugRewrite = createDebugger('vite:rewrite');
  66385. const clientDir = normalizePath$4(CLIENT_DIR);
  66386. const skipRE = /\.(map|json)$/;
  66387. const canSkip = (id) => skipRE.test(id) || isDirectCSSRequest(id);
  66388. function isExplicitImportRequired(url) {
  66389. return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url);
  66390. }
  66391. function markExplicitImport(url) {
  66392. if (isExplicitImportRequired(url)) {
  66393. return injectQuery(url, 'import');
  66394. }
  66395. return url;
  66396. }
  66397. /**
  66398. * Server-only plugin that lexes, resolves, rewrites and analyzes url imports.
  66399. *
  66400. * - Imports are resolved to ensure they exist on disk
  66401. *
  66402. * - Lexes HMR accept calls and updates import relationships in the module graph
  66403. *
  66404. * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
  66405. * absolute file paths, e.g.
  66406. *
  66407. * ```js
  66408. * import 'foo'
  66409. * ```
  66410. * is rewritten to
  66411. * ```js
  66412. * import '/@fs//project/node_modules/foo/dist/foo.js'
  66413. * ```
  66414. *
  66415. * - CSS imports are appended with `.js` since both the js module and the actual
  66416. * css (referenced via <link>) may go through the transform pipeline:
  66417. *
  66418. * ```js
  66419. * import './style.css'
  66420. * ```
  66421. * is rewritten to
  66422. * ```js
  66423. * import './style.css.js'
  66424. * ```
  66425. */
  66426. function importAnalysisPlugin(config) {
  66427. const { root, base } = config;
  66428. const clientPublicPath = path__default.posix.join(base, CLIENT_PUBLIC_PATH);
  66429. let server;
  66430. return {
  66431. name: 'vite:import-analysis',
  66432. configureServer(_server) {
  66433. server = _server;
  66434. },
  66435. async transform(source$1, importer, ssr) {
  66436. const prettyImporter = prettifyUrl(importer, root);
  66437. if (canSkip(importer)) {
  66438. isDebug && debugRewrite(source.dim(`[skipped] ${prettyImporter}`));
  66439. return null;
  66440. }
  66441. const rewriteStart = Date.now();
  66442. await init;
  66443. let imports = [];
  66444. // strip UTF-8 BOM
  66445. if (source$1.charCodeAt(0) === 0xfeff) {
  66446. source$1 = source$1.slice(1);
  66447. }
  66448. try {
  66449. imports = parse$d(source$1)[0];
  66450. }
  66451. catch (e) {
  66452. const isVue = importer.endsWith('.vue');
  66453. const maybeJSX = !isVue && isJSRequest(importer);
  66454. const msg = isVue
  66455. ? `Install @vitejs/plugin-vue to handle .vue files.`
  66456. : maybeJSX
  66457. ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.`
  66458. : `You may need to install appropriate plugins to handle the ${path__default.extname(importer)} file format.`;
  66459. this.error(`Failed to parse source for import analysis because the content ` +
  66460. `contains invalid JS syntax. ` +
  66461. msg, e.idx);
  66462. }
  66463. if (!imports.length) {
  66464. isDebug &&
  66465. debugRewrite(`${timeFrom(rewriteStart)} ${source.dim(`[no imports] ${prettyImporter}`)}`);
  66466. return source$1;
  66467. }
  66468. let hasHMR = false;
  66469. let isSelfAccepting = false;
  66470. let hasEnv = false;
  66471. let needQueryInjectHelper = false;
  66472. let s;
  66473. const str = () => s || (s = new MagicString(source$1));
  66474. // vite-only server context
  66475. const { moduleGraph } = server;
  66476. // since we are already in the transform phase of the importer, it must
  66477. // have been loaded so its entry is guaranteed in the module graph.
  66478. const importerModule = moduleGraph.getModuleById(importer);
  66479. const importedUrls = new Set();
  66480. const acceptedUrls = new Set();
  66481. const toAbsoluteUrl = (url) => path__default.posix.resolve(path__default.posix.dirname(importerModule.url), url);
  66482. const normalizeUrl = async (url, pos) => {
  66483. if (base !== '/' && url.startsWith(base)) {
  66484. url = url.replace(base, '/');
  66485. }
  66486. const resolved = await this.resolve(url, importer);
  66487. if (!resolved) {
  66488. this.error(`Failed to resolve import "${url}" from "${path__default.relative(process.cwd(), importer)}". Does the file exist?`, pos);
  66489. }
  66490. const isRelative = url.startsWith('.');
  66491. // normalize all imports into resolved URLs
  66492. // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js`
  66493. if (resolved.id.startsWith(root + '/')) {
  66494. // in root: infer short absolute path from root
  66495. url = resolved.id.slice(root.length);
  66496. }
  66497. else if (fs__default.existsSync(cleanUrl(resolved.id))) {
  66498. // exists but out of root: rewrite to absolute /@fs/ paths
  66499. url = path__default.posix.join(FS_PREFIX + resolved.id);
  66500. }
  66501. else {
  66502. url = resolved.id;
  66503. }
  66504. if (isExternalUrl(url)) {
  66505. return [url, url];
  66506. }
  66507. // if the resolved id is not a valid browser import specifier,
  66508. // prefix it to make it valid. We will strip this before feeding it
  66509. // back into the transform pipeline
  66510. if (!url.startsWith('.') && !url.startsWith('/')) {
  66511. url =
  66512. VALID_ID_PREFIX + resolved.id.replace('\0', NULL_BYTE_PLACEHOLDER);
  66513. }
  66514. // make the URL browser-valid if not SSR
  66515. if (!ssr) {
  66516. // mark non-js/css imports with `?import`
  66517. url = markExplicitImport(url);
  66518. // for relative js/css imports, inherit importer's version query
  66519. // do not do this for unknown type imports, otherwise the appended
  66520. // query can break 3rd party plugin's extension checks.
  66521. if (isRelative && !/[\?&]import=?\b/.test(url)) {
  66522. const versionMatch = importer.match(DEP_VERSION_RE);
  66523. if (versionMatch) {
  66524. url = injectQuery(url, versionMatch[1]);
  66525. }
  66526. }
  66527. // check if the dep has been hmr updated. If yes, we need to attach
  66528. // its last updated timestamp to force the browser to fetch the most
  66529. // up-to-date version of this module.
  66530. try {
  66531. const depModule = await moduleGraph.ensureEntryFromUrl(url);
  66532. if (depModule.lastHMRTimestamp > 0) {
  66533. url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
  66534. }
  66535. }
  66536. catch (e) {
  66537. // it's possible that the dep fails to resolve (non-existent import)
  66538. // attach location to the missing import
  66539. e.pos = pos;
  66540. throw e;
  66541. }
  66542. // prepend base (dev base is guaranteed to have ending slash)
  66543. url = base + url.replace(/^\//, '');
  66544. }
  66545. return [url, resolved.id];
  66546. };
  66547. for (let index = 0; index < imports.length; index++) {
  66548. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex,
  66549. // #2083 User may use escape path,
  66550. // so use imports[index].n to get the unescaped string
  66551. // @ts-ignore
  66552. n: specifier } = imports[index];
  66553. const rawUrl = source$1.slice(start, end);
  66554. // check import.meta usage
  66555. if (rawUrl === 'import.meta') {
  66556. const prop = source$1.slice(end, end + 4);
  66557. if (prop === '.hot') {
  66558. hasHMR = true;
  66559. if (source$1.slice(end + 4, end + 11) === '.accept') {
  66560. // further analyze accepted modules
  66561. if (lexAcceptedHmrDeps(source$1, source$1.indexOf('(', end + 11) + 1, acceptedUrls)) {
  66562. isSelfAccepting = true;
  66563. }
  66564. }
  66565. }
  66566. else if (prop === '.env') {
  66567. hasEnv = true;
  66568. }
  66569. else if (prop === '.glo' && source$1[end + 4] === 'b') {
  66570. // transform import.meta.glob()
  66571. // e.g. `import.meta.glob('glob:./dir/*.js')`
  66572. const { imports, importsString, exp, endIndex, base, pattern } = await transformImportGlob(source$1, start, importer, index, root, normalizeUrl);
  66573. str().prepend(importsString);
  66574. str().overwrite(expStart, endIndex, exp);
  66575. imports.forEach((url) => importedUrls.add(url.replace(base, '/')));
  66576. if (!(importerModule.file in server._globImporters)) {
  66577. server._globImporters[importerModule.file] = {
  66578. module: importerModule,
  66579. importGlobs: []
  66580. };
  66581. }
  66582. server._globImporters[importerModule.file].importGlobs.push({
  66583. base,
  66584. pattern
  66585. });
  66586. }
  66587. continue;
  66588. }
  66589. const isDynamicImport = dynamicIndex >= 0;
  66590. // static import or valid string in dynamic import
  66591. // If resolvable, let's resolve it
  66592. if (specifier) {
  66593. // skip external / data uri
  66594. if (isExternalUrl(specifier) || isDataUrl(specifier)) {
  66595. continue;
  66596. }
  66597. // skip ssr external
  66598. if (ssr) {
  66599. if (server._ssrExternals &&
  66600. shouldExternalizeForSSR(specifier, server._ssrExternals)) {
  66601. continue;
  66602. }
  66603. if (isBuiltin(specifier)) {
  66604. continue;
  66605. }
  66606. }
  66607. // skip client
  66608. if (specifier === clientPublicPath) {
  66609. continue;
  66610. }
  66611. // warn imports to non-asset /public files
  66612. if (specifier.startsWith('/') &&
  66613. !config.assetsInclude(cleanUrl(specifier)) &&
  66614. !specifier.endsWith('.json') &&
  66615. checkPublicFile(specifier, config)) {
  66616. throw new Error(`Cannot import non-asset file ${specifier} which is inside /public.` +
  66617. `JS/CSS files inside /public are copied as-is on build and ` +
  66618. `can only be referenced via <script src> or <link href> in html.`);
  66619. }
  66620. // normalize
  66621. const [normalizedUrl, resolvedId] = await normalizeUrl(specifier, start);
  66622. let url = normalizedUrl;
  66623. // record as safe modules
  66624. server === null || server === void 0 ? void 0 : server.moduleGraph.safeModulesPath.add(cleanUrl(url).slice(4 /* '/@fs'.length */));
  66625. // rewrite
  66626. if (url !== specifier) {
  66627. // for optimized cjs deps, support named imports by rewriting named
  66628. // imports to const assignments.
  66629. if (resolvedId.endsWith(`&es-interop`)) {
  66630. url = url.slice(0, -11);
  66631. if (isDynamicImport) {
  66632. // rewrite `import('package')` to expose the default directly
  66633. str().overwrite(dynamicIndex, end + 1, `import('${url}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))`);
  66634. }
  66635. else {
  66636. const exp = source$1.slice(expStart, expEnd);
  66637. const rewritten = transformCjsImport(exp, url, rawUrl, index);
  66638. if (rewritten) {
  66639. str().overwrite(expStart, expEnd, rewritten);
  66640. }
  66641. else {
  66642. // #1439 export * from '...'
  66643. str().overwrite(start, end, url);
  66644. }
  66645. }
  66646. }
  66647. else {
  66648. str().overwrite(start, end, isDynamicImport ? `'${url}'` : url);
  66649. }
  66650. }
  66651. // record for HMR import chain analysis
  66652. // make sure to normalize away base
  66653. importedUrls.add(url.replace(base, '/'));
  66654. }
  66655. else if (!importer.startsWith(clientDir) && !ssr) {
  66656. // check @vite-ignore which suppresses dynamic import warning
  66657. const hasViteIgnore = /\/\*\s*@vite-ignore\s*\*\//.test(rawUrl);
  66658. const url = rawUrl
  66659. .replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '')
  66660. .trim();
  66661. if (!hasViteIgnore && !isSupportedDynamicImport(url)) {
  66662. this.warn(`\n` +
  66663. source.cyan(importerModule.file) +
  66664. `\n` +
  66665. generateCodeFrame(source$1, start) +
  66666. `\nThe above dynamic import cannot be analyzed by vite.\n` +
  66667. `See ${source.blue(`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`)} ` +
  66668. `for supported dynamic import formats. ` +
  66669. `If this is intended to be left as-is, you can use the ` +
  66670. `/* @vite-ignore */ comment inside the import() call to suppress this warning.\n`);
  66671. }
  66672. if (!/^('.*'|".*"|`.*`)$/.test(url) ||
  66673. isExplicitImportRequired(url.slice(1, -1))) {
  66674. needQueryInjectHelper = true;
  66675. str().overwrite(start, end, `__vite__injectQuery(${url}, 'import')`);
  66676. }
  66677. }
  66678. }
  66679. if (hasEnv) {
  66680. // inject import.meta.env
  66681. let env = `import.meta.env = ${JSON.stringify({
  66682. ...config.env,
  66683. SSR: !!ssr
  66684. })};`;
  66685. // account for user env defines
  66686. for (const key in config.define) {
  66687. if (key.startsWith(`import.meta.env.`)) {
  66688. const val = config.define[key];
  66689. env += `${key} = ${typeof val === 'string' ? val : JSON.stringify(val)};`;
  66690. }
  66691. }
  66692. str().prepend(env);
  66693. }
  66694. if (hasHMR && !ssr) {
  66695. debugHmr(`${isSelfAccepting
  66696. ? `[self-accepts]`
  66697. : acceptedUrls.size
  66698. ? `[accepts-deps]`
  66699. : `[detected api usage]`} ${prettyImporter}`);
  66700. // inject hot context
  66701. str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";` +
  66702. `import.meta.hot = __vite__createHotContext(${JSON.stringify(importerModule.url)});`);
  66703. }
  66704. if (needQueryInjectHelper) {
  66705. str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
  66706. }
  66707. // normalize and rewrite accepted urls
  66708. const normalizedAcceptedUrls = new Set();
  66709. for (const { url, start, end } of acceptedUrls) {
  66710. const [normalized] = await moduleGraph.resolveUrl(toAbsoluteUrl(markExplicitImport(url)));
  66711. normalizedAcceptedUrls.add(normalized);
  66712. str().overwrite(start, end, JSON.stringify(normalized));
  66713. }
  66714. // update the module graph for HMR analysis.
  66715. // node CSS imports does its own graph update in the css plugin so we
  66716. // only handle js graph updates here.
  66717. if (!isCSSRequest(importer)) {
  66718. // attached by pluginContainer.addWatchFile
  66719. const pluginImports = this._addedImports;
  66720. if (pluginImports) {
  66721. (await Promise.all([...pluginImports].map((id) => normalizeUrl(id, 0)))).forEach(([url]) => importedUrls.add(url));
  66722. }
  66723. const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, normalizedAcceptedUrls, isSelfAccepting);
  66724. if (hasHMR && prunedImports) {
  66725. handlePrunedModules(prunedImports, server);
  66726. }
  66727. }
  66728. if (s) {
  66729. return s.toString();
  66730. }
  66731. else {
  66732. return source$1;
  66733. }
  66734. }
  66735. };
  66736. }
  66737. /**
  66738. * https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations
  66739. * This is probably less accurate but is much cheaper than a full AST parse.
  66740. */
  66741. function isSupportedDynamicImport(url) {
  66742. url = url.trim().slice(1, -1);
  66743. // must be relative
  66744. if (!url.startsWith('./') && !url.startsWith('../')) {
  66745. return false;
  66746. }
  66747. // must have extension
  66748. if (!path__default.extname(url)) {
  66749. return false;
  66750. }
  66751. // must be more specific if importing from same dir
  66752. if (url.startsWith('./${') && url.indexOf('/') === url.lastIndexOf('/')) {
  66753. return false;
  66754. }
  66755. return true;
  66756. }
  66757. /**
  66758. * Detect import statements to a known optimized CJS dependency and provide
  66759. * ES named imports interop. We do this by rewriting named imports to a variable
  66760. * assignment to the corresponding property on the `module.exports` of the cjs
  66761. * module. Note this doesn't support dynamic re-assignments from within the cjs
  66762. * module.
  66763. *
  66764. * Note that es-module-lexer treats `export * from '...'` as an import as well,
  66765. * so, we may encounter ExportAllDeclaration here, in which case `undefined`
  66766. * will be returned.
  66767. *
  66768. * Credits \@csr632 via #837
  66769. */
  66770. function transformCjsImport(importExp, url, rawUrl, importIndex) {
  66771. const node = parse$b(importExp, {
  66772. ecmaVersion: 2020,
  66773. sourceType: 'module'
  66774. }).body[0];
  66775. if (node.type === 'ImportDeclaration') {
  66776. if (!node.specifiers.length) {
  66777. return `import "${url}"`;
  66778. }
  66779. const importNames = [];
  66780. for (const spec of node.specifiers) {
  66781. if (spec.type === 'ImportSpecifier' &&
  66782. spec.imported.type === 'Identifier') {
  66783. const importedName = spec.imported.name;
  66784. const localName = spec.local.name;
  66785. importNames.push({ importedName, localName });
  66786. }
  66787. else if (spec.type === 'ImportDefaultSpecifier') {
  66788. importNames.push({
  66789. importedName: 'default',
  66790. localName: spec.local.name
  66791. });
  66792. }
  66793. else if (spec.type === 'ImportNamespaceSpecifier') {
  66794. importNames.push({ importedName: '*', localName: spec.local.name });
  66795. }
  66796. }
  66797. // If there is multiple import for same id in one file,
  66798. // importIndex will prevent the cjsModuleName to be duplicate
  66799. const cjsModuleName = makeLegalIdentifier$1(`__vite__cjsImport${importIndex}_${rawUrl}`);
  66800. const lines = [`import ${cjsModuleName} from "${url}"`];
  66801. importNames.forEach(({ importedName, localName }) => {
  66802. if (importedName === '*') {
  66803. lines.push(`const ${localName} = ${cjsModuleName}`);
  66804. }
  66805. else if (importedName === 'default') {
  66806. lines.push(`const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`);
  66807. }
  66808. else {
  66809. lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
  66810. }
  66811. });
  66812. return lines.join('; ');
  66813. }
  66814. }
  66815. // ids in transform are normalized to unix style
  66816. const normalizedClientEntry = normalizePath$4(CLIENT_ENTRY);
  66817. const normalizedEnvEntry = normalizePath$4(ENV_ENTRY);
  66818. /**
  66819. * some values used by the client needs to be dynamically injected by the server
  66820. * @server-only
  66821. */
  66822. function clientInjectionsPlugin(config) {
  66823. return {
  66824. name: 'vite:client-inject',
  66825. transform(code, id) {
  66826. if (id === normalizedClientEntry || id === normalizedEnvEntry) {
  66827. let options = config.server.hmr;
  66828. options = options && typeof options !== 'boolean' ? options : {};
  66829. const host = options.host || null;
  66830. const protocol = options.protocol || null;
  66831. const timeout = options.timeout || 30000;
  66832. const overlay = options.overlay !== false;
  66833. let port;
  66834. if (isObject$3(config.server.hmr)) {
  66835. port = config.server.hmr.clientPort || config.server.hmr.port;
  66836. }
  66837. if (config.server.middlewareMode) {
  66838. port = String(port || 24678);
  66839. }
  66840. else {
  66841. port = String(port || options.port || config.server.port);
  66842. }
  66843. let hmrBase = config.base;
  66844. if (options.path) {
  66845. hmrBase = path__default.posix.join(hmrBase, options.path);
  66846. }
  66847. if (hmrBase !== '/') {
  66848. port = path__default.posix.normalize(`${port}${hmrBase}`);
  66849. }
  66850. return code
  66851. .replace(`__MODE__`, JSON.stringify(config.mode))
  66852. .replace(`__BASE__`, JSON.stringify(config.base))
  66853. .replace(`__DEFINES__`, serializeDefine(config.define || {}))
  66854. .replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol))
  66855. .replace(`__HMR_HOSTNAME__`, JSON.stringify(host))
  66856. .replace(`__HMR_PORT__`, JSON.stringify(port))
  66857. .replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout))
  66858. .replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay));
  66859. }
  66860. else if (code.includes('process.env.NODE_ENV')) {
  66861. // replace process.env.NODE_ENV
  66862. return code.replace(/\bprocess\.env\.NODE_ENV\b/g, JSON.stringify(config.mode));
  66863. }
  66864. }
  66865. };
  66866. }
  66867. function serializeDefine(define) {
  66868. let res = `{`;
  66869. for (const key in define) {
  66870. const val = define[key];
  66871. res += `${JSON.stringify(key)}: ${typeof val === 'string' ? `(${val})` : JSON.stringify(val)}, `;
  66872. }
  66873. return res + `}`;
  66874. }
  66875. const wasmHelperId = '/__vite-wasm-helper';
  66876. const wasmHelper = async (opts = {}, url) => {
  66877. let result;
  66878. if (url.startsWith('data:')) {
  66879. // @ts-ignore
  66880. const binaryString = atob(url.replace(/^data:.*?base64,/, ''));
  66881. const bytes = new Uint8Array(binaryString.length);
  66882. for (let i = 0; i < binaryString.length; i++) {
  66883. bytes[i] = binaryString.charCodeAt(i);
  66884. }
  66885. // @ts-ignore
  66886. result = await WebAssembly.instantiate(bytes, opts);
  66887. }
  66888. else {
  66889. // https://github.com/mdn/webassembly-examples/issues/5
  66890. // WebAssembly.instantiateStreaming requires the server to provide the
  66891. // correct MIME type for .wasm files, which unfortunately doesn't work for
  66892. // a lot of static file servers, so we just work around it by getting the
  66893. // raw buffer.
  66894. // @ts-ignore
  66895. const response = await fetch(url);
  66896. const contentType = response.headers.get('Content-Type') || '';
  66897. if (
  66898. // @ts-ignore
  66899. 'instantiateStreaming' in WebAssembly &&
  66900. contentType.startsWith('application/wasm')) {
  66901. // @ts-ignore
  66902. result = await WebAssembly.instantiateStreaming(response, opts);
  66903. }
  66904. else {
  66905. const buffer = await response.arrayBuffer();
  66906. // @ts-ignore
  66907. result = await WebAssembly.instantiate(buffer, opts);
  66908. }
  66909. }
  66910. return result.instance.exports;
  66911. };
  66912. const wasmHelperCode = wasmHelper.toString();
  66913. const wasmPlugin = (config) => {
  66914. return {
  66915. name: 'vite:wasm',
  66916. resolveId(id) {
  66917. if (id === wasmHelperId) {
  66918. return id;
  66919. }
  66920. },
  66921. async load(id) {
  66922. if (id === wasmHelperId) {
  66923. return `export default ${wasmHelperCode}`;
  66924. }
  66925. if (!id.endsWith('.wasm')) {
  66926. return;
  66927. }
  66928. const url = await fileToUrl(id, config, this);
  66929. return `
  66930. import initWasm from "${wasmHelperId}"
  66931. export default opts => initWasm(opts, ${JSON.stringify(url)})
  66932. `;
  66933. }
  66934. };
  66935. };
  66936. function parseWorkerRequest(id) {
  66937. const { search } = require$$0$a.parse(id);
  66938. if (!search) {
  66939. return null;
  66940. }
  66941. return Object.fromEntries(new require$$0$a.URLSearchParams(search.slice(1)));
  66942. }
  66943. const WorkerFileId = 'worker_file';
  66944. function webWorkerPlugin(config) {
  66945. const isBuild = config.command === 'build';
  66946. return {
  66947. name: 'vite:worker',
  66948. load(id) {
  66949. var _a;
  66950. if (isBuild) {
  66951. const parsedQuery = parseWorkerRequest(id);
  66952. if (parsedQuery &&
  66953. ((_a = parsedQuery.worker) !== null && _a !== void 0 ? _a : parsedQuery.sharedworker) != null) {
  66954. return '';
  66955. }
  66956. }
  66957. },
  66958. async transform(_, id) {
  66959. var _a;
  66960. const query = parseWorkerRequest(id);
  66961. if (query && query[WorkerFileId] != null) {
  66962. return {
  66963. code: `import '${ENV_PUBLIC_PATH}'\n` + _
  66964. };
  66965. }
  66966. if (query == null ||
  66967. (query && ((_a = query.worker) !== null && _a !== void 0 ? _a : query.sharedworker) == null)) {
  66968. return;
  66969. }
  66970. let url;
  66971. if (isBuild) {
  66972. // bundle the file as entry to support imports
  66973. const rollup = require('rollup');
  66974. const bundle = await rollup.rollup({
  66975. input: cleanUrl(id),
  66976. plugins: await resolvePlugins({ ...config }, [], [], [])
  66977. });
  66978. let code;
  66979. try {
  66980. const { output } = await bundle.generate({
  66981. format: 'iife',
  66982. sourcemap: config.build.sourcemap
  66983. });
  66984. code = output[0].code;
  66985. }
  66986. finally {
  66987. await bundle.close();
  66988. }
  66989. const content = Buffer.from(code);
  66990. if (query.inline != null) {
  66991. // inline as blob data url
  66992. return `const blob = new Blob([atob(\"${content.toString('base64')}\")], { type: 'text/javascript;charset=utf-8' });
  66993. export default function WorkerWrapper() {
  66994. const objURL = (window.URL || window.webkitURL).createObjectURL(blob);
  66995. try {
  66996. return new Worker(objURL);
  66997. } finally {
  66998. (window.URL || window.webkitURL).revokeObjectURL(objURL);
  66999. }
  67000. }`;
  67001. }
  67002. else {
  67003. const basename = path__default.parse(cleanUrl(id)).name;
  67004. const contentHash = getAssetHash(content);
  67005. const fileName = path__default.posix.join(config.build.assetsDir, `${basename}.${contentHash}.js`);
  67006. url = `__VITE_ASSET__${this.emitFile({
  67007. fileName,
  67008. type: 'asset',
  67009. source: code
  67010. })}__`;
  67011. }
  67012. }
  67013. else {
  67014. url = await fileToUrl(cleanUrl(id), config, this);
  67015. url = injectQuery(url, WorkerFileId);
  67016. }
  67017. const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
  67018. const workerOptions = { type: 'module' };
  67019. return `export default function WorkerWrapper() {
  67020. return new ${workerConstructor}(${JSON.stringify(url)}, ${JSON.stringify(workerOptions, null, 2)})
  67021. }`;
  67022. }
  67023. };
  67024. }
  67025. /**
  67026. * A plugin to avoid an aliased AND optimized dep from being aliased in src
  67027. */
  67028. function preAliasPlugin() {
  67029. let server;
  67030. return {
  67031. name: 'vite:pre-alias',
  67032. configureServer(_server) {
  67033. server = _server;
  67034. },
  67035. resolveId(id, importer, _, ssr) {
  67036. if (!ssr && bareImportRE.test(id)) {
  67037. return tryOptimizedResolve(id, server, importer);
  67038. }
  67039. }
  67040. };
  67041. }
  67042. function definePlugin(config) {
  67043. const isBuild = config.command === 'build';
  67044. const userDefine = {};
  67045. for (const key in config.define) {
  67046. const val = config.define[key];
  67047. userDefine[key] = typeof val === 'string' ? val : JSON.stringify(val);
  67048. }
  67049. // during dev, import.meta properties are handled by importAnalysis plugin
  67050. const importMetaKeys = {};
  67051. if (isBuild) {
  67052. const env = {
  67053. ...config.env,
  67054. SSR: !!config.build.ssr
  67055. };
  67056. for (const key in env) {
  67057. importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(env[key]);
  67058. }
  67059. Object.assign(importMetaKeys, {
  67060. 'import.meta.env.': `({}).`,
  67061. 'import.meta.env': JSON.stringify(config.env),
  67062. 'import.meta.hot': `false`
  67063. });
  67064. }
  67065. const replacements = {
  67066. 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
  67067. 'global.process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
  67068. 'globalThis.process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
  67069. ...userDefine,
  67070. ...importMetaKeys,
  67071. 'process.env.': `({}).`,
  67072. 'global.process.env.': `({}).`,
  67073. 'globalThis.process.env.': `({}).`
  67074. };
  67075. const pattern = new RegExp(
  67076. // Do not allow preceding '.', but do allow preceding '...' for spread operations
  67077. '(?<!(?<!\\.\\.)\\.)\\b(' +
  67078. Object.keys(replacements)
  67079. .map((str) => {
  67080. return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  67081. })
  67082. .join('|') +
  67083. ')\\b', 'g');
  67084. return {
  67085. name: 'vite:define',
  67086. transform(code, id, ssr) {
  67087. if (!ssr && !isBuild) {
  67088. // for dev we inject actual global defines in the vite client to
  67089. // avoid the transform cost.
  67090. return;
  67091. }
  67092. if (
  67093. // exclude css and static assets for performance
  67094. isCSSRequest(id) ||
  67095. config.assetsInclude(id)) {
  67096. return;
  67097. }
  67098. if (ssr && !isBuild) {
  67099. // ssr + dev, simple replace
  67100. return code.replace(pattern, (_, match) => {
  67101. return '' + replacements[match];
  67102. });
  67103. }
  67104. const s = new MagicString(code);
  67105. let hasReplaced = false;
  67106. let match;
  67107. while ((match = pattern.exec(code))) {
  67108. hasReplaced = true;
  67109. const start = match.index;
  67110. const end = start + match[0].length;
  67111. const replacement = '' + replacements[match[1]];
  67112. s.overwrite(start, end, replacement);
  67113. }
  67114. if (!hasReplaced) {
  67115. return null;
  67116. }
  67117. const result = { code: s.toString() };
  67118. if (config.build.sourcemap) {
  67119. result.map = s.generateMap({ hires: true });
  67120. }
  67121. return result;
  67122. }
  67123. };
  67124. }
  67125. async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
  67126. const isBuild = config.command === 'build';
  67127. const buildPlugins = isBuild
  67128. ? (await Promise.resolve().then(function () { return build$1; })).resolveBuildPlugins(config)
  67129. : { pre: [], post: [] };
  67130. return [
  67131. isBuild ? null : preAliasPlugin(),
  67132. alias({ entries: config.resolve.alias }),
  67133. ...prePlugins,
  67134. config.build.polyfillModulePreload
  67135. ? modulePreloadPolyfillPlugin(config)
  67136. : null,
  67137. resolvePlugin({
  67138. ...config.resolve,
  67139. root: config.root,
  67140. isProduction: config.isProduction,
  67141. isBuild,
  67142. ssrConfig: config.ssr,
  67143. asSrc: true
  67144. }),
  67145. htmlInlineScriptProxyPlugin(),
  67146. cssPlugin(config),
  67147. config.esbuild !== false ? esbuildPlugin(config.esbuild) : null,
  67148. jsonPlugin({
  67149. namedExports: true,
  67150. ...config.json
  67151. }, isBuild),
  67152. wasmPlugin(config),
  67153. webWorkerPlugin(config),
  67154. assetPlugin(config),
  67155. ...normalPlugins,
  67156. definePlugin(config),
  67157. cssPostPlugin(config),
  67158. ...buildPlugins.pre,
  67159. ...postPlugins,
  67160. ...buildPlugins.post,
  67161. // internal server-only plugins are always applied after everything else
  67162. ...(isBuild
  67163. ? []
  67164. : [clientInjectionsPlugin(config), importAnalysisPlugin(config)])
  67165. ].filter(Boolean);
  67166. }
  67167. var main$1 = {};
  67168. /* @flow */
  67169. /*::
  67170. type DotenvParseOptions = {
  67171. debug?: boolean
  67172. }
  67173. // keys and values from src
  67174. type DotenvParseOutput = { [string]: string }
  67175. type DotenvConfigOptions = {
  67176. path?: string, // path to .env file
  67177. encoding?: string, // encoding of .env file
  67178. debug?: string // turn on logging for debugging purposes
  67179. }
  67180. type DotenvConfigOutput = {
  67181. parsed?: DotenvParseOutput,
  67182. error?: Error
  67183. }
  67184. */
  67185. const fs = fs__default;
  67186. const path = path__default;
  67187. const os = require$$0__default$1;
  67188. function log (message /*: string */) {
  67189. console.log(`[dotenv][DEBUG] ${message}`);
  67190. }
  67191. const NEWLINE = '\n';
  67192. const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/;
  67193. const RE_NEWLINES = /\\n/g;
  67194. const NEWLINES_MATCH = /\r\n|\n|\r/;
  67195. // Parses src into an Object
  67196. function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ {
  67197. const debug = Boolean(options && options.debug);
  67198. const obj = {};
  67199. // convert Buffers before splitting into lines and processing
  67200. src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) {
  67201. // matching "KEY' and 'VAL' in 'KEY=VAL'
  67202. const keyValueArr = line.match(RE_INI_KEY_VAL);
  67203. // matched?
  67204. if (keyValueArr != null) {
  67205. const key = keyValueArr[1];
  67206. // default undefined or missing values to empty string
  67207. let val = (keyValueArr[2] || '');
  67208. const end = val.length - 1;
  67209. const isDoubleQuoted = val[0] === '"' && val[end] === '"';
  67210. const isSingleQuoted = val[0] === "'" && val[end] === "'";
  67211. // if single or double quoted, remove quotes
  67212. if (isSingleQuoted || isDoubleQuoted) {
  67213. val = val.substring(1, end);
  67214. // if double quoted, expand newlines
  67215. if (isDoubleQuoted) {
  67216. val = val.replace(RE_NEWLINES, NEWLINE);
  67217. }
  67218. } else {
  67219. // remove surrounding whitespace
  67220. val = val.trim();
  67221. }
  67222. obj[key] = val;
  67223. } else if (debug) {
  67224. log(`did not match key and value when parsing line ${idx + 1}: ${line}`);
  67225. }
  67226. });
  67227. return obj
  67228. }
  67229. function resolveHome (envPath) {
  67230. return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
  67231. }
  67232. // Populates process.env from .env file
  67233. function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
  67234. let dotenvPath = path.resolve(process.cwd(), '.env');
  67235. let encoding /*: string */ = 'utf8';
  67236. let debug = false;
  67237. if (options) {
  67238. if (options.path != null) {
  67239. dotenvPath = resolveHome(options.path);
  67240. }
  67241. if (options.encoding != null) {
  67242. encoding = options.encoding;
  67243. }
  67244. if (options.debug != null) {
  67245. debug = true;
  67246. }
  67247. }
  67248. try {
  67249. // specifying an encoding returns a string instead of a buffer
  67250. const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug });
  67251. Object.keys(parsed).forEach(function (key) {
  67252. if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
  67253. process.env[key] = parsed[key];
  67254. } else if (debug) {
  67255. log(`"${key}" is already defined in \`process.env\` and will not be overwritten`);
  67256. }
  67257. });
  67258. return { parsed }
  67259. } catch (e) {
  67260. return { error: e }
  67261. }
  67262. }
  67263. main$1.config = config;
  67264. main$1.parse = parse;
  67265. var dotenvExpand = function (config) {
  67266. // if ignoring process.env, use a blank object
  67267. var environment = config.ignoreProcessEnv ? {} : process.env;
  67268. var interpolate = function (envValue) {
  67269. var matches = envValue.match(/(.?\${?(?:[a-zA-Z0-9_]+)?}?)/g) || [];
  67270. return matches.reduce(function (newEnv, match) {
  67271. var parts = /(.?)\${?([a-zA-Z0-9_]+)?}?/g.exec(match);
  67272. var prefix = parts[1];
  67273. var value, replacePart;
  67274. if (prefix === '\\') {
  67275. replacePart = parts[0];
  67276. value = replacePart.replace('\\$', '$');
  67277. } else {
  67278. var key = parts[2];
  67279. replacePart = parts[0].substring(prefix.length);
  67280. // process.env value 'wins' over .env file's value
  67281. value = environment.hasOwnProperty(key) ? environment[key] : (config.parsed[key] || '');
  67282. // Resolve recursive interpolations
  67283. value = interpolate(value);
  67284. }
  67285. return newEnv.replace(replacePart, value)
  67286. }, envValue)
  67287. };
  67288. for (var configKey in config.parsed) {
  67289. var value = environment.hasOwnProperty(configKey) ? environment[configKey] : config.parsed[configKey];
  67290. config.parsed[configKey] = interpolate(value);
  67291. }
  67292. for (var processKey in config.parsed) {
  67293. environment[processKey] = config.parsed[processKey];
  67294. }
  67295. return config
  67296. };
  67297. var main = dotenvExpand;
  67298. const debug = createDebugger('vite:config');
  67299. /**
  67300. * Type helper to make it easier to use vite.config.ts
  67301. * accepts a direct {@link UserConfig} object, or a function that returns it.
  67302. * The function receives a {@link ConfigEnv} object that exposes two properties:
  67303. * `command` (either `'build'` or `'serve'`), and `mode`.
  67304. */
  67305. function defineConfig(config) {
  67306. return config;
  67307. }
  67308. async function resolveConfig(inlineConfig, command, defaultMode = 'development') {
  67309. var _a, _b, _c, _d, _e, _f, _g;
  67310. let config = inlineConfig;
  67311. let configFileDependencies = [];
  67312. let mode = inlineConfig.mode || defaultMode;
  67313. // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting
  67314. // production-specific behavior, so set it here even though we haven't
  67315. // resolve the final mode yet
  67316. if (mode === 'production') {
  67317. process.env.NODE_ENV = 'production';
  67318. }
  67319. const configEnv = {
  67320. mode,
  67321. command
  67322. };
  67323. let { configFile } = config;
  67324. if (configFile !== false) {
  67325. const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel);
  67326. if (loadResult) {
  67327. config = mergeConfig(loadResult.config, config);
  67328. configFile = loadResult.path;
  67329. configFileDependencies = loadResult.dependencies;
  67330. }
  67331. }
  67332. // Define logger
  67333. const logger = createLogger(config.logLevel, {
  67334. allowClearScreen: config.clearScreen,
  67335. customLogger: config.customLogger
  67336. });
  67337. // user config may provide an alternative mode. But --mode has a higher prority
  67338. mode = inlineConfig.mode || config.mode || mode;
  67339. configEnv.mode = mode;
  67340. // resolve plugins
  67341. const rawUserPlugins = (config.plugins || []).flat().filter((p) => {
  67342. return p && (!p.apply || p.apply === command);
  67343. });
  67344. const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins);
  67345. // run config hooks
  67346. const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
  67347. for (const p of userPlugins) {
  67348. if (p.config) {
  67349. const res = await p.config(config, configEnv);
  67350. if (res) {
  67351. config = mergeConfig(config, res);
  67352. }
  67353. }
  67354. }
  67355. // resolve root
  67356. const resolvedRoot = normalizePath$4(config.root ? path__default.resolve(config.root) : process.cwd());
  67357. const clientAlias = [
  67358. { find: /^[\/]?@vite\/env/, replacement: () => ENV_ENTRY },
  67359. { find: /^[\/]?@vite\/client/, replacement: () => CLIENT_ENTRY }
  67360. ];
  67361. // resolve alias with internal client alias
  67362. const resolvedAlias = mergeAlias(
  67363. // @ts-ignore because @rollup/plugin-alias' type doesn't allow function
  67364. // replacement, but its implementation does work with function values.
  67365. clientAlias, ((_a = config.resolve) === null || _a === void 0 ? void 0 : _a.alias) || config.alias || []);
  67366. const resolveOptions = {
  67367. dedupe: config.dedupe,
  67368. ...config.resolve,
  67369. alias: resolvedAlias
  67370. };
  67371. // load .env files
  67372. const envDir = config.envDir
  67373. ? normalizePath$4(path__default.resolve(resolvedRoot, config.envDir))
  67374. : resolvedRoot;
  67375. const userEnv = inlineConfig.envFile !== false &&
  67376. loadEnv(mode, envDir, resolveEnvPrefix(config));
  67377. // Note it is possible for user to have a custom mode, e.g. `staging` where
  67378. // production-like behavior is expected. This is indicated by NODE_ENV=production
  67379. // loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV
  67380. const isProduction = (process.env.VITE_USER_NODE_ENV || mode) === 'production';
  67381. if (isProduction) {
  67382. // in case default mode was not production and is overwritten
  67383. process.env.NODE_ENV = 'production';
  67384. }
  67385. // resolve public base url
  67386. const BASE_URL = resolveBaseUrl(config.base, command === 'build', logger);
  67387. const resolvedBuildOptions = resolveBuildOptions(config.build);
  67388. // resolve cache directory
  67389. const pkgPath = lookupFile(resolvedRoot, [`package.json`], true /* pathOnly */);
  67390. const cacheDir = config.cacheDir
  67391. ? path__default.resolve(resolvedRoot, config.cacheDir)
  67392. : pkgPath && path__default.join(path__default.dirname(pkgPath), `node_modules/.vite`);
  67393. const assetsFilter = config.assetsInclude
  67394. ? createFilter$1(config.assetsInclude)
  67395. : () => false;
  67396. // create an internal resolver to be used in special scenarios, e.g.
  67397. // optimizer & handling css @imports
  67398. const createResolver = (options) => {
  67399. let aliasContainer;
  67400. let resolverContainer;
  67401. return async (id, importer, aliasOnly, ssr) => {
  67402. var _a;
  67403. let container;
  67404. if (aliasOnly) {
  67405. container =
  67406. aliasContainer ||
  67407. (aliasContainer = await createPluginContainer({
  67408. ...resolved,
  67409. plugins: [alias({ entries: resolved.resolve.alias })]
  67410. }));
  67411. }
  67412. else {
  67413. container =
  67414. resolverContainer ||
  67415. (resolverContainer = await createPluginContainer({
  67416. ...resolved,
  67417. plugins: [
  67418. alias({ entries: resolved.resolve.alias }),
  67419. resolvePlugin({
  67420. ...resolved.resolve,
  67421. root: resolvedRoot,
  67422. isProduction,
  67423. isBuild: command === 'build',
  67424. ssrConfig: resolved.ssr,
  67425. asSrc: true,
  67426. preferRelative: false,
  67427. tryIndex: true,
  67428. ...options
  67429. })
  67430. ]
  67431. }));
  67432. }
  67433. return (_a = (await container.resolveId(id, importer, undefined, ssr))) === null || _a === void 0 ? void 0 : _a.id;
  67434. };
  67435. };
  67436. const { publicDir } = config;
  67437. const resolvedPublicDir = publicDir !== false && publicDir !== ''
  67438. ? path__default.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public')
  67439. : '';
  67440. const resolved = {
  67441. ...config,
  67442. configFile: configFile ? normalizePath$4(configFile) : undefined,
  67443. configFileDependencies,
  67444. inlineConfig,
  67445. root: resolvedRoot,
  67446. base: BASE_URL,
  67447. resolve: resolveOptions,
  67448. publicDir: resolvedPublicDir,
  67449. cacheDir,
  67450. command,
  67451. mode,
  67452. isProduction,
  67453. plugins: userPlugins,
  67454. server: resolveServerOptions(resolvedRoot, config.server),
  67455. build: resolvedBuildOptions,
  67456. env: {
  67457. ...userEnv,
  67458. BASE_URL,
  67459. MODE: mode,
  67460. DEV: !isProduction,
  67461. PROD: isProduction
  67462. },
  67463. assetsInclude(file) {
  67464. return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
  67465. },
  67466. logger,
  67467. createResolver,
  67468. optimizeDeps: {
  67469. ...config.optimizeDeps,
  67470. esbuildOptions: {
  67471. keepNames: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.keepNames,
  67472. ...(_c = config.optimizeDeps) === null || _c === void 0 ? void 0 : _c.esbuildOptions
  67473. }
  67474. }
  67475. };
  67476. resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
  67477. // call configResolved hooks
  67478. await Promise.all(userPlugins.map((p) => { var _a; return (_a = p.configResolved) === null || _a === void 0 ? void 0 : _a.call(p, resolved); }));
  67479. if (process.env.DEBUG) {
  67480. debug(`using resolved config: %O`, {
  67481. ...resolved,
  67482. plugins: resolved.plugins.map((p) => p.name)
  67483. });
  67484. }
  67485. // TODO Deprecation warnings - remove when out of beta
  67486. const logDeprecationWarning = (deprecatedOption, hint, error) => {
  67487. logger.warn(source.yellow.bold(`(!) "${deprecatedOption}" option is deprecated. ${hint}${error ? `\n${error.stack}` : ''}`));
  67488. };
  67489. if ((_d = config.build) === null || _d === void 0 ? void 0 : _d.base) {
  67490. logDeprecationWarning('build.base', '"base" is now a root-level config option.');
  67491. config.base = config.build.base;
  67492. }
  67493. Object.defineProperty(resolvedBuildOptions, 'base', {
  67494. enumerable: false,
  67495. get() {
  67496. logDeprecationWarning('build.base', '"base" is now a root-level config option.', new Error());
  67497. return resolved.base;
  67498. }
  67499. });
  67500. if (config.alias) {
  67501. logDeprecationWarning('alias', 'Use "resolve.alias" instead.');
  67502. }
  67503. Object.defineProperty(resolved, 'alias', {
  67504. enumerable: false,
  67505. get() {
  67506. logDeprecationWarning('alias', 'Use "resolve.alias" instead.', new Error());
  67507. return resolved.resolve.alias;
  67508. }
  67509. });
  67510. if (config.dedupe) {
  67511. logDeprecationWarning('dedupe', 'Use "resolve.dedupe" instead.');
  67512. }
  67513. Object.defineProperty(resolved, 'dedupe', {
  67514. enumerable: false,
  67515. get() {
  67516. logDeprecationWarning('dedupe', 'Use "resolve.dedupe" instead.', new Error());
  67517. return resolved.resolve.dedupe;
  67518. }
  67519. });
  67520. if ((_e = config.optimizeDeps) === null || _e === void 0 ? void 0 : _e.keepNames) {
  67521. logDeprecationWarning('optimizeDeps.keepNames', 'Use "optimizeDeps.esbuildOptions.keepNames" instead.');
  67522. }
  67523. Object.defineProperty(resolved.optimizeDeps, 'keepNames', {
  67524. enumerable: false,
  67525. get() {
  67526. var _a;
  67527. logDeprecationWarning('optimizeDeps.keepNames', 'Use "optimizeDeps.esbuildOptions.keepNames" instead.', new Error());
  67528. return (_a = resolved.optimizeDeps.esbuildOptions) === null || _a === void 0 ? void 0 : _a.keepNames;
  67529. }
  67530. });
  67531. if ((_f = config.build) === null || _f === void 0 ? void 0 : _f.polyfillDynamicImport) {
  67532. logDeprecationWarning('build.polyfillDynamicImport', '"polyfillDynamicImport" has been removed. Please use @vitejs/plugin-legacy if your target browsers do not support dynamic imports.');
  67533. }
  67534. Object.defineProperty(resolvedBuildOptions, 'polyfillDynamicImport', {
  67535. enumerable: false,
  67536. get() {
  67537. logDeprecationWarning('build.polyfillDynamicImport', '"polyfillDynamicImport" has been removed. Please use @vitejs/plugin-legacy if your target browsers do not support dynamic imports.', new Error());
  67538. return false;
  67539. }
  67540. });
  67541. if ((_g = config.build) === null || _g === void 0 ? void 0 : _g.cleanCssOptions) {
  67542. logDeprecationWarning('build.cleanCssOptions', 'Vite now uses esbuild for CSS minification.');
  67543. }
  67544. return resolved;
  67545. }
  67546. /**
  67547. * Resolve base. Note that some users use Vite to build for non-web targets like
  67548. * electron or expects to deploy
  67549. */
  67550. function resolveBaseUrl(base = '/', isBuild, logger) {
  67551. // #1669 special treatment for empty for same dir relative base
  67552. if (base === '' || base === './') {
  67553. return isBuild ? base : '/';
  67554. }
  67555. if (base.startsWith('.')) {
  67556. logger.warn(source.yellow.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
  67557. `URL, ./, or an empty string.`));
  67558. base = '/';
  67559. }
  67560. // external URL
  67561. if (isExternalUrl(base)) {
  67562. if (!isBuild) {
  67563. // get base from full url during dev
  67564. const parsed = require$$0$a.parse(base);
  67565. base = parsed.pathname || '/';
  67566. }
  67567. }
  67568. else {
  67569. // ensure leading slash
  67570. if (!base.startsWith('/')) {
  67571. logger.warn(source.yellow.bold(`(!) "base" option should start with a slash.`));
  67572. base = '/' + base;
  67573. }
  67574. }
  67575. // ensure ending slash
  67576. if (!base.endsWith('/')) {
  67577. logger.warn(source.yellow.bold(`(!) "base" option should end with a slash.`));
  67578. base += '/';
  67579. }
  67580. return base;
  67581. }
  67582. function mergeConfigRecursively(a, b, rootPath) {
  67583. const merged = { ...a };
  67584. for (const key in b) {
  67585. const value = b[key];
  67586. if (value == null) {
  67587. continue;
  67588. }
  67589. const existing = merged[key];
  67590. if (Array.isArray(existing) && Array.isArray(value)) {
  67591. merged[key] = [...existing, ...value];
  67592. continue;
  67593. }
  67594. if (isObject$3(existing) && isObject$3(value)) {
  67595. merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
  67596. continue;
  67597. }
  67598. // fields that require special handling
  67599. if (existing != null) {
  67600. if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
  67601. merged[key] = mergeAlias(existing, value);
  67602. continue;
  67603. }
  67604. else if (key === 'assetsInclude' && rootPath === '') {
  67605. merged[key] = [].concat(existing, value);
  67606. continue;
  67607. }
  67608. else if (key === 'noExternal' && existing === true) {
  67609. continue;
  67610. }
  67611. }
  67612. merged[key] = value;
  67613. }
  67614. return merged;
  67615. }
  67616. function mergeConfig(a, b, isRoot = true) {
  67617. return mergeConfigRecursively(a, b, isRoot ? '' : '.');
  67618. }
  67619. function mergeAlias(a = [], b = []) {
  67620. return [...normalizeAlias(a), ...normalizeAlias(b)];
  67621. }
  67622. function normalizeAlias(o) {
  67623. return Array.isArray(o)
  67624. ? o.map(normalizeSingleAlias)
  67625. : Object.keys(o).map((find) => normalizeSingleAlias({
  67626. find,
  67627. replacement: o[find]
  67628. }));
  67629. }
  67630. // https://github.com/vitejs/vite/issues/1363
  67631. // work around https://github.com/rollup/plugins/issues/759
  67632. function normalizeSingleAlias({ find, replacement }) {
  67633. if (typeof find === 'string' &&
  67634. find.endsWith('/') &&
  67635. replacement.endsWith('/')) {
  67636. find = find.slice(0, find.length - 1);
  67637. replacement = replacement.slice(0, replacement.length - 1);
  67638. }
  67639. return { find, replacement };
  67640. }
  67641. function sortUserPlugins(plugins) {
  67642. const prePlugins = [];
  67643. const postPlugins = [];
  67644. const normalPlugins = [];
  67645. if (plugins) {
  67646. plugins.flat().forEach((p) => {
  67647. if (p.enforce === 'pre')
  67648. prePlugins.push(p);
  67649. else if (p.enforce === 'post')
  67650. postPlugins.push(p);
  67651. else
  67652. normalPlugins.push(p);
  67653. });
  67654. }
  67655. return [prePlugins, normalPlugins, postPlugins];
  67656. }
  67657. async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) {
  67658. const start = Date.now();
  67659. let resolvedPath;
  67660. let isTS = false;
  67661. let isMjs = false;
  67662. let dependencies = [];
  67663. // check package.json for type: "module" and set `isMjs` to true
  67664. try {
  67665. const pkg = lookupFile(configRoot, ['package.json']);
  67666. if (pkg && JSON.parse(pkg).type === 'module') {
  67667. isMjs = true;
  67668. }
  67669. }
  67670. catch (e) { }
  67671. if (configFile) {
  67672. // explicit config path is always resolved from cwd
  67673. resolvedPath = path__default.resolve(configFile);
  67674. isTS = configFile.endsWith('.ts');
  67675. }
  67676. else {
  67677. // implicit config file loaded from inline root (if present)
  67678. // otherwise from cwd
  67679. const jsconfigFile = path__default.resolve(configRoot, 'vite.config.js');
  67680. if (fs__default.existsSync(jsconfigFile)) {
  67681. resolvedPath = jsconfigFile;
  67682. }
  67683. if (!resolvedPath) {
  67684. const mjsconfigFile = path__default.resolve(configRoot, 'vite.config.mjs');
  67685. if (fs__default.existsSync(mjsconfigFile)) {
  67686. resolvedPath = mjsconfigFile;
  67687. isMjs = true;
  67688. }
  67689. }
  67690. if (!resolvedPath) {
  67691. const tsconfigFile = path__default.resolve(configRoot, 'vite.config.ts');
  67692. if (fs__default.existsSync(tsconfigFile)) {
  67693. resolvedPath = tsconfigFile;
  67694. isTS = true;
  67695. }
  67696. }
  67697. }
  67698. if (!resolvedPath) {
  67699. debug('no config file found.');
  67700. return null;
  67701. }
  67702. try {
  67703. let userConfig;
  67704. if (isMjs) {
  67705. const fileUrl = require('url').pathToFileURL(resolvedPath);
  67706. if (isTS) {
  67707. // before we can register loaders without requiring users to run node
  67708. // with --experimental-loader themselves, we have to do a hack here:
  67709. // bundle the config file w/ ts transforms first, write it to disk,
  67710. // load it with native Node ESM, then delete the file.
  67711. const bundled = await bundleConfigFile(resolvedPath, true);
  67712. dependencies = bundled.dependencies;
  67713. fs__default.writeFileSync(resolvedPath + '.js', bundled.code);
  67714. userConfig = (await eval(`import(fileUrl + '.js?t=${Date.now()}')`))
  67715. .default;
  67716. fs__default.unlinkSync(resolvedPath + '.js');
  67717. debug(`TS + native esm config loaded in ${Date.now() - start}ms`, fileUrl);
  67718. }
  67719. else {
  67720. // using eval to avoid this from being compiled away by TS/Rollup
  67721. // append a query so that we force reload fresh config in case of
  67722. // server restart
  67723. userConfig = (await eval(`import(fileUrl + '?t=${Date.now()}')`))
  67724. .default;
  67725. debug(`native esm config loaded in ${Date.now() - start}ms`, fileUrl);
  67726. }
  67727. }
  67728. if (!userConfig && !isTS && !isMjs) {
  67729. // 1. try to directly require the module (assuming commonjs)
  67730. try {
  67731. // clear cache in case of server restart
  67732. delete require.cache[require.resolve(resolvedPath)];
  67733. userConfig = require(resolvedPath);
  67734. debug(`cjs config loaded in ${Date.now() - start}ms`);
  67735. }
  67736. catch (e) {
  67737. const ignored = new RegExp([
  67738. `Cannot use import statement`,
  67739. `Must use import to load ES Module`,
  67740. // #1635, #2050 some Node 12.x versions don't have esm detection
  67741. // so it throws normal syntax errors when encountering esm syntax
  67742. `Unexpected token`,
  67743. `Unexpected identifier`
  67744. ].join('|'));
  67745. if (!ignored.test(e.message)) {
  67746. throw e;
  67747. }
  67748. }
  67749. }
  67750. if (!userConfig) {
  67751. // 2. if we reach here, the file is ts or using es import syntax, or
  67752. // the user has type: "module" in their package.json (#917)
  67753. // transpile es import syntax to require syntax using rollup.
  67754. // lazy require rollup (it's actually in dependencies)
  67755. const bundled = await bundleConfigFile(resolvedPath);
  67756. dependencies = bundled.dependencies;
  67757. userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code);
  67758. debug(`bundled config file loaded in ${Date.now() - start}ms`);
  67759. }
  67760. const config = await (typeof userConfig === 'function'
  67761. ? userConfig(configEnv)
  67762. : userConfig);
  67763. if (!isObject$3(config)) {
  67764. throw new Error(`config must export or return an object.`);
  67765. }
  67766. return {
  67767. path: normalizePath$4(resolvedPath),
  67768. config,
  67769. dependencies
  67770. };
  67771. }
  67772. catch (e) {
  67773. createLogger(logLevel).error(source.red(`failed to load config from ${resolvedPath}`), { error: e });
  67774. throw e;
  67775. }
  67776. }
  67777. async function bundleConfigFile(fileName, mjs = false) {
  67778. const result = await esbuild.build({
  67779. absWorkingDir: process.cwd(),
  67780. entryPoints: [fileName],
  67781. outfile: 'out.js',
  67782. write: false,
  67783. platform: 'node',
  67784. bundle: true,
  67785. format: mjs ? 'esm' : 'cjs',
  67786. sourcemap: 'inline',
  67787. metafile: true,
  67788. plugins: [
  67789. {
  67790. name: 'externalize-deps',
  67791. setup(build) {
  67792. build.onResolve({ filter: /.*/ }, (args) => {
  67793. const id = args.path;
  67794. if (id[0] !== '.' && !path__default.isAbsolute(id)) {
  67795. return {
  67796. external: true
  67797. };
  67798. }
  67799. });
  67800. }
  67801. },
  67802. {
  67803. name: 'replace-import-meta',
  67804. setup(build) {
  67805. build.onLoad({ filter: /\.[jt]s$/ }, async (args) => {
  67806. const contents = await fs__default.promises.readFile(args.path, 'utf8');
  67807. return {
  67808. loader: args.path.endsWith('.ts') ? 'ts' : 'js',
  67809. contents: contents
  67810. .replace(/\bimport\.meta\.url\b/g, JSON.stringify(`file://${args.path}`))
  67811. .replace(/\b__dirname\b/g, JSON.stringify(path__default.dirname(args.path)))
  67812. .replace(/\b__filename\b/g, JSON.stringify(args.path))
  67813. };
  67814. });
  67815. }
  67816. }
  67817. ]
  67818. });
  67819. const { text } = result.outputFiles[0];
  67820. return {
  67821. code: text,
  67822. dependencies: result.metafile ? Object.keys(result.metafile.inputs) : []
  67823. };
  67824. }
  67825. async function loadConfigFromBundledFile(fileName, bundledCode) {
  67826. const extension = path__default.extname(fileName);
  67827. const defaultLoader = require.extensions[extension];
  67828. require.extensions[extension] = (module, filename) => {
  67829. if (filename === fileName) {
  67830. module._compile(bundledCode, filename);
  67831. }
  67832. else {
  67833. defaultLoader(module, filename);
  67834. }
  67835. };
  67836. // clear cache in case of server restart
  67837. delete require.cache[require.resolve(fileName)];
  67838. const raw = require(fileName);
  67839. const config = raw.__esModule ? raw.default : raw;
  67840. require.extensions[extension] = defaultLoader;
  67841. return config;
  67842. }
  67843. function loadEnv(mode, envDir, prefixes = 'VITE_') {
  67844. if (mode === 'local') {
  67845. throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
  67846. `the .local postfix for .env files.`);
  67847. }
  67848. prefixes = arraify(prefixes);
  67849. const env = {};
  67850. const envFiles = [
  67851. /** mode local file */ `.env.${mode}.local`,
  67852. /** mode file */ `.env.${mode}`,
  67853. /** local file */ `.env.local`,
  67854. /** default file */ `.env`
  67855. ];
  67856. // check if there are actual env variables starting with VITE_*
  67857. // these are typically provided inline and should be prioritized
  67858. for (const key in process.env) {
  67859. if (prefixes.some((prefix) => key.startsWith(prefix)) &&
  67860. env[key] === undefined) {
  67861. env[key] = process.env[key];
  67862. }
  67863. }
  67864. for (const file of envFiles) {
  67865. const path = lookupFile(envDir, [file], true);
  67866. if (path) {
  67867. const parsed = main$1.parse(fs__default.readFileSync(path), {
  67868. debug: !!process.env.DEBUG || undefined
  67869. });
  67870. // let environment variables use each other
  67871. main({
  67872. parsed,
  67873. // prevent process.env mutation
  67874. ignoreProcessEnv: true
  67875. });
  67876. // only keys that start with prefix are exposed to client
  67877. for (const [key, value] of Object.entries(parsed)) {
  67878. if (prefixes.some((prefix) => key.startsWith(prefix)) &&
  67879. env[key] === undefined) {
  67880. env[key] = value;
  67881. }
  67882. else if (key === 'NODE_ENV') {
  67883. // NODE_ENV override in .env file
  67884. process.env.VITE_USER_NODE_ENV = value;
  67885. }
  67886. }
  67887. }
  67888. }
  67889. return env;
  67890. }
  67891. function resolveEnvPrefix({ envPrefix = 'VITE_' }) {
  67892. envPrefix = arraify(envPrefix);
  67893. if (envPrefix.some((prefix) => prefix === '')) {
  67894. throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
  67895. }
  67896. return envPrefix;
  67897. }
  67898. exports.build = build;
  67899. exports.build$1 = build$1;
  67900. exports.commonjsGlobal = commonjsGlobal;
  67901. exports.connect = connect;
  67902. exports.corsMiddleware = corsMiddleware;
  67903. exports.createLogger = createLogger;
  67904. exports.createServer = createServer;
  67905. exports.defineConfig = defineConfig;
  67906. exports.getAugmentedNamespace = getAugmentedNamespace;
  67907. exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
  67908. exports.httpServerStart = httpServerStart;
  67909. exports.index = index$1;
  67910. exports.index$1 = index;
  67911. exports.loadConfigFromFile = loadConfigFromFile;
  67912. exports.loadEnv = loadEnv;
  67913. exports.mergeConfig = mergeConfig;
  67914. exports.ms = ms;
  67915. exports.normalizePath = normalizePath$4;
  67916. exports.openBrowser = openBrowser;
  67917. exports.optimizeDeps = optimizeDeps;
  67918. exports.printServerUrls = printServerUrls;
  67919. exports.proxyMiddleware = proxyMiddleware;
  67920. exports.resolveConfig = resolveConfig;
  67921. exports.resolveEnvPrefix = resolveEnvPrefix;
  67922. exports.resolveHostname = resolveHostname;
  67923. exports.resolveHttpServer = resolveHttpServer;
  67924. exports.resolveHttpsConfig = resolveHttpsConfig;
  67925. exports.resolvePackageData = resolvePackageData;
  67926. exports.resolvePackageEntry = resolvePackageEntry;
  67927. exports.safeBuffer = safeBuffer;
  67928. exports.send = send$1;
  67929. exports.sirv = sirv;
  67930. exports.sortUserPlugins = sortUserPlugins;
  67931. exports.source = source;
  67932. exports.vary = vary$1;
  67933. exports.walk = walk$1;
  67934. //# sourceMappingURL=dep-1be34a63.js.map