watch.js 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001
  1. /*
  2. @license
  3. Rollup.js v2.72.1
  4. Sat, 07 May 2022 19:04:43 GMT - commit 8c6e0f319b792ea52fe979888593b6523315ae93
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import require$$0$2, { resolve } from 'path';
  9. import process$1 from 'process';
  10. import { defaultOnWarn, ensureArray, warnUnknownOptions, objectifyOptionWithPresets, treeshakePresets, objectifyOption, generatedCodePresets, picomatch as picomatch$2, getAugmentedNamespace, fseventsImporter, createFilter, rollupInternal } from './rollup.js';
  11. import require$$2$1, { platform } from 'os';
  12. import require$$0$1 from 'fs';
  13. import require$$2 from 'util';
  14. import require$$1 from 'stream';
  15. import require$$0$3 from 'events';
  16. import 'perf_hooks';
  17. import 'crypto';
  18. const commandAliases = {
  19. c: 'config',
  20. d: 'dir',
  21. e: 'external',
  22. f: 'format',
  23. g: 'globals',
  24. h: 'help',
  25. i: 'input',
  26. m: 'sourcemap',
  27. n: 'name',
  28. o: 'file',
  29. p: 'plugin',
  30. v: 'version',
  31. w: 'watch'
  32. };
  33. function mergeOptions(config, rawCommandOptions = { external: [], globals: undefined }, defaultOnWarnHandler = defaultOnWarn) {
  34. const command = getCommandOptions(rawCommandOptions);
  35. const inputOptions = mergeInputOptions(config, command, defaultOnWarnHandler);
  36. const warn = inputOptions.onwarn;
  37. if (command.output) {
  38. Object.assign(command, command.output);
  39. }
  40. const outputOptionsArray = ensureArray(config.output);
  41. if (outputOptionsArray.length === 0)
  42. outputOptionsArray.push({});
  43. const outputOptions = outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, warn));
  44. warnUnknownOptions(command, Object.keys(inputOptions).concat(Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapPathTransform'), Object.keys(commandAliases), 'config', 'environment', 'plugin', 'silent', 'failAfterWarnings', 'stdin', 'waitForBundleInput', 'configPlugin'), 'CLI flags', warn, /^_$|output$|config/);
  45. inputOptions.output = outputOptions;
  46. return inputOptions;
  47. }
  48. function getCommandOptions(rawCommandOptions) {
  49. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  50. ? rawCommandOptions.external.split(',')
  51. : [];
  52. return {
  53. ...rawCommandOptions,
  54. external,
  55. globals: typeof rawCommandOptions.globals === 'string'
  56. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  57. const [id, variableName] = globalDefinition.split(':');
  58. globals[id] = variableName;
  59. if (!external.includes(id)) {
  60. external.push(id);
  61. }
  62. return globals;
  63. }, Object.create(null))
  64. : undefined
  65. };
  66. }
  67. function mergeInputOptions(config, overrides, defaultOnWarnHandler) {
  68. const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };
  69. const inputOptions = {
  70. acorn: getOption('acorn'),
  71. acornInjectPlugins: config.acornInjectPlugins,
  72. cache: config.cache,
  73. context: getOption('context'),
  74. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  75. external: getExternal(config, overrides),
  76. inlineDynamicImports: getOption('inlineDynamicImports'),
  77. input: getOption('input') || [],
  78. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  79. manualChunks: getOption('manualChunks'),
  80. maxParallelFileReads: getOption('maxParallelFileReads'),
  81. moduleContext: getOption('moduleContext'),
  82. onwarn: getOnWarn(config, defaultOnWarnHandler),
  83. perf: getOption('perf'),
  84. plugins: ensureArray(config.plugins),
  85. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  86. preserveModules: getOption('preserveModules'),
  87. preserveSymlinks: getOption('preserveSymlinks'),
  88. shimMissingExports: getOption('shimMissingExports'),
  89. strictDeprecations: getOption('strictDeprecations'),
  90. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', 'false, true, ')),
  91. watch: getWatch(config, overrides)
  92. };
  93. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', inputOptions.onwarn, /^output$/);
  94. return inputOptions;
  95. }
  96. const getExternal = (config, overrides) => {
  97. const configExternal = config.external;
  98. return typeof configExternal === 'function'
  99. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  100. : ensureArray(configExternal).concat(overrides.external);
  101. };
  102. const getOnWarn = (config, defaultOnWarnHandler) => config.onwarn
  103. ? warning => config.onwarn(warning, defaultOnWarnHandler)
  104. : defaultOnWarnHandler;
  105. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  106. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  107. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  108. if (commandOption !== undefined) {
  109. return commandOption && { ...configOption, ...commandOption };
  110. }
  111. return configOption;
  112. };
  113. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  114. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  115. if (!optionValue) {
  116. return optionValue;
  117. }
  118. if (Array.isArray(optionValue)) {
  119. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  120. }
  121. return objectifyValue(optionValue);
  122. };
  123. function mergeOutputOptions(config, overrides, warn) {
  124. const getOption = (name) => { var _a; return (_a = overrides[name]) !== null && _a !== void 0 ? _a : config[name]; };
  125. const outputOptions = {
  126. amd: getObjectOption(config, overrides, 'amd'),
  127. assetFileNames: getOption('assetFileNames'),
  128. banner: getOption('banner'),
  129. chunkFileNames: getOption('chunkFileNames'),
  130. compact: getOption('compact'),
  131. dir: getOption('dir'),
  132. dynamicImportFunction: getOption('dynamicImportFunction'),
  133. entryFileNames: getOption('entryFileNames'),
  134. esModule: getOption('esModule'),
  135. exports: getOption('exports'),
  136. extend: getOption('extend'),
  137. externalLiveBindings: getOption('externalLiveBindings'),
  138. file: getOption('file'),
  139. footer: getOption('footer'),
  140. format: getOption('format'),
  141. freeze: getOption('freeze'),
  142. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', '')),
  143. globals: getOption('globals'),
  144. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  145. indent: getOption('indent'),
  146. inlineDynamicImports: getOption('inlineDynamicImports'),
  147. interop: getOption('interop'),
  148. intro: getOption('intro'),
  149. manualChunks: getOption('manualChunks'),
  150. minifyInternalExports: getOption('minifyInternalExports'),
  151. name: getOption('name'),
  152. namespaceToStringTag: getOption('namespaceToStringTag'),
  153. noConflict: getOption('noConflict'),
  154. outro: getOption('outro'),
  155. paths: getOption('paths'),
  156. plugins: ensureArray(config.plugins),
  157. preferConst: getOption('preferConst'),
  158. preserveModules: getOption('preserveModules'),
  159. preserveModulesRoot: getOption('preserveModulesRoot'),
  160. sanitizeFileName: getOption('sanitizeFileName'),
  161. sourcemap: getOption('sourcemap'),
  162. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  163. sourcemapFile: getOption('sourcemapFile'),
  164. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  165. strict: getOption('strict'),
  166. systemNullSetters: getOption('systemNullSetters'),
  167. validate: getOption('validate')
  168. };
  169. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', warn);
  170. return outputOptions;
  171. }
  172. var chokidar = {};
  173. const fs$3 = require$$0$1;
  174. const { Readable } = require$$1;
  175. const sysPath$3 = require$$0$2;
  176. const { promisify: promisify$3 } = require$$2;
  177. const picomatch$1 = picomatch$2.exports;
  178. const readdir$1 = promisify$3(fs$3.readdir);
  179. const stat$3 = promisify$3(fs$3.stat);
  180. const lstat$2 = promisify$3(fs$3.lstat);
  181. const realpath$1 = promisify$3(fs$3.realpath);
  182. /**
  183. * @typedef {Object} EntryInfo
  184. * @property {String} path
  185. * @property {String} fullPath
  186. * @property {fs.Stats=} stats
  187. * @property {fs.Dirent=} dirent
  188. * @property {String} basename
  189. */
  190. const BANG$2 = '!';
  191. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  192. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  193. const FILE_TYPE = 'files';
  194. const DIR_TYPE = 'directories';
  195. const FILE_DIR_TYPE = 'files_directories';
  196. const EVERYTHING_TYPE = 'all';
  197. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  198. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  199. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  200. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  201. const normalizeFilter = filter => {
  202. if (filter === undefined) return;
  203. if (typeof filter === 'function') return filter;
  204. if (typeof filter === 'string') {
  205. const glob = picomatch$1(filter.trim());
  206. return entry => glob(entry.basename);
  207. }
  208. if (Array.isArray(filter)) {
  209. const positive = [];
  210. const negative = [];
  211. for (const item of filter) {
  212. const trimmed = item.trim();
  213. if (trimmed.charAt(0) === BANG$2) {
  214. negative.push(picomatch$1(trimmed.slice(1)));
  215. } else {
  216. positive.push(picomatch$1(trimmed));
  217. }
  218. }
  219. if (negative.length > 0) {
  220. if (positive.length > 0) {
  221. return entry =>
  222. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  223. }
  224. return entry => !negative.some(f => f(entry.basename));
  225. }
  226. return entry => positive.some(f => f(entry.basename));
  227. }
  228. };
  229. class ReaddirpStream extends Readable {
  230. static get defaultOptions() {
  231. return {
  232. root: '.',
  233. /* eslint-disable no-unused-vars */
  234. fileFilter: (path) => true,
  235. directoryFilter: (path) => true,
  236. /* eslint-enable no-unused-vars */
  237. type: FILE_TYPE,
  238. lstat: false,
  239. depth: 2147483648,
  240. alwaysStat: false
  241. };
  242. }
  243. constructor(options = {}) {
  244. super({
  245. objectMode: true,
  246. autoDestroy: true,
  247. highWaterMark: options.highWaterMark || 4096
  248. });
  249. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  250. const { root, type } = opts;
  251. this._fileFilter = normalizeFilter(opts.fileFilter);
  252. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  253. const statMethod = opts.lstat ? lstat$2 : stat$3;
  254. // Use bigint stats if it's windows and stat() supports options (node 10+).
  255. if (wantBigintFsStats) {
  256. this._stat = path => statMethod(path, { bigint: true });
  257. } else {
  258. this._stat = statMethod;
  259. }
  260. this._maxDepth = opts.depth;
  261. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  262. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  263. this._wantsEverything = type === EVERYTHING_TYPE;
  264. this._root = sysPath$3.resolve(root);
  265. this._isDirent = ('Dirent' in fs$3) && !opts.alwaysStat;
  266. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  267. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  268. // Launch stream with one parent, the root dir.
  269. this.parents = [this._exploreDir(root, 1)];
  270. this.reading = false;
  271. this.parent = undefined;
  272. }
  273. async _read(batch) {
  274. if (this.reading) return;
  275. this.reading = true;
  276. try {
  277. while (!this.destroyed && batch > 0) {
  278. const { path, depth, files = [] } = this.parent || {};
  279. if (files.length > 0) {
  280. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  281. for (const entry of await Promise.all(slice)) {
  282. if (this.destroyed) return;
  283. const entryType = await this._getEntryType(entry);
  284. if (entryType === 'directory' && this._directoryFilter(entry)) {
  285. if (depth <= this._maxDepth) {
  286. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  287. }
  288. if (this._wantsDir) {
  289. this.push(entry);
  290. batch--;
  291. }
  292. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  293. if (this._wantsFile) {
  294. this.push(entry);
  295. batch--;
  296. }
  297. }
  298. }
  299. } else {
  300. const parent = this.parents.pop();
  301. if (!parent) {
  302. this.push(null);
  303. break;
  304. }
  305. this.parent = await parent;
  306. if (this.destroyed) return;
  307. }
  308. }
  309. } catch (error) {
  310. this.destroy(error);
  311. } finally {
  312. this.reading = false;
  313. }
  314. }
  315. async _exploreDir(path, depth) {
  316. let files;
  317. try {
  318. files = await readdir$1(path, this._rdOptions);
  319. } catch (error) {
  320. this._onError(error);
  321. }
  322. return { files, depth, path };
  323. }
  324. async _formatEntry(dirent, path) {
  325. let entry;
  326. try {
  327. const basename = this._isDirent ? dirent.name : dirent;
  328. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  329. entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
  330. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  331. } catch (err) {
  332. this._onError(err);
  333. }
  334. return entry;
  335. }
  336. _onError(err) {
  337. if (isNormalFlowError(err) && !this.destroyed) {
  338. this.emit('warn', err);
  339. } else {
  340. this.destroy(err);
  341. }
  342. }
  343. async _getEntryType(entry) {
  344. // entry may be undefined, because a warning or an error were emitted
  345. // and the statsProp is undefined
  346. const stats = entry && entry[this._statsProp];
  347. if (!stats) {
  348. return;
  349. }
  350. if (stats.isFile()) {
  351. return 'file';
  352. }
  353. if (stats.isDirectory()) {
  354. return 'directory';
  355. }
  356. if (stats && stats.isSymbolicLink()) {
  357. const full = entry.fullPath;
  358. try {
  359. const entryRealPath = await realpath$1(full);
  360. const entryRealPathStats = await lstat$2(entryRealPath);
  361. if (entryRealPathStats.isFile()) {
  362. return 'file';
  363. }
  364. if (entryRealPathStats.isDirectory()) {
  365. const len = entryRealPath.length;
  366. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  367. const recursiveError = new Error(
  368. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  369. );
  370. recursiveError.code = RECURSIVE_ERROR_CODE;
  371. return this._onError(recursiveError);
  372. }
  373. return 'directory';
  374. }
  375. } catch (error) {
  376. this._onError(error);
  377. }
  378. }
  379. }
  380. _includeAsFile(entry) {
  381. const stats = entry && entry[this._statsProp];
  382. return stats && this._wantsEverything && !stats.isDirectory();
  383. }
  384. }
  385. /**
  386. * @typedef {Object} ReaddirpArguments
  387. * @property {Function=} fileFilter
  388. * @property {Function=} directoryFilter
  389. * @property {String=} type
  390. * @property {Number=} depth
  391. * @property {String=} root
  392. * @property {Boolean=} lstat
  393. * @property {Boolean=} bigint
  394. */
  395. /**
  396. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  397. * @param {String} root Root directory
  398. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  399. */
  400. const readdirp$1 = (root, options = {}) => {
  401. let type = options.entryType || options.type;
  402. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  403. if (type) options.type = type;
  404. if (!root) {
  405. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  406. } else if (typeof root !== 'string') {
  407. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  408. } else if (type && !ALL_TYPES.includes(type)) {
  409. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  410. }
  411. options.root = root;
  412. return new ReaddirpStream(options);
  413. };
  414. const readdirpPromise = (root, options = {}) => {
  415. return new Promise((resolve, reject) => {
  416. const files = [];
  417. readdirp$1(root, options)
  418. .on('data', entry => files.push(entry))
  419. .on('end', () => resolve(files))
  420. .on('error', error => reject(error));
  421. });
  422. };
  423. readdirp$1.promise = readdirpPromise;
  424. readdirp$1.ReaddirpStream = ReaddirpStream;
  425. readdirp$1.default = readdirp$1;
  426. var readdirp_1 = readdirp$1;
  427. var anymatch$2 = {exports: {}};
  428. /*!
  429. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  430. *
  431. * Copyright (c) 2014-2018, Jon Schlinkert.
  432. * Released under the MIT License.
  433. */
  434. var normalizePath$2 = function(path, stripTrailing) {
  435. if (typeof path !== 'string') {
  436. throw new TypeError('expected path to be a string');
  437. }
  438. if (path === '\\' || path === '/') return '/';
  439. var len = path.length;
  440. if (len <= 1) return path;
  441. // ensure that win32 namespaces has two leading slashes, so that the path is
  442. // handled properly by the win32 version of path.parse() after being normalized
  443. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  444. var prefix = '';
  445. if (len > 4 && path[3] === '\\') {
  446. var ch = path[2];
  447. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  448. path = path.slice(2);
  449. prefix = '//';
  450. }
  451. }
  452. var segs = path.split(/[/\\]+/);
  453. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  454. segs.pop();
  455. }
  456. return prefix + segs.join('/');
  457. };
  458. Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
  459. const picomatch = picomatch$2.exports;
  460. const normalizePath$1 = normalizePath$2;
  461. /**
  462. * @typedef {(testString: string) => boolean} AnymatchFn
  463. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  464. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  465. */
  466. const BANG$1 = '!';
  467. const DEFAULT_OPTIONS = {returnIndex: false};
  468. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  469. /**
  470. * @param {AnymatchPattern} matcher
  471. * @param {object} options
  472. * @returns {AnymatchFn}
  473. */
  474. const createPattern = (matcher, options) => {
  475. if (typeof matcher === 'function') {
  476. return matcher;
  477. }
  478. if (typeof matcher === 'string') {
  479. const glob = picomatch(matcher, options);
  480. return (string) => matcher === string || glob(string);
  481. }
  482. if (matcher instanceof RegExp) {
  483. return (string) => matcher.test(string);
  484. }
  485. return (string) => false;
  486. };
  487. /**
  488. * @param {Array<Function>} patterns
  489. * @param {Array<Function>} negPatterns
  490. * @param {String|Array} args
  491. * @param {Boolean} returnIndex
  492. * @returns {boolean|number}
  493. */
  494. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  495. const isList = Array.isArray(args);
  496. const _path = isList ? args[0] : args;
  497. if (!isList && typeof _path !== 'string') {
  498. throw new TypeError('anymatch: second argument must be a string: got ' +
  499. Object.prototype.toString.call(_path))
  500. }
  501. const path = normalizePath$1(_path);
  502. for (let index = 0; index < negPatterns.length; index++) {
  503. const nglob = negPatterns[index];
  504. if (nglob(path)) {
  505. return returnIndex ? -1 : false;
  506. }
  507. }
  508. const applied = isList && [path].concat(args.slice(1));
  509. for (let index = 0; index < patterns.length; index++) {
  510. const pattern = patterns[index];
  511. if (isList ? pattern(...applied) : pattern(path)) {
  512. return returnIndex ? index : true;
  513. }
  514. }
  515. return returnIndex ? -1 : false;
  516. };
  517. /**
  518. * @param {AnymatchMatcher} matchers
  519. * @param {Array|string} testString
  520. * @param {object} options
  521. * @returns {boolean|number|Function}
  522. */
  523. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  524. if (matchers == null) {
  525. throw new TypeError('anymatch: specify first argument');
  526. }
  527. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  528. const returnIndex = opts.returnIndex || false;
  529. // Early cache for matchers.
  530. const mtchers = arrify$1(matchers);
  531. const negatedGlobs = mtchers
  532. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  533. .map(item => item.slice(1))
  534. .map(item => picomatch(item, opts));
  535. const patterns = mtchers
  536. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
  537. .map(matcher => createPattern(matcher, opts));
  538. if (testString == null) {
  539. return (testString, ri = false) => {
  540. const returnIndex = typeof ri === 'boolean' ? ri : false;
  541. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  542. }
  543. }
  544. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  545. };
  546. anymatch$1.default = anymatch$1;
  547. anymatch$2.exports = anymatch$1;
  548. /*!
  549. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  550. *
  551. * Copyright (c) 2014-2016, Jon Schlinkert.
  552. * Licensed under the MIT License.
  553. */
  554. var isExtglob$1 = function isExtglob(str) {
  555. if (typeof str !== 'string' || str === '') {
  556. return false;
  557. }
  558. var match;
  559. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  560. if (match[2]) return true;
  561. str = str.slice(match.index + match[0].length);
  562. }
  563. return false;
  564. };
  565. /*!
  566. * is-glob <https://github.com/jonschlinkert/is-glob>
  567. *
  568. * Copyright (c) 2014-2017, Jon Schlinkert.
  569. * Released under the MIT License.
  570. */
  571. var isExtglob = isExtglob$1;
  572. var chars = { '{': '}', '(': ')', '[': ']'};
  573. var strictCheck = function(str) {
  574. if (str[0] === '!') {
  575. return true;
  576. }
  577. var index = 0;
  578. var pipeIndex = -2;
  579. var closeSquareIndex = -2;
  580. var closeCurlyIndex = -2;
  581. var closeParenIndex = -2;
  582. var backSlashIndex = -2;
  583. while (index < str.length) {
  584. if (str[index] === '*') {
  585. return true;
  586. }
  587. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  588. return true;
  589. }
  590. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  591. if (closeSquareIndex < index) {
  592. closeSquareIndex = str.indexOf(']', index);
  593. }
  594. if (closeSquareIndex > index) {
  595. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  596. return true;
  597. }
  598. backSlashIndex = str.indexOf('\\', index);
  599. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  600. return true;
  601. }
  602. }
  603. }
  604. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  605. closeCurlyIndex = str.indexOf('}', index);
  606. if (closeCurlyIndex > index) {
  607. backSlashIndex = str.indexOf('\\', index);
  608. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  609. return true;
  610. }
  611. }
  612. }
  613. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  614. closeParenIndex = str.indexOf(')', index);
  615. if (closeParenIndex > index) {
  616. backSlashIndex = str.indexOf('\\', index);
  617. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  618. return true;
  619. }
  620. }
  621. }
  622. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  623. if (pipeIndex < index) {
  624. pipeIndex = str.indexOf('|', index);
  625. }
  626. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  627. closeParenIndex = str.indexOf(')', pipeIndex);
  628. if (closeParenIndex > pipeIndex) {
  629. backSlashIndex = str.indexOf('\\', pipeIndex);
  630. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  631. return true;
  632. }
  633. }
  634. }
  635. }
  636. if (str[index] === '\\') {
  637. var open = str[index + 1];
  638. index += 2;
  639. var close = chars[open];
  640. if (close) {
  641. var n = str.indexOf(close, index);
  642. if (n !== -1) {
  643. index = n + 1;
  644. }
  645. }
  646. if (str[index] === '!') {
  647. return true;
  648. }
  649. } else {
  650. index++;
  651. }
  652. }
  653. return false;
  654. };
  655. var relaxedCheck = function(str) {
  656. if (str[0] === '!') {
  657. return true;
  658. }
  659. var index = 0;
  660. while (index < str.length) {
  661. if (/[*?{}()[\]]/.test(str[index])) {
  662. return true;
  663. }
  664. if (str[index] === '\\') {
  665. var open = str[index + 1];
  666. index += 2;
  667. var close = chars[open];
  668. if (close) {
  669. var n = str.indexOf(close, index);
  670. if (n !== -1) {
  671. index = n + 1;
  672. }
  673. }
  674. if (str[index] === '!') {
  675. return true;
  676. }
  677. } else {
  678. index++;
  679. }
  680. }
  681. return false;
  682. };
  683. var isGlob$2 = function isGlob(str, options) {
  684. if (typeof str !== 'string' || str === '') {
  685. return false;
  686. }
  687. if (isExtglob(str)) {
  688. return true;
  689. }
  690. var check = strictCheck;
  691. // optionally relax check
  692. if (options && options.strict === false) {
  693. check = relaxedCheck;
  694. }
  695. return check(str);
  696. };
  697. var isGlob$1 = isGlob$2;
  698. var pathPosixDirname = require$$0$2.posix.dirname;
  699. var isWin32 = require$$2$1.platform() === 'win32';
  700. var slash = '/';
  701. var backslash = /\\/g;
  702. var enclosure = /[\{\[].*[\}\]]$/;
  703. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  704. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  705. /**
  706. * @param {string} str
  707. * @param {Object} opts
  708. * @param {boolean} [opts.flipBackslashes=true]
  709. * @returns {string}
  710. */
  711. var globParent$1 = function globParent(str, opts) {
  712. var options = Object.assign({ flipBackslashes: true }, opts);
  713. // flip windows path separators
  714. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  715. str = str.replace(backslash, slash);
  716. }
  717. // special case for strings ending in enclosure containing path separator
  718. if (enclosure.test(str)) {
  719. str += slash;
  720. }
  721. // preserves full path in case of trailing path separator
  722. str += 'a';
  723. // remove path parts that are globby
  724. do {
  725. str = pathPosixDirname(str);
  726. } while (isGlob$1(str) || globby.test(str));
  727. // remove escape chars and return result
  728. return str.replace(escaped, '$1');
  729. };
  730. var utils$3 = {};
  731. (function (exports) {
  732. exports.isInteger = num => {
  733. if (typeof num === 'number') {
  734. return Number.isInteger(num);
  735. }
  736. if (typeof num === 'string' && num.trim() !== '') {
  737. return Number.isInteger(Number(num));
  738. }
  739. return false;
  740. };
  741. /**
  742. * Find a node of the given type
  743. */
  744. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  745. /**
  746. * Find a node of the given type
  747. */
  748. exports.exceedsLimit = (min, max, step = 1, limit) => {
  749. if (limit === false) return false;
  750. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  751. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  752. };
  753. /**
  754. * Escape the given node with '\\' before node.value
  755. */
  756. exports.escapeNode = (block, n = 0, type) => {
  757. let node = block.nodes[n];
  758. if (!node) return;
  759. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  760. if (node.escaped !== true) {
  761. node.value = '\\' + node.value;
  762. node.escaped = true;
  763. }
  764. }
  765. };
  766. /**
  767. * Returns true if the given brace node should be enclosed in literal braces
  768. */
  769. exports.encloseBrace = node => {
  770. if (node.type !== 'brace') return false;
  771. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  772. node.invalid = true;
  773. return true;
  774. }
  775. return false;
  776. };
  777. /**
  778. * Returns true if a brace node is invalid.
  779. */
  780. exports.isInvalidBrace = block => {
  781. if (block.type !== 'brace') return false;
  782. if (block.invalid === true || block.dollar) return true;
  783. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  784. block.invalid = true;
  785. return true;
  786. }
  787. if (block.open !== true || block.close !== true) {
  788. block.invalid = true;
  789. return true;
  790. }
  791. return false;
  792. };
  793. /**
  794. * Returns true if a node is an open or close node
  795. */
  796. exports.isOpenOrClose = node => {
  797. if (node.type === 'open' || node.type === 'close') {
  798. return true;
  799. }
  800. return node.open === true || node.close === true;
  801. };
  802. /**
  803. * Reduce an array of text nodes.
  804. */
  805. exports.reduce = nodes => nodes.reduce((acc, node) => {
  806. if (node.type === 'text') acc.push(node.value);
  807. if (node.type === 'range') node.type = 'text';
  808. return acc;
  809. }, []);
  810. /**
  811. * Flatten an array
  812. */
  813. exports.flatten = (...args) => {
  814. const result = [];
  815. const flat = arr => {
  816. for (let i = 0; i < arr.length; i++) {
  817. let ele = arr[i];
  818. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  819. }
  820. return result;
  821. };
  822. flat(args);
  823. return result;
  824. };
  825. } (utils$3));
  826. const utils$2 = utils$3;
  827. var stringify$4 = (ast, options = {}) => {
  828. let stringify = (node, parent = {}) => {
  829. let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);
  830. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  831. let output = '';
  832. if (node.value) {
  833. if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {
  834. return '\\' + node.value;
  835. }
  836. return node.value;
  837. }
  838. if (node.value) {
  839. return node.value;
  840. }
  841. if (node.nodes) {
  842. for (let child of node.nodes) {
  843. output += stringify(child);
  844. }
  845. }
  846. return output;
  847. };
  848. return stringify(ast);
  849. };
  850. /*!
  851. * is-number <https://github.com/jonschlinkert/is-number>
  852. *
  853. * Copyright (c) 2014-present, Jon Schlinkert.
  854. * Released under the MIT License.
  855. */
  856. var isNumber$2 = function(num) {
  857. if (typeof num === 'number') {
  858. return num - num === 0;
  859. }
  860. if (typeof num === 'string' && num.trim() !== '') {
  861. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  862. }
  863. return false;
  864. };
  865. /*!
  866. * to-regex-range <https://github.com/micromatch/to-regex-range>
  867. *
  868. * Copyright (c) 2015-present, Jon Schlinkert.
  869. * Released under the MIT License.
  870. */
  871. const isNumber$1 = isNumber$2;
  872. const toRegexRange$1 = (min, max, options) => {
  873. if (isNumber$1(min) === false) {
  874. throw new TypeError('toRegexRange: expected the first argument to be a number');
  875. }
  876. if (max === void 0 || min === max) {
  877. return String(min);
  878. }
  879. if (isNumber$1(max) === false) {
  880. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  881. }
  882. let opts = { relaxZeros: true, ...options };
  883. if (typeof opts.strictZeros === 'boolean') {
  884. opts.relaxZeros = opts.strictZeros === false;
  885. }
  886. let relax = String(opts.relaxZeros);
  887. let shorthand = String(opts.shorthand);
  888. let capture = String(opts.capture);
  889. let wrap = String(opts.wrap);
  890. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  891. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  892. return toRegexRange$1.cache[cacheKey].result;
  893. }
  894. let a = Math.min(min, max);
  895. let b = Math.max(min, max);
  896. if (Math.abs(a - b) === 1) {
  897. let result = min + '|' + max;
  898. if (opts.capture) {
  899. return `(${result})`;
  900. }
  901. if (opts.wrap === false) {
  902. return result;
  903. }
  904. return `(?:${result})`;
  905. }
  906. let isPadded = hasPadding(min) || hasPadding(max);
  907. let state = { min, max, a, b };
  908. let positives = [];
  909. let negatives = [];
  910. if (isPadded) {
  911. state.isPadded = isPadded;
  912. state.maxLen = String(state.max).length;
  913. }
  914. if (a < 0) {
  915. let newMin = b < 0 ? Math.abs(b) : 1;
  916. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  917. a = state.a = 0;
  918. }
  919. if (b >= 0) {
  920. positives = splitToPatterns(a, b, state, opts);
  921. }
  922. state.negatives = negatives;
  923. state.positives = positives;
  924. state.result = collatePatterns(negatives, positives);
  925. if (opts.capture === true) {
  926. state.result = `(${state.result})`;
  927. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  928. state.result = `(?:${state.result})`;
  929. }
  930. toRegexRange$1.cache[cacheKey] = state;
  931. return state.result;
  932. };
  933. function collatePatterns(neg, pos, options) {
  934. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  935. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  936. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  937. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  938. return subpatterns.join('|');
  939. }
  940. function splitToRanges(min, max) {
  941. let nines = 1;
  942. let zeros = 1;
  943. let stop = countNines(min, nines);
  944. let stops = new Set([max]);
  945. while (min <= stop && stop <= max) {
  946. stops.add(stop);
  947. nines += 1;
  948. stop = countNines(min, nines);
  949. }
  950. stop = countZeros(max + 1, zeros) - 1;
  951. while (min < stop && stop <= max) {
  952. stops.add(stop);
  953. zeros += 1;
  954. stop = countZeros(max + 1, zeros) - 1;
  955. }
  956. stops = [...stops];
  957. stops.sort(compare);
  958. return stops;
  959. }
  960. /**
  961. * Convert a range to a regex pattern
  962. * @param {Number} `start`
  963. * @param {Number} `stop`
  964. * @return {String}
  965. */
  966. function rangeToPattern(start, stop, options) {
  967. if (start === stop) {
  968. return { pattern: start, count: [], digits: 0 };
  969. }
  970. let zipped = zip(start, stop);
  971. let digits = zipped.length;
  972. let pattern = '';
  973. let count = 0;
  974. for (let i = 0; i < digits; i++) {
  975. let [startDigit, stopDigit] = zipped[i];
  976. if (startDigit === stopDigit) {
  977. pattern += startDigit;
  978. } else if (startDigit !== '0' || stopDigit !== '9') {
  979. pattern += toCharacterClass(startDigit, stopDigit);
  980. } else {
  981. count++;
  982. }
  983. }
  984. if (count) {
  985. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  986. }
  987. return { pattern, count: [count], digits };
  988. }
  989. function splitToPatterns(min, max, tok, options) {
  990. let ranges = splitToRanges(min, max);
  991. let tokens = [];
  992. let start = min;
  993. let prev;
  994. for (let i = 0; i < ranges.length; i++) {
  995. let max = ranges[i];
  996. let obj = rangeToPattern(String(start), String(max), options);
  997. let zeros = '';
  998. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  999. if (prev.count.length > 1) {
  1000. prev.count.pop();
  1001. }
  1002. prev.count.push(obj.count[0]);
  1003. prev.string = prev.pattern + toQuantifier(prev.count);
  1004. start = max + 1;
  1005. continue;
  1006. }
  1007. if (tok.isPadded) {
  1008. zeros = padZeros(max, tok, options);
  1009. }
  1010. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  1011. tokens.push(obj);
  1012. start = max + 1;
  1013. prev = obj;
  1014. }
  1015. return tokens;
  1016. }
  1017. function filterPatterns(arr, comparison, prefix, intersection, options) {
  1018. let result = [];
  1019. for (let ele of arr) {
  1020. let { string } = ele;
  1021. // only push if _both_ are negative...
  1022. if (!intersection && !contains(comparison, 'string', string)) {
  1023. result.push(prefix + string);
  1024. }
  1025. // or _both_ are positive
  1026. if (intersection && contains(comparison, 'string', string)) {
  1027. result.push(prefix + string);
  1028. }
  1029. }
  1030. return result;
  1031. }
  1032. /**
  1033. * Zip strings
  1034. */
  1035. function zip(a, b) {
  1036. let arr = [];
  1037. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  1038. return arr;
  1039. }
  1040. function compare(a, b) {
  1041. return a > b ? 1 : b > a ? -1 : 0;
  1042. }
  1043. function contains(arr, key, val) {
  1044. return arr.some(ele => ele[key] === val);
  1045. }
  1046. function countNines(min, len) {
  1047. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  1048. }
  1049. function countZeros(integer, zeros) {
  1050. return integer - (integer % Math.pow(10, zeros));
  1051. }
  1052. function toQuantifier(digits) {
  1053. let [start = 0, stop = ''] = digits;
  1054. if (stop || start > 1) {
  1055. return `{${start + (stop ? ',' + stop : '')}}`;
  1056. }
  1057. return '';
  1058. }
  1059. function toCharacterClass(a, b, options) {
  1060. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  1061. }
  1062. function hasPadding(str) {
  1063. return /^-?(0+)\d/.test(str);
  1064. }
  1065. function padZeros(value, tok, options) {
  1066. if (!tok.isPadded) {
  1067. return value;
  1068. }
  1069. let diff = Math.abs(tok.maxLen - String(value).length);
  1070. let relax = options.relaxZeros !== false;
  1071. switch (diff) {
  1072. case 0:
  1073. return '';
  1074. case 1:
  1075. return relax ? '0?' : '0';
  1076. case 2:
  1077. return relax ? '0{0,2}' : '00';
  1078. default: {
  1079. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  1080. }
  1081. }
  1082. }
  1083. /**
  1084. * Cache
  1085. */
  1086. toRegexRange$1.cache = {};
  1087. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  1088. /**
  1089. * Expose `toRegexRange`
  1090. */
  1091. var toRegexRange_1 = toRegexRange$1;
  1092. /*!
  1093. * fill-range <https://github.com/jonschlinkert/fill-range>
  1094. *
  1095. * Copyright (c) 2014-present, Jon Schlinkert.
  1096. * Licensed under the MIT License.
  1097. */
  1098. const util = require$$2;
  1099. const toRegexRange = toRegexRange_1;
  1100. const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1101. const transform = toNumber => {
  1102. return value => toNumber === true ? Number(value) : String(value);
  1103. };
  1104. const isValidValue = value => {
  1105. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  1106. };
  1107. const isNumber = num => Number.isInteger(+num);
  1108. const zeros = input => {
  1109. let value = `${input}`;
  1110. let index = -1;
  1111. if (value[0] === '-') value = value.slice(1);
  1112. if (value === '0') return false;
  1113. while (value[++index] === '0');
  1114. return index > 0;
  1115. };
  1116. const stringify$3 = (start, end, options) => {
  1117. if (typeof start === 'string' || typeof end === 'string') {
  1118. return true;
  1119. }
  1120. return options.stringify === true;
  1121. };
  1122. const pad = (input, maxLength, toNumber) => {
  1123. if (maxLength > 0) {
  1124. let dash = input[0] === '-' ? '-' : '';
  1125. if (dash) input = input.slice(1);
  1126. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  1127. }
  1128. if (toNumber === false) {
  1129. return String(input);
  1130. }
  1131. return input;
  1132. };
  1133. const toMaxLen = (input, maxLength) => {
  1134. let negative = input[0] === '-' ? '-' : '';
  1135. if (negative) {
  1136. input = input.slice(1);
  1137. maxLength--;
  1138. }
  1139. while (input.length < maxLength) input = '0' + input;
  1140. return negative ? ('-' + input) : input;
  1141. };
  1142. const toSequence = (parts, options) => {
  1143. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  1144. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  1145. let prefix = options.capture ? '' : '?:';
  1146. let positives = '';
  1147. let negatives = '';
  1148. let result;
  1149. if (parts.positives.length) {
  1150. positives = parts.positives.join('|');
  1151. }
  1152. if (parts.negatives.length) {
  1153. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  1154. }
  1155. if (positives && negatives) {
  1156. result = `${positives}|${negatives}`;
  1157. } else {
  1158. result = positives || negatives;
  1159. }
  1160. if (options.wrap) {
  1161. return `(${prefix}${result})`;
  1162. }
  1163. return result;
  1164. };
  1165. const toRange = (a, b, isNumbers, options) => {
  1166. if (isNumbers) {
  1167. return toRegexRange(a, b, { wrap: false, ...options });
  1168. }
  1169. let start = String.fromCharCode(a);
  1170. if (a === b) return start;
  1171. let stop = String.fromCharCode(b);
  1172. return `[${start}-${stop}]`;
  1173. };
  1174. const toRegex = (start, end, options) => {
  1175. if (Array.isArray(start)) {
  1176. let wrap = options.wrap === true;
  1177. let prefix = options.capture ? '' : '?:';
  1178. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  1179. }
  1180. return toRegexRange(start, end, options);
  1181. };
  1182. const rangeError = (...args) => {
  1183. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  1184. };
  1185. const invalidRange = (start, end, options) => {
  1186. if (options.strictRanges === true) throw rangeError([start, end]);
  1187. return [];
  1188. };
  1189. const invalidStep = (step, options) => {
  1190. if (options.strictRanges === true) {
  1191. throw new TypeError(`Expected step "${step}" to be a number`);
  1192. }
  1193. return [];
  1194. };
  1195. const fillNumbers = (start, end, step = 1, options = {}) => {
  1196. let a = Number(start);
  1197. let b = Number(end);
  1198. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  1199. if (options.strictRanges === true) throw rangeError([start, end]);
  1200. return [];
  1201. }
  1202. // fix negative zero
  1203. if (a === 0) a = 0;
  1204. if (b === 0) b = 0;
  1205. let descending = a > b;
  1206. let startString = String(start);
  1207. let endString = String(end);
  1208. let stepString = String(step);
  1209. step = Math.max(Math.abs(step), 1);
  1210. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  1211. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  1212. let toNumber = padded === false && stringify$3(start, end, options) === false;
  1213. let format = options.transform || transform(toNumber);
  1214. if (options.toRegex && step === 1) {
  1215. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  1216. }
  1217. let parts = { negatives: [], positives: [] };
  1218. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  1219. let range = [];
  1220. let index = 0;
  1221. while (descending ? a >= b : a <= b) {
  1222. if (options.toRegex === true && step > 1) {
  1223. push(a);
  1224. } else {
  1225. range.push(pad(format(a, index), maxLen, toNumber));
  1226. }
  1227. a = descending ? a - step : a + step;
  1228. index++;
  1229. }
  1230. if (options.toRegex === true) {
  1231. return step > 1
  1232. ? toSequence(parts, options)
  1233. : toRegex(range, null, { wrap: false, ...options });
  1234. }
  1235. return range;
  1236. };
  1237. const fillLetters = (start, end, step = 1, options = {}) => {
  1238. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  1239. return invalidRange(start, end, options);
  1240. }
  1241. let format = options.transform || (val => String.fromCharCode(val));
  1242. let a = `${start}`.charCodeAt(0);
  1243. let b = `${end}`.charCodeAt(0);
  1244. let descending = a > b;
  1245. let min = Math.min(a, b);
  1246. let max = Math.max(a, b);
  1247. if (options.toRegex && step === 1) {
  1248. return toRange(min, max, false, options);
  1249. }
  1250. let range = [];
  1251. let index = 0;
  1252. while (descending ? a >= b : a <= b) {
  1253. range.push(format(a, index));
  1254. a = descending ? a - step : a + step;
  1255. index++;
  1256. }
  1257. if (options.toRegex === true) {
  1258. return toRegex(range, null, { wrap: false, options });
  1259. }
  1260. return range;
  1261. };
  1262. const fill$2 = (start, end, step, options = {}) => {
  1263. if (end == null && isValidValue(start)) {
  1264. return [start];
  1265. }
  1266. if (!isValidValue(start) || !isValidValue(end)) {
  1267. return invalidRange(start, end, options);
  1268. }
  1269. if (typeof step === 'function') {
  1270. return fill$2(start, end, 1, { transform: step });
  1271. }
  1272. if (isObject(step)) {
  1273. return fill$2(start, end, 0, step);
  1274. }
  1275. let opts = { ...options };
  1276. if (opts.capture === true) opts.wrap = true;
  1277. step = step || opts.step || 1;
  1278. if (!isNumber(step)) {
  1279. if (step != null && !isObject(step)) return invalidStep(step, opts);
  1280. return fill$2(start, end, 1, step);
  1281. }
  1282. if (isNumber(start) && isNumber(end)) {
  1283. return fillNumbers(start, end, step, opts);
  1284. }
  1285. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  1286. };
  1287. var fillRange = fill$2;
  1288. const fill$1 = fillRange;
  1289. const utils$1 = utils$3;
  1290. const compile$1 = (ast, options = {}) => {
  1291. let walk = (node, parent = {}) => {
  1292. let invalidBlock = utils$1.isInvalidBrace(parent);
  1293. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  1294. let invalid = invalidBlock === true || invalidNode === true;
  1295. let prefix = options.escapeInvalid === true ? '\\' : '';
  1296. let output = '';
  1297. if (node.isOpen === true) {
  1298. return prefix + node.value;
  1299. }
  1300. if (node.isClose === true) {
  1301. return prefix + node.value;
  1302. }
  1303. if (node.type === 'open') {
  1304. return invalid ? (prefix + node.value) : '(';
  1305. }
  1306. if (node.type === 'close') {
  1307. return invalid ? (prefix + node.value) : ')';
  1308. }
  1309. if (node.type === 'comma') {
  1310. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  1311. }
  1312. if (node.value) {
  1313. return node.value;
  1314. }
  1315. if (node.nodes && node.ranges > 0) {
  1316. let args = utils$1.reduce(node.nodes);
  1317. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  1318. if (range.length !== 0) {
  1319. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  1320. }
  1321. }
  1322. if (node.nodes) {
  1323. for (let child of node.nodes) {
  1324. output += walk(child, node);
  1325. }
  1326. }
  1327. return output;
  1328. };
  1329. return walk(ast);
  1330. };
  1331. var compile_1 = compile$1;
  1332. const fill = fillRange;
  1333. const stringify$2 = stringify$4;
  1334. const utils = utils$3;
  1335. const append = (queue = '', stash = '', enclose = false) => {
  1336. let result = [];
  1337. queue = [].concat(queue);
  1338. stash = [].concat(stash);
  1339. if (!stash.length) return queue;
  1340. if (!queue.length) {
  1341. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  1342. }
  1343. for (let item of queue) {
  1344. if (Array.isArray(item)) {
  1345. for (let value of item) {
  1346. result.push(append(value, stash, enclose));
  1347. }
  1348. } else {
  1349. for (let ele of stash) {
  1350. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  1351. result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
  1352. }
  1353. }
  1354. }
  1355. return utils.flatten(result);
  1356. };
  1357. const expand$1 = (ast, options = {}) => {
  1358. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  1359. let walk = (node, parent = {}) => {
  1360. node.queue = [];
  1361. let p = parent;
  1362. let q = parent.queue;
  1363. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  1364. p = p.parent;
  1365. q = p.queue;
  1366. }
  1367. if (node.invalid || node.dollar) {
  1368. q.push(append(q.pop(), stringify$2(node, options)));
  1369. return;
  1370. }
  1371. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  1372. q.push(append(q.pop(), ['{}']));
  1373. return;
  1374. }
  1375. if (node.nodes && node.ranges > 0) {
  1376. let args = utils.reduce(node.nodes);
  1377. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  1378. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  1379. }
  1380. let range = fill(...args, options);
  1381. if (range.length === 0) {
  1382. range = stringify$2(node, options);
  1383. }
  1384. q.push(append(q.pop(), range));
  1385. node.nodes = [];
  1386. return;
  1387. }
  1388. let enclose = utils.encloseBrace(node);
  1389. let queue = node.queue;
  1390. let block = node;
  1391. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  1392. block = block.parent;
  1393. queue = block.queue;
  1394. }
  1395. for (let i = 0; i < node.nodes.length; i++) {
  1396. let child = node.nodes[i];
  1397. if (child.type === 'comma' && node.type === 'brace') {
  1398. if (i === 1) queue.push('');
  1399. queue.push('');
  1400. continue;
  1401. }
  1402. if (child.type === 'close') {
  1403. q.push(append(q.pop(), queue, enclose));
  1404. continue;
  1405. }
  1406. if (child.value && child.type !== 'open') {
  1407. queue.push(append(queue.pop(), child.value));
  1408. continue;
  1409. }
  1410. if (child.nodes) {
  1411. walk(child, node);
  1412. }
  1413. }
  1414. return queue;
  1415. };
  1416. return utils.flatten(walk(ast));
  1417. };
  1418. var expand_1 = expand$1;
  1419. var constants$1 = {
  1420. MAX_LENGTH: 1024 * 64,
  1421. // Digits
  1422. CHAR_0: '0', /* 0 */
  1423. CHAR_9: '9', /* 9 */
  1424. // Alphabet chars.
  1425. CHAR_UPPERCASE_A: 'A', /* A */
  1426. CHAR_LOWERCASE_A: 'a', /* a */
  1427. CHAR_UPPERCASE_Z: 'Z', /* Z */
  1428. CHAR_LOWERCASE_Z: 'z', /* z */
  1429. CHAR_LEFT_PARENTHESES: '(', /* ( */
  1430. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  1431. CHAR_ASTERISK: '*', /* * */
  1432. // Non-alphabetic chars.
  1433. CHAR_AMPERSAND: '&', /* & */
  1434. CHAR_AT: '@', /* @ */
  1435. CHAR_BACKSLASH: '\\', /* \ */
  1436. CHAR_BACKTICK: '`', /* ` */
  1437. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  1438. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  1439. CHAR_COLON: ':', /* : */
  1440. CHAR_COMMA: ',', /* , */
  1441. CHAR_DOLLAR: '$', /* . */
  1442. CHAR_DOT: '.', /* . */
  1443. CHAR_DOUBLE_QUOTE: '"', /* " */
  1444. CHAR_EQUAL: '=', /* = */
  1445. CHAR_EXCLAMATION_MARK: '!', /* ! */
  1446. CHAR_FORM_FEED: '\f', /* \f */
  1447. CHAR_FORWARD_SLASH: '/', /* / */
  1448. CHAR_HASH: '#', /* # */
  1449. CHAR_HYPHEN_MINUS: '-', /* - */
  1450. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  1451. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  1452. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  1453. CHAR_LINE_FEED: '\n', /* \n */
  1454. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  1455. CHAR_PERCENT: '%', /* % */
  1456. CHAR_PLUS: '+', /* + */
  1457. CHAR_QUESTION_MARK: '?', /* ? */
  1458. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  1459. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  1460. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  1461. CHAR_SEMICOLON: ';', /* ; */
  1462. CHAR_SINGLE_QUOTE: '\'', /* ' */
  1463. CHAR_SPACE: ' ', /* */
  1464. CHAR_TAB: '\t', /* \t */
  1465. CHAR_UNDERSCORE: '_', /* _ */
  1466. CHAR_VERTICAL_LINE: '|', /* | */
  1467. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  1468. };
  1469. const stringify$1 = stringify$4;
  1470. /**
  1471. * Constants
  1472. */
  1473. const {
  1474. MAX_LENGTH,
  1475. CHAR_BACKSLASH, /* \ */
  1476. CHAR_BACKTICK, /* ` */
  1477. CHAR_COMMA, /* , */
  1478. CHAR_DOT, /* . */
  1479. CHAR_LEFT_PARENTHESES, /* ( */
  1480. CHAR_RIGHT_PARENTHESES, /* ) */
  1481. CHAR_LEFT_CURLY_BRACE, /* { */
  1482. CHAR_RIGHT_CURLY_BRACE, /* } */
  1483. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1484. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  1485. CHAR_DOUBLE_QUOTE, /* " */
  1486. CHAR_SINGLE_QUOTE, /* ' */
  1487. CHAR_NO_BREAK_SPACE,
  1488. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  1489. } = constants$1;
  1490. /**
  1491. * parse
  1492. */
  1493. const parse$1 = (input, options = {}) => {
  1494. if (typeof input !== 'string') {
  1495. throw new TypeError('Expected a string');
  1496. }
  1497. let opts = options || {};
  1498. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1499. if (input.length > max) {
  1500. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  1501. }
  1502. let ast = { type: 'root', input, nodes: [] };
  1503. let stack = [ast];
  1504. let block = ast;
  1505. let prev = ast;
  1506. let brackets = 0;
  1507. let length = input.length;
  1508. let index = 0;
  1509. let depth = 0;
  1510. let value;
  1511. /**
  1512. * Helpers
  1513. */
  1514. const advance = () => input[index++];
  1515. const push = node => {
  1516. if (node.type === 'text' && prev.type === 'dot') {
  1517. prev.type = 'text';
  1518. }
  1519. if (prev && prev.type === 'text' && node.type === 'text') {
  1520. prev.value += node.value;
  1521. return;
  1522. }
  1523. block.nodes.push(node);
  1524. node.parent = block;
  1525. node.prev = prev;
  1526. prev = node;
  1527. return node;
  1528. };
  1529. push({ type: 'bos' });
  1530. while (index < length) {
  1531. block = stack[stack.length - 1];
  1532. value = advance();
  1533. /**
  1534. * Invalid chars
  1535. */
  1536. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  1537. continue;
  1538. }
  1539. /**
  1540. * Escaped chars
  1541. */
  1542. if (value === CHAR_BACKSLASH) {
  1543. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  1544. continue;
  1545. }
  1546. /**
  1547. * Right square bracket (literal): ']'
  1548. */
  1549. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  1550. push({ type: 'text', value: '\\' + value });
  1551. continue;
  1552. }
  1553. /**
  1554. * Left square bracket: '['
  1555. */
  1556. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  1557. brackets++;
  1558. let next;
  1559. while (index < length && (next = advance())) {
  1560. value += next;
  1561. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  1562. brackets++;
  1563. continue;
  1564. }
  1565. if (next === CHAR_BACKSLASH) {
  1566. value += advance();
  1567. continue;
  1568. }
  1569. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1570. brackets--;
  1571. if (brackets === 0) {
  1572. break;
  1573. }
  1574. }
  1575. }
  1576. push({ type: 'text', value });
  1577. continue;
  1578. }
  1579. /**
  1580. * Parentheses
  1581. */
  1582. if (value === CHAR_LEFT_PARENTHESES) {
  1583. block = push({ type: 'paren', nodes: [] });
  1584. stack.push(block);
  1585. push({ type: 'text', value });
  1586. continue;
  1587. }
  1588. if (value === CHAR_RIGHT_PARENTHESES) {
  1589. if (block.type !== 'paren') {
  1590. push({ type: 'text', value });
  1591. continue;
  1592. }
  1593. block = stack.pop();
  1594. push({ type: 'text', value });
  1595. block = stack[stack.length - 1];
  1596. continue;
  1597. }
  1598. /**
  1599. * Quotes: '|"|`
  1600. */
  1601. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  1602. let open = value;
  1603. let next;
  1604. if (options.keepQuotes !== true) {
  1605. value = '';
  1606. }
  1607. while (index < length && (next = advance())) {
  1608. if (next === CHAR_BACKSLASH) {
  1609. value += next + advance();
  1610. continue;
  1611. }
  1612. if (next === open) {
  1613. if (options.keepQuotes === true) value += next;
  1614. break;
  1615. }
  1616. value += next;
  1617. }
  1618. push({ type: 'text', value });
  1619. continue;
  1620. }
  1621. /**
  1622. * Left curly brace: '{'
  1623. */
  1624. if (value === CHAR_LEFT_CURLY_BRACE) {
  1625. depth++;
  1626. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  1627. let brace = {
  1628. type: 'brace',
  1629. open: true,
  1630. close: false,
  1631. dollar,
  1632. depth,
  1633. commas: 0,
  1634. ranges: 0,
  1635. nodes: []
  1636. };
  1637. block = push(brace);
  1638. stack.push(block);
  1639. push({ type: 'open', value });
  1640. continue;
  1641. }
  1642. /**
  1643. * Right curly brace: '}'
  1644. */
  1645. if (value === CHAR_RIGHT_CURLY_BRACE) {
  1646. if (block.type !== 'brace') {
  1647. push({ type: 'text', value });
  1648. continue;
  1649. }
  1650. let type = 'close';
  1651. block = stack.pop();
  1652. block.close = true;
  1653. push({ type, value });
  1654. depth--;
  1655. block = stack[stack.length - 1];
  1656. continue;
  1657. }
  1658. /**
  1659. * Comma: ','
  1660. */
  1661. if (value === CHAR_COMMA && depth > 0) {
  1662. if (block.ranges > 0) {
  1663. block.ranges = 0;
  1664. let open = block.nodes.shift();
  1665. block.nodes = [open, { type: 'text', value: stringify$1(block) }];
  1666. }
  1667. push({ type: 'comma', value });
  1668. block.commas++;
  1669. continue;
  1670. }
  1671. /**
  1672. * Dot: '.'
  1673. */
  1674. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  1675. let siblings = block.nodes;
  1676. if (depth === 0 || siblings.length === 0) {
  1677. push({ type: 'text', value });
  1678. continue;
  1679. }
  1680. if (prev.type === 'dot') {
  1681. block.range = [];
  1682. prev.value += value;
  1683. prev.type = 'range';
  1684. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  1685. block.invalid = true;
  1686. block.ranges = 0;
  1687. prev.type = 'text';
  1688. continue;
  1689. }
  1690. block.ranges++;
  1691. block.args = [];
  1692. continue;
  1693. }
  1694. if (prev.type === 'range') {
  1695. siblings.pop();
  1696. let before = siblings[siblings.length - 1];
  1697. before.value += prev.value + value;
  1698. prev = before;
  1699. block.ranges--;
  1700. continue;
  1701. }
  1702. push({ type: 'dot', value });
  1703. continue;
  1704. }
  1705. /**
  1706. * Text
  1707. */
  1708. push({ type: 'text', value });
  1709. }
  1710. // Mark imbalanced braces and brackets as invalid
  1711. do {
  1712. block = stack.pop();
  1713. if (block.type !== 'root') {
  1714. block.nodes.forEach(node => {
  1715. if (!node.nodes) {
  1716. if (node.type === 'open') node.isOpen = true;
  1717. if (node.type === 'close') node.isClose = true;
  1718. if (!node.nodes) node.type = 'text';
  1719. node.invalid = true;
  1720. }
  1721. });
  1722. // get the location of the block on parent.nodes (block's siblings)
  1723. let parent = stack[stack.length - 1];
  1724. let index = parent.nodes.indexOf(block);
  1725. // replace the (invalid) block with it's nodes
  1726. parent.nodes.splice(index, 1, ...block.nodes);
  1727. }
  1728. } while (stack.length > 0);
  1729. push({ type: 'eos' });
  1730. return ast;
  1731. };
  1732. var parse_1 = parse$1;
  1733. const stringify = stringify$4;
  1734. const compile = compile_1;
  1735. const expand = expand_1;
  1736. const parse = parse_1;
  1737. /**
  1738. * Expand the given pattern or create a regex-compatible string.
  1739. *
  1740. * ```js
  1741. * const braces = require('braces');
  1742. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  1743. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  1744. * ```
  1745. * @param {String} `str`
  1746. * @param {Object} `options`
  1747. * @return {String}
  1748. * @api public
  1749. */
  1750. const braces$1 = (input, options = {}) => {
  1751. let output = [];
  1752. if (Array.isArray(input)) {
  1753. for (let pattern of input) {
  1754. let result = braces$1.create(pattern, options);
  1755. if (Array.isArray(result)) {
  1756. output.push(...result);
  1757. } else {
  1758. output.push(result);
  1759. }
  1760. }
  1761. } else {
  1762. output = [].concat(braces$1.create(input, options));
  1763. }
  1764. if (options && options.expand === true && options.nodupes === true) {
  1765. output = [...new Set(output)];
  1766. }
  1767. return output;
  1768. };
  1769. /**
  1770. * Parse the given `str` with the given `options`.
  1771. *
  1772. * ```js
  1773. * // braces.parse(pattern, [, options]);
  1774. * const ast = braces.parse('a/{b,c}/d');
  1775. * console.log(ast);
  1776. * ```
  1777. * @param {String} pattern Brace pattern to parse
  1778. * @param {Object} options
  1779. * @return {Object} Returns an AST
  1780. * @api public
  1781. */
  1782. braces$1.parse = (input, options = {}) => parse(input, options);
  1783. /**
  1784. * Creates a braces string from an AST, or an AST node.
  1785. *
  1786. * ```js
  1787. * const braces = require('braces');
  1788. * let ast = braces.parse('foo/{a,b}/bar');
  1789. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  1790. * ```
  1791. * @param {String} `input` Brace pattern or AST.
  1792. * @param {Object} `options`
  1793. * @return {Array} Returns an array of expanded values.
  1794. * @api public
  1795. */
  1796. braces$1.stringify = (input, options = {}) => {
  1797. if (typeof input === 'string') {
  1798. return stringify(braces$1.parse(input, options), options);
  1799. }
  1800. return stringify(input, options);
  1801. };
  1802. /**
  1803. * Compiles a brace pattern into a regex-compatible, optimized string.
  1804. * This method is called by the main [braces](#braces) function by default.
  1805. *
  1806. * ```js
  1807. * const braces = require('braces');
  1808. * console.log(braces.compile('a/{b,c}/d'));
  1809. * //=> ['a/(b|c)/d']
  1810. * ```
  1811. * @param {String} `input` Brace pattern or AST.
  1812. * @param {Object} `options`
  1813. * @return {Array} Returns an array of expanded values.
  1814. * @api public
  1815. */
  1816. braces$1.compile = (input, options = {}) => {
  1817. if (typeof input === 'string') {
  1818. input = braces$1.parse(input, options);
  1819. }
  1820. return compile(input, options);
  1821. };
  1822. /**
  1823. * Expands a brace pattern into an array. This method is called by the
  1824. * main [braces](#braces) function when `options.expand` is true. Before
  1825. * using this method it's recommended that you read the [performance notes](#performance))
  1826. * and advantages of using [.compile](#compile) instead.
  1827. *
  1828. * ```js
  1829. * const braces = require('braces');
  1830. * console.log(braces.expand('a/{b,c}/d'));
  1831. * //=> ['a/b/d', 'a/c/d'];
  1832. * ```
  1833. * @param {String} `pattern` Brace pattern
  1834. * @param {Object} `options`
  1835. * @return {Array} Returns an array of expanded values.
  1836. * @api public
  1837. */
  1838. braces$1.expand = (input, options = {}) => {
  1839. if (typeof input === 'string') {
  1840. input = braces$1.parse(input, options);
  1841. }
  1842. let result = expand(input, options);
  1843. // filter out empty strings if specified
  1844. if (options.noempty === true) {
  1845. result = result.filter(Boolean);
  1846. }
  1847. // filter out duplicates if specified
  1848. if (options.nodupes === true) {
  1849. result = [...new Set(result)];
  1850. }
  1851. return result;
  1852. };
  1853. /**
  1854. * Processes a brace pattern and returns either an expanded array
  1855. * (if `options.expand` is true), a highly optimized regex-compatible string.
  1856. * This method is called by the main [braces](#braces) function.
  1857. *
  1858. * ```js
  1859. * const braces = require('braces');
  1860. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  1861. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  1862. * ```
  1863. * @param {String} `pattern` Brace pattern
  1864. * @param {Object} `options`
  1865. * @return {Array} Returns an array of expanded values.
  1866. * @api public
  1867. */
  1868. braces$1.create = (input, options = {}) => {
  1869. if (input === '' || input.length < 3) {
  1870. return [input];
  1871. }
  1872. return options.expand !== true
  1873. ? braces$1.compile(input, options)
  1874. : braces$1.expand(input, options);
  1875. };
  1876. /**
  1877. * Expose "braces"
  1878. */
  1879. var braces_1 = braces$1;
  1880. var binaryExtensions$1 = {exports: {}};
  1881. const require$$0 = [
  1882. "3dm",
  1883. "3ds",
  1884. "3g2",
  1885. "3gp",
  1886. "7z",
  1887. "a",
  1888. "aac",
  1889. "adp",
  1890. "ai",
  1891. "aif",
  1892. "aiff",
  1893. "alz",
  1894. "ape",
  1895. "apk",
  1896. "appimage",
  1897. "ar",
  1898. "arj",
  1899. "asf",
  1900. "au",
  1901. "avi",
  1902. "bak",
  1903. "baml",
  1904. "bh",
  1905. "bin",
  1906. "bk",
  1907. "bmp",
  1908. "btif",
  1909. "bz2",
  1910. "bzip2",
  1911. "cab",
  1912. "caf",
  1913. "cgm",
  1914. "class",
  1915. "cmx",
  1916. "cpio",
  1917. "cr2",
  1918. "cur",
  1919. "dat",
  1920. "dcm",
  1921. "deb",
  1922. "dex",
  1923. "djvu",
  1924. "dll",
  1925. "dmg",
  1926. "dng",
  1927. "doc",
  1928. "docm",
  1929. "docx",
  1930. "dot",
  1931. "dotm",
  1932. "dra",
  1933. "DS_Store",
  1934. "dsk",
  1935. "dts",
  1936. "dtshd",
  1937. "dvb",
  1938. "dwg",
  1939. "dxf",
  1940. "ecelp4800",
  1941. "ecelp7470",
  1942. "ecelp9600",
  1943. "egg",
  1944. "eol",
  1945. "eot",
  1946. "epub",
  1947. "exe",
  1948. "f4v",
  1949. "fbs",
  1950. "fh",
  1951. "fla",
  1952. "flac",
  1953. "flatpak",
  1954. "fli",
  1955. "flv",
  1956. "fpx",
  1957. "fst",
  1958. "fvt",
  1959. "g3",
  1960. "gh",
  1961. "gif",
  1962. "graffle",
  1963. "gz",
  1964. "gzip",
  1965. "h261",
  1966. "h263",
  1967. "h264",
  1968. "icns",
  1969. "ico",
  1970. "ief",
  1971. "img",
  1972. "ipa",
  1973. "iso",
  1974. "jar",
  1975. "jpeg",
  1976. "jpg",
  1977. "jpgv",
  1978. "jpm",
  1979. "jxr",
  1980. "key",
  1981. "ktx",
  1982. "lha",
  1983. "lib",
  1984. "lvp",
  1985. "lz",
  1986. "lzh",
  1987. "lzma",
  1988. "lzo",
  1989. "m3u",
  1990. "m4a",
  1991. "m4v",
  1992. "mar",
  1993. "mdi",
  1994. "mht",
  1995. "mid",
  1996. "midi",
  1997. "mj2",
  1998. "mka",
  1999. "mkv",
  2000. "mmr",
  2001. "mng",
  2002. "mobi",
  2003. "mov",
  2004. "movie",
  2005. "mp3",
  2006. "mp4",
  2007. "mp4a",
  2008. "mpeg",
  2009. "mpg",
  2010. "mpga",
  2011. "mxu",
  2012. "nef",
  2013. "npx",
  2014. "numbers",
  2015. "nupkg",
  2016. "o",
  2017. "odp",
  2018. "ods",
  2019. "odt",
  2020. "oga",
  2021. "ogg",
  2022. "ogv",
  2023. "otf",
  2024. "ott",
  2025. "pages",
  2026. "pbm",
  2027. "pcx",
  2028. "pdb",
  2029. "pdf",
  2030. "pea",
  2031. "pgm",
  2032. "pic",
  2033. "png",
  2034. "pnm",
  2035. "pot",
  2036. "potm",
  2037. "potx",
  2038. "ppa",
  2039. "ppam",
  2040. "ppm",
  2041. "pps",
  2042. "ppsm",
  2043. "ppsx",
  2044. "ppt",
  2045. "pptm",
  2046. "pptx",
  2047. "psd",
  2048. "pya",
  2049. "pyc",
  2050. "pyo",
  2051. "pyv",
  2052. "qt",
  2053. "rar",
  2054. "ras",
  2055. "raw",
  2056. "resources",
  2057. "rgb",
  2058. "rip",
  2059. "rlc",
  2060. "rmf",
  2061. "rmvb",
  2062. "rpm",
  2063. "rtf",
  2064. "rz",
  2065. "s3m",
  2066. "s7z",
  2067. "scpt",
  2068. "sgi",
  2069. "shar",
  2070. "snap",
  2071. "sil",
  2072. "sketch",
  2073. "slk",
  2074. "smv",
  2075. "snk",
  2076. "so",
  2077. "stl",
  2078. "suo",
  2079. "sub",
  2080. "swf",
  2081. "tar",
  2082. "tbz",
  2083. "tbz2",
  2084. "tga",
  2085. "tgz",
  2086. "thmx",
  2087. "tif",
  2088. "tiff",
  2089. "tlz",
  2090. "ttc",
  2091. "ttf",
  2092. "txz",
  2093. "udf",
  2094. "uvh",
  2095. "uvi",
  2096. "uvm",
  2097. "uvp",
  2098. "uvs",
  2099. "uvu",
  2100. "viv",
  2101. "vob",
  2102. "war",
  2103. "wav",
  2104. "wax",
  2105. "wbmp",
  2106. "wdp",
  2107. "weba",
  2108. "webm",
  2109. "webp",
  2110. "whl",
  2111. "wim",
  2112. "wm",
  2113. "wma",
  2114. "wmv",
  2115. "wmx",
  2116. "woff",
  2117. "woff2",
  2118. "wrm",
  2119. "wvx",
  2120. "xbm",
  2121. "xif",
  2122. "xla",
  2123. "xlam",
  2124. "xls",
  2125. "xlsb",
  2126. "xlsm",
  2127. "xlsx",
  2128. "xlt",
  2129. "xltm",
  2130. "xltx",
  2131. "xm",
  2132. "xmind",
  2133. "xpi",
  2134. "xpm",
  2135. "xwd",
  2136. "xz",
  2137. "z",
  2138. "zip",
  2139. "zipx"
  2140. ];
  2141. (function (module) {
  2142. module.exports = require$$0;
  2143. } (binaryExtensions$1));
  2144. const path = require$$0$2;
  2145. const binaryExtensions = binaryExtensions$1.exports;
  2146. const extensions = new Set(binaryExtensions);
  2147. var isBinaryPath$1 = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());
  2148. var constants = {};
  2149. (function (exports) {
  2150. const {sep} = require$$0$2;
  2151. const {platform} = process;
  2152. const os = require$$2$1;
  2153. exports.EV_ALL = 'all';
  2154. exports.EV_READY = 'ready';
  2155. exports.EV_ADD = 'add';
  2156. exports.EV_CHANGE = 'change';
  2157. exports.EV_ADD_DIR = 'addDir';
  2158. exports.EV_UNLINK = 'unlink';
  2159. exports.EV_UNLINK_DIR = 'unlinkDir';
  2160. exports.EV_RAW = 'raw';
  2161. exports.EV_ERROR = 'error';
  2162. exports.STR_DATA = 'data';
  2163. exports.STR_END = 'end';
  2164. exports.STR_CLOSE = 'close';
  2165. exports.FSEVENT_CREATED = 'created';
  2166. exports.FSEVENT_MODIFIED = 'modified';
  2167. exports.FSEVENT_DELETED = 'deleted';
  2168. exports.FSEVENT_MOVED = 'moved';
  2169. exports.FSEVENT_CLONED = 'cloned';
  2170. exports.FSEVENT_UNKNOWN = 'unknown';
  2171. exports.FSEVENT_TYPE_FILE = 'file';
  2172. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  2173. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  2174. exports.KEY_LISTENERS = 'listeners';
  2175. exports.KEY_ERR = 'errHandlers';
  2176. exports.KEY_RAW = 'rawEmitters';
  2177. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  2178. exports.DOT_SLASH = `.${sep}`;
  2179. exports.BACK_SLASH_RE = /\\/g;
  2180. exports.DOUBLE_SLASH_RE = /\/\//;
  2181. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  2182. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  2183. exports.REPLACER_RE = /^\.[/\\]/;
  2184. exports.SLASH = '/';
  2185. exports.SLASH_SLASH = '//';
  2186. exports.BRACE_START = '{';
  2187. exports.BANG = '!';
  2188. exports.ONE_DOT = '.';
  2189. exports.TWO_DOTS = '..';
  2190. exports.STAR = '*';
  2191. exports.GLOBSTAR = '**';
  2192. exports.ROOT_GLOBSTAR = '/**/*';
  2193. exports.SLASH_GLOBSTAR = '/**';
  2194. exports.DIR_SUFFIX = 'Dir';
  2195. exports.ANYMATCH_OPTS = {dot: true};
  2196. exports.STRING_TYPE = 'string';
  2197. exports.FUNCTION_TYPE = 'function';
  2198. exports.EMPTY_STR = '';
  2199. exports.EMPTY_FN = () => {};
  2200. exports.IDENTITY_FN = val => val;
  2201. exports.isWindows = platform === 'win32';
  2202. exports.isMacos = platform === 'darwin';
  2203. exports.isLinux = platform === 'linux';
  2204. exports.isIBMi = os.type() === 'OS400';
  2205. } (constants));
  2206. const fs$2 = require$$0$1;
  2207. const sysPath$2 = require$$0$2;
  2208. const { promisify: promisify$2 } = require$$2;
  2209. const isBinaryPath = isBinaryPath$1;
  2210. const {
  2211. isWindows: isWindows$1,
  2212. isLinux,
  2213. EMPTY_FN: EMPTY_FN$2,
  2214. EMPTY_STR: EMPTY_STR$1,
  2215. KEY_LISTENERS,
  2216. KEY_ERR,
  2217. KEY_RAW,
  2218. HANDLER_KEYS,
  2219. EV_CHANGE: EV_CHANGE$2,
  2220. EV_ADD: EV_ADD$2,
  2221. EV_ADD_DIR: EV_ADD_DIR$2,
  2222. EV_ERROR: EV_ERROR$2,
  2223. STR_DATA: STR_DATA$1,
  2224. STR_END: STR_END$2,
  2225. BRACE_START: BRACE_START$1,
  2226. STAR
  2227. } = constants;
  2228. const THROTTLE_MODE_WATCH = 'watch';
  2229. const open = promisify$2(fs$2.open);
  2230. const stat$2 = promisify$2(fs$2.stat);
  2231. const lstat$1 = promisify$2(fs$2.lstat);
  2232. const close = promisify$2(fs$2.close);
  2233. const fsrealpath = promisify$2(fs$2.realpath);
  2234. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  2235. // TODO: emit errors properly. Example: EMFILE on Macos.
  2236. const foreach = (val, fn) => {
  2237. if (val instanceof Set) {
  2238. val.forEach(fn);
  2239. } else {
  2240. fn(val);
  2241. }
  2242. };
  2243. const addAndConvert = (main, prop, item) => {
  2244. let container = main[prop];
  2245. if (!(container instanceof Set)) {
  2246. main[prop] = container = new Set([container]);
  2247. }
  2248. container.add(item);
  2249. };
  2250. const clearItem = cont => key => {
  2251. const set = cont[key];
  2252. if (set instanceof Set) {
  2253. set.clear();
  2254. } else {
  2255. delete cont[key];
  2256. }
  2257. };
  2258. const delFromSet = (main, prop, item) => {
  2259. const container = main[prop];
  2260. if (container instanceof Set) {
  2261. container.delete(item);
  2262. } else if (container === item) {
  2263. delete main[prop];
  2264. }
  2265. };
  2266. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  2267. /**
  2268. * @typedef {String} Path
  2269. */
  2270. // fs_watch helpers
  2271. // object to hold per-process fs_watch instances
  2272. // (may be shared across chokidar FSWatcher instances)
  2273. /**
  2274. * @typedef {Object} FsWatchContainer
  2275. * @property {Set} listeners
  2276. * @property {Set} errHandlers
  2277. * @property {Set} rawEmitters
  2278. * @property {fs.FSWatcher=} watcher
  2279. * @property {Boolean=} watcherUnusable
  2280. */
  2281. /**
  2282. * @type {Map<String,FsWatchContainer>}
  2283. */
  2284. const FsWatchInstances = new Map();
  2285. /**
  2286. * Instantiates the fs_watch interface
  2287. * @param {String} path to be watched
  2288. * @param {Object} options to be passed to fs_watch
  2289. * @param {Function} listener main event handler
  2290. * @param {Function} errHandler emits info about errors
  2291. * @param {Function} emitRaw emits raw event data
  2292. * @returns {fs.FSWatcher} new fsevents instance
  2293. */
  2294. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  2295. const handleEvent = (rawEvent, evPath) => {
  2296. listener(path);
  2297. emitRaw(rawEvent, evPath, {watchedPath: path});
  2298. // emit based on events occurring for files from a directory's watcher in
  2299. // case the file's watcher misses it (and rely on throttling to de-dupe)
  2300. if (evPath && path !== evPath) {
  2301. fsWatchBroadcast(
  2302. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  2303. );
  2304. }
  2305. };
  2306. try {
  2307. return fs$2.watch(path, options, handleEvent);
  2308. } catch (error) {
  2309. errHandler(error);
  2310. }
  2311. }
  2312. /**
  2313. * Helper for passing fs_watch event data to a collection of listeners
  2314. * @param {Path} fullPath absolute path bound to fs_watch instance
  2315. * @param {String} type listener type
  2316. * @param {*=} val1 arguments to be passed to listeners
  2317. * @param {*=} val2
  2318. * @param {*=} val3
  2319. */
  2320. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  2321. const cont = FsWatchInstances.get(fullPath);
  2322. if (!cont) return;
  2323. foreach(cont[type], (listener) => {
  2324. listener(val1, val2, val3);
  2325. });
  2326. };
  2327. /**
  2328. * Instantiates the fs_watch interface or binds listeners
  2329. * to an existing one covering the same file system entry
  2330. * @param {String} path
  2331. * @param {String} fullPath absolute path
  2332. * @param {Object} options to be passed to fs_watch
  2333. * @param {Object} handlers container for event listener functions
  2334. */
  2335. const setFsWatchListener = (path, fullPath, options, handlers) => {
  2336. const {listener, errHandler, rawEmitter} = handlers;
  2337. let cont = FsWatchInstances.get(fullPath);
  2338. /** @type {fs.FSWatcher=} */
  2339. let watcher;
  2340. if (!options.persistent) {
  2341. watcher = createFsWatchInstance(
  2342. path, options, listener, errHandler, rawEmitter
  2343. );
  2344. return watcher.close.bind(watcher);
  2345. }
  2346. if (cont) {
  2347. addAndConvert(cont, KEY_LISTENERS, listener);
  2348. addAndConvert(cont, KEY_ERR, errHandler);
  2349. addAndConvert(cont, KEY_RAW, rawEmitter);
  2350. } else {
  2351. watcher = createFsWatchInstance(
  2352. path,
  2353. options,
  2354. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  2355. errHandler, // no need to use broadcast here
  2356. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  2357. );
  2358. if (!watcher) return;
  2359. watcher.on(EV_ERROR$2, async (error) => {
  2360. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  2361. cont.watcherUnusable = true; // documented since Node 10.4.1
  2362. // Workaround for https://github.com/joyent/node/issues/4337
  2363. if (isWindows$1 && error.code === 'EPERM') {
  2364. try {
  2365. const fd = await open(path, 'r');
  2366. await close(fd);
  2367. broadcastErr(error);
  2368. } catch (err) {}
  2369. } else {
  2370. broadcastErr(error);
  2371. }
  2372. });
  2373. cont = {
  2374. listeners: listener,
  2375. errHandlers: errHandler,
  2376. rawEmitters: rawEmitter,
  2377. watcher
  2378. };
  2379. FsWatchInstances.set(fullPath, cont);
  2380. }
  2381. // const index = cont.listeners.indexOf(listener);
  2382. // removes this instance's listeners and closes the underlying fs_watch
  2383. // instance if there are no more listeners left
  2384. return () => {
  2385. delFromSet(cont, KEY_LISTENERS, listener);
  2386. delFromSet(cont, KEY_ERR, errHandler);
  2387. delFromSet(cont, KEY_RAW, rawEmitter);
  2388. if (isEmptySet(cont.listeners)) {
  2389. // Check to protect against issue gh-730.
  2390. // if (cont.watcherUnusable) {
  2391. cont.watcher.close();
  2392. // }
  2393. FsWatchInstances.delete(fullPath);
  2394. HANDLER_KEYS.forEach(clearItem(cont));
  2395. cont.watcher = undefined;
  2396. Object.freeze(cont);
  2397. }
  2398. };
  2399. };
  2400. // fs_watchFile helpers
  2401. // object to hold per-process fs_watchFile instances
  2402. // (may be shared across chokidar FSWatcher instances)
  2403. const FsWatchFileInstances = new Map();
  2404. /**
  2405. * Instantiates the fs_watchFile interface or binds listeners
  2406. * to an existing one covering the same file system entry
  2407. * @param {String} path to be watched
  2408. * @param {String} fullPath absolute path
  2409. * @param {Object} options options to be passed to fs_watchFile
  2410. * @param {Object} handlers container for event listener functions
  2411. * @returns {Function} closer
  2412. */
  2413. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  2414. const {listener, rawEmitter} = handlers;
  2415. let cont = FsWatchFileInstances.get(fullPath);
  2416. const copts = cont && cont.options;
  2417. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  2418. fs$2.unwatchFile(fullPath);
  2419. cont = undefined;
  2420. }
  2421. /* eslint-enable no-unused-vars, prefer-destructuring */
  2422. if (cont) {
  2423. addAndConvert(cont, KEY_LISTENERS, listener);
  2424. addAndConvert(cont, KEY_RAW, rawEmitter);
  2425. } else {
  2426. // TODO
  2427. // listeners.add(listener);
  2428. // rawEmitters.add(rawEmitter);
  2429. cont = {
  2430. listeners: listener,
  2431. rawEmitters: rawEmitter,
  2432. options,
  2433. watcher: fs$2.watchFile(fullPath, options, (curr, prev) => {
  2434. foreach(cont.rawEmitters, (rawEmitter) => {
  2435. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  2436. });
  2437. const currmtime = curr.mtimeMs;
  2438. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  2439. foreach(cont.listeners, (listener) => listener(path, curr));
  2440. }
  2441. })
  2442. };
  2443. FsWatchFileInstances.set(fullPath, cont);
  2444. }
  2445. // const index = cont.listeners.indexOf(listener);
  2446. // Removes this instance's listeners and closes the underlying fs_watchFile
  2447. // instance if there are no more listeners left.
  2448. return () => {
  2449. delFromSet(cont, KEY_LISTENERS, listener);
  2450. delFromSet(cont, KEY_RAW, rawEmitter);
  2451. if (isEmptySet(cont.listeners)) {
  2452. FsWatchFileInstances.delete(fullPath);
  2453. fs$2.unwatchFile(fullPath);
  2454. cont.options = cont.watcher = undefined;
  2455. Object.freeze(cont);
  2456. }
  2457. };
  2458. };
  2459. /**
  2460. * @mixin
  2461. */
  2462. class NodeFsHandler$1 {
  2463. /**
  2464. * @param {import("../index").FSWatcher} fsW
  2465. */
  2466. constructor(fsW) {
  2467. this.fsw = fsW;
  2468. this._boundHandleError = (error) => fsW._handleError(error);
  2469. }
  2470. /**
  2471. * Watch file for changes with fs_watchFile or fs_watch.
  2472. * @param {String} path to file or dir
  2473. * @param {Function} listener on fs change
  2474. * @returns {Function} closer for the watcher instance
  2475. */
  2476. _watchWithNodeFs(path, listener) {
  2477. const opts = this.fsw.options;
  2478. const directory = sysPath$2.dirname(path);
  2479. const basename = sysPath$2.basename(path);
  2480. const parent = this.fsw._getWatchedDir(directory);
  2481. parent.add(basename);
  2482. const absolutePath = sysPath$2.resolve(path);
  2483. const options = {persistent: opts.persistent};
  2484. if (!listener) listener = EMPTY_FN$2;
  2485. let closer;
  2486. if (opts.usePolling) {
  2487. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  2488. opts.binaryInterval : opts.interval;
  2489. closer = setFsWatchFileListener(path, absolutePath, options, {
  2490. listener,
  2491. rawEmitter: this.fsw._emitRaw
  2492. });
  2493. } else {
  2494. closer = setFsWatchListener(path, absolutePath, options, {
  2495. listener,
  2496. errHandler: this._boundHandleError,
  2497. rawEmitter: this.fsw._emitRaw
  2498. });
  2499. }
  2500. return closer;
  2501. }
  2502. /**
  2503. * Watch a file and emit add event if warranted.
  2504. * @param {Path} file Path
  2505. * @param {fs.Stats} stats result of fs_stat
  2506. * @param {Boolean} initialAdd was the file added at watch instantiation?
  2507. * @returns {Function} closer for the watcher instance
  2508. */
  2509. _handleFile(file, stats, initialAdd) {
  2510. if (this.fsw.closed) {
  2511. return;
  2512. }
  2513. const dirname = sysPath$2.dirname(file);
  2514. const basename = sysPath$2.basename(file);
  2515. const parent = this.fsw._getWatchedDir(dirname);
  2516. // stats is always present
  2517. let prevStats = stats;
  2518. // if the file is already being watched, do nothing
  2519. if (parent.has(basename)) return;
  2520. const listener = async (path, newStats) => {
  2521. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  2522. if (!newStats || newStats.mtimeMs === 0) {
  2523. try {
  2524. const newStats = await stat$2(file);
  2525. if (this.fsw.closed) return;
  2526. // Check that change event was not fired because of changed only accessTime.
  2527. const at = newStats.atimeMs;
  2528. const mt = newStats.mtimeMs;
  2529. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  2530. this.fsw._emit(EV_CHANGE$2, file, newStats);
  2531. }
  2532. if (isLinux && prevStats.ino !== newStats.ino) {
  2533. this.fsw._closeFile(path);
  2534. prevStats = newStats;
  2535. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  2536. } else {
  2537. prevStats = newStats;
  2538. }
  2539. } catch (error) {
  2540. // Fix issues where mtime is null but file is still present
  2541. this.fsw._remove(dirname, basename);
  2542. }
  2543. // add is about to be emitted if file not already tracked in parent
  2544. } else if (parent.has(basename)) {
  2545. // Check that change event was not fired because of changed only accessTime.
  2546. const at = newStats.atimeMs;
  2547. const mt = newStats.mtimeMs;
  2548. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  2549. this.fsw._emit(EV_CHANGE$2, file, newStats);
  2550. }
  2551. prevStats = newStats;
  2552. }
  2553. };
  2554. // kick off the watcher
  2555. const closer = this._watchWithNodeFs(file, listener);
  2556. // emit an add event if we're supposed to
  2557. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  2558. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  2559. this.fsw._emit(EV_ADD$2, file, stats);
  2560. }
  2561. return closer;
  2562. }
  2563. /**
  2564. * Handle symlinks encountered while reading a dir.
  2565. * @param {Object} entry returned by readdirp
  2566. * @param {String} directory path of dir being read
  2567. * @param {String} path of this item
  2568. * @param {String} item basename of this item
  2569. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  2570. */
  2571. async _handleSymlink(entry, directory, path, item) {
  2572. if (this.fsw.closed) {
  2573. return;
  2574. }
  2575. const full = entry.fullPath;
  2576. const dir = this.fsw._getWatchedDir(directory);
  2577. if (!this.fsw.options.followSymlinks) {
  2578. // watch symlink directly (don't follow) and detect changes
  2579. this.fsw._incrReadyCount();
  2580. let linkPath;
  2581. try {
  2582. linkPath = await fsrealpath(path);
  2583. } catch (e) {
  2584. this.fsw._emitReady();
  2585. return true;
  2586. }
  2587. if (this.fsw.closed) return;
  2588. if (dir.has(item)) {
  2589. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  2590. this.fsw._symlinkPaths.set(full, linkPath);
  2591. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  2592. }
  2593. } else {
  2594. dir.add(item);
  2595. this.fsw._symlinkPaths.set(full, linkPath);
  2596. this.fsw._emit(EV_ADD$2, path, entry.stats);
  2597. }
  2598. this.fsw._emitReady();
  2599. return true;
  2600. }
  2601. // don't follow the same symlink more than once
  2602. if (this.fsw._symlinkPaths.has(full)) {
  2603. return true;
  2604. }
  2605. this.fsw._symlinkPaths.set(full, true);
  2606. }
  2607. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  2608. // Normalize the directory name on Windows
  2609. directory = sysPath$2.join(directory, EMPTY_STR$1);
  2610. if (!wh.hasGlob) {
  2611. throttler = this.fsw._throttle('readdir', directory, 1000);
  2612. if (!throttler) return;
  2613. }
  2614. const previous = this.fsw._getWatchedDir(wh.path);
  2615. const current = new Set();
  2616. let stream = this.fsw._readdirp(directory, {
  2617. fileFilter: entry => wh.filterPath(entry),
  2618. directoryFilter: entry => wh.filterDir(entry),
  2619. depth: 0
  2620. }).on(STR_DATA$1, async (entry) => {
  2621. if (this.fsw.closed) {
  2622. stream = undefined;
  2623. return;
  2624. }
  2625. const item = entry.path;
  2626. let path = sysPath$2.join(directory, item);
  2627. current.add(item);
  2628. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  2629. return;
  2630. }
  2631. if (this.fsw.closed) {
  2632. stream = undefined;
  2633. return;
  2634. }
  2635. // Files that present in current directory snapshot
  2636. // but absent in previous are added to watch list and
  2637. // emit `add` event.
  2638. if (item === target || !target && !previous.has(item)) {
  2639. this.fsw._incrReadyCount();
  2640. // ensure relativeness of path is preserved in case of watcher reuse
  2641. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  2642. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  2643. }
  2644. }).on(EV_ERROR$2, this._boundHandleError);
  2645. return new Promise(resolve =>
  2646. stream.once(STR_END$2, () => {
  2647. if (this.fsw.closed) {
  2648. stream = undefined;
  2649. return;
  2650. }
  2651. const wasThrottled = throttler ? throttler.clear() : false;
  2652. resolve();
  2653. // Files that absent in current directory snapshot
  2654. // but present in previous emit `remove` event
  2655. // and are removed from @watched[directory].
  2656. previous.getChildren().filter((item) => {
  2657. return item !== directory &&
  2658. !current.has(item) &&
  2659. // in case of intersecting globs;
  2660. // a path may have been filtered out of this readdir, but
  2661. // shouldn't be removed because it matches a different glob
  2662. (!wh.hasGlob || wh.filterPath({
  2663. fullPath: sysPath$2.resolve(directory, item)
  2664. }));
  2665. }).forEach((item) => {
  2666. this.fsw._remove(directory, item);
  2667. });
  2668. stream = undefined;
  2669. // one more time for any missed in case changes came in extremely quickly
  2670. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  2671. })
  2672. );
  2673. }
  2674. /**
  2675. * Read directory to add / remove files from `@watched` list and re-read it on change.
  2676. * @param {String} dir fs path
  2677. * @param {fs.Stats} stats
  2678. * @param {Boolean} initialAdd
  2679. * @param {Number} depth relative to user-supplied path
  2680. * @param {String} target child path targeted for watch
  2681. * @param {Object} wh Common watch helpers for this path
  2682. * @param {String} realpath
  2683. * @returns {Promise<Function>} closer for the watcher instance.
  2684. */
  2685. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  2686. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  2687. const tracked = parentDir.has(sysPath$2.basename(dir));
  2688. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  2689. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  2690. }
  2691. // ensure dir is tracked (harmless if redundant)
  2692. parentDir.add(sysPath$2.basename(dir));
  2693. this.fsw._getWatchedDir(dir);
  2694. let throttler;
  2695. let closer;
  2696. const oDepth = this.fsw.options.depth;
  2697. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  2698. if (!target) {
  2699. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  2700. if (this.fsw.closed) return;
  2701. }
  2702. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  2703. // if current directory is removed, do nothing
  2704. if (stats && stats.mtimeMs === 0) return;
  2705. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  2706. });
  2707. }
  2708. return closer;
  2709. }
  2710. /**
  2711. * Handle added file, directory, or glob pattern.
  2712. * Delegates call to _handleFile / _handleDir after checks.
  2713. * @param {String} path to file or ir
  2714. * @param {Boolean} initialAdd was the file added at watch instantiation?
  2715. * @param {Object} priorWh depth relative to user-supplied path
  2716. * @param {Number} depth Child path actually targeted for watch
  2717. * @param {String=} target Child path actually targeted for watch
  2718. * @returns {Promise}
  2719. */
  2720. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  2721. const ready = this.fsw._emitReady;
  2722. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  2723. ready();
  2724. return false;
  2725. }
  2726. const wh = this.fsw._getWatchHelpers(path, depth);
  2727. if (!wh.hasGlob && priorWh) {
  2728. wh.hasGlob = priorWh.hasGlob;
  2729. wh.globFilter = priorWh.globFilter;
  2730. wh.filterPath = entry => priorWh.filterPath(entry);
  2731. wh.filterDir = entry => priorWh.filterDir(entry);
  2732. }
  2733. // evaluate what is at the path we're being asked to watch
  2734. try {
  2735. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  2736. if (this.fsw.closed) return;
  2737. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  2738. ready();
  2739. return false;
  2740. }
  2741. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  2742. let closer;
  2743. if (stats.isDirectory()) {
  2744. const absPath = sysPath$2.resolve(path);
  2745. const targetPath = follow ? await fsrealpath(path) : path;
  2746. if (this.fsw.closed) return;
  2747. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  2748. if (this.fsw.closed) return;
  2749. // preserve this symlink's target path
  2750. if (absPath !== targetPath && targetPath !== undefined) {
  2751. this.fsw._symlinkPaths.set(absPath, targetPath);
  2752. }
  2753. } else if (stats.isSymbolicLink()) {
  2754. const targetPath = follow ? await fsrealpath(path) : path;
  2755. if (this.fsw.closed) return;
  2756. const parent = sysPath$2.dirname(wh.watchPath);
  2757. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  2758. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  2759. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  2760. if (this.fsw.closed) return;
  2761. // preserve this symlink's target path
  2762. if (targetPath !== undefined) {
  2763. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  2764. }
  2765. } else {
  2766. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  2767. }
  2768. ready();
  2769. this.fsw._addPathCloser(path, closer);
  2770. return false;
  2771. } catch (error) {
  2772. if (this.fsw._handleError(error)) {
  2773. ready();
  2774. return path;
  2775. }
  2776. }
  2777. }
  2778. }
  2779. var nodefsHandler = NodeFsHandler$1;
  2780. var fseventsHandler = {exports: {}};
  2781. const require$$3 = /*@__PURE__*/getAugmentedNamespace(fseventsImporter);
  2782. const fs$1 = require$$0$1;
  2783. const sysPath$1 = require$$0$2;
  2784. const { promisify: promisify$1 } = require$$2;
  2785. let fsevents;
  2786. try {
  2787. fsevents = require$$3.getFsEvents();
  2788. } catch (error) {
  2789. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  2790. }
  2791. if (fsevents) {
  2792. // TODO: real check
  2793. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  2794. if (mtch && mtch[1] && mtch[2]) {
  2795. const maj = Number.parseInt(mtch[1], 10);
  2796. const min = Number.parseInt(mtch[2], 10);
  2797. if (maj === 8 && min < 16) {
  2798. fsevents = undefined;
  2799. }
  2800. }
  2801. }
  2802. const {
  2803. EV_ADD: EV_ADD$1,
  2804. EV_CHANGE: EV_CHANGE$1,
  2805. EV_ADD_DIR: EV_ADD_DIR$1,
  2806. EV_UNLINK: EV_UNLINK$1,
  2807. EV_ERROR: EV_ERROR$1,
  2808. STR_DATA,
  2809. STR_END: STR_END$1,
  2810. FSEVENT_CREATED,
  2811. FSEVENT_MODIFIED,
  2812. FSEVENT_DELETED,
  2813. FSEVENT_MOVED,
  2814. // FSEVENT_CLONED,
  2815. FSEVENT_UNKNOWN,
  2816. FSEVENT_TYPE_FILE,
  2817. FSEVENT_TYPE_DIRECTORY,
  2818. FSEVENT_TYPE_SYMLINK,
  2819. ROOT_GLOBSTAR,
  2820. DIR_SUFFIX,
  2821. DOT_SLASH,
  2822. FUNCTION_TYPE: FUNCTION_TYPE$1,
  2823. EMPTY_FN: EMPTY_FN$1,
  2824. IDENTITY_FN
  2825. } = constants;
  2826. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  2827. const stat$1 = promisify$1(fs$1.stat);
  2828. const lstat = promisify$1(fs$1.lstat);
  2829. const realpath = promisify$1(fs$1.realpath);
  2830. const statMethods = { stat: stat$1, lstat };
  2831. /**
  2832. * @typedef {String} Path
  2833. */
  2834. /**
  2835. * @typedef {Object} FsEventsWatchContainer
  2836. * @property {Set<Function>} listeners
  2837. * @property {Function} rawEmitter
  2838. * @property {{stop: Function}} watcher
  2839. */
  2840. // fsevents instance helper functions
  2841. /**
  2842. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  2843. * @type {Map<Path,FsEventsWatchContainer>}
  2844. */
  2845. const FSEventsWatchers = new Map();
  2846. // Threshold of duplicate path prefixes at which to start
  2847. // consolidating going forward
  2848. const consolidateThreshhold = 10;
  2849. const wrongEventFlags = new Set([
  2850. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  2851. ]);
  2852. /**
  2853. * Instantiates the fsevents interface
  2854. * @param {Path} path path to be watched
  2855. * @param {Function} callback called when fsevents is bound and ready
  2856. * @returns {{stop: Function}} new fsevents instance
  2857. */
  2858. const createFSEventsInstance = (path, callback) => {
  2859. const stop = fsevents.watch(path, callback);
  2860. return {stop};
  2861. };
  2862. /**
  2863. * Instantiates the fsevents interface or binds listeners to an existing one covering
  2864. * the same file tree.
  2865. * @param {Path} path - to be watched
  2866. * @param {Path} realPath - real path for symlinks
  2867. * @param {Function} listener - called when fsevents emits events
  2868. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  2869. * @returns {Function} closer
  2870. */
  2871. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  2872. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  2873. const parentPath = sysPath$1.dirname(watchPath);
  2874. let cont = FSEventsWatchers.get(watchPath);
  2875. // If we've accumulated a substantial number of paths that
  2876. // could have been consolidated by watching one directory
  2877. // above the current one, create a watcher on the parent
  2878. // path instead, so that we do consolidate going forward.
  2879. if (couldConsolidate(parentPath)) {
  2880. watchPath = parentPath;
  2881. }
  2882. const resolvedPath = sysPath$1.resolve(path);
  2883. const hasSymlink = resolvedPath !== realPath;
  2884. const filteredListener = (fullPath, flags, info) => {
  2885. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  2886. if (
  2887. fullPath === resolvedPath ||
  2888. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  2889. ) listener(fullPath, flags, info);
  2890. };
  2891. // check if there is already a watcher on a parent path
  2892. // modifies `watchPath` to the parent path when it finds a match
  2893. let watchedParent = false;
  2894. for (const watchedPath of FSEventsWatchers.keys()) {
  2895. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  2896. watchPath = watchedPath;
  2897. cont = FSEventsWatchers.get(watchPath);
  2898. watchedParent = true;
  2899. break;
  2900. }
  2901. }
  2902. if (cont || watchedParent) {
  2903. cont.listeners.add(filteredListener);
  2904. } else {
  2905. cont = {
  2906. listeners: new Set([filteredListener]),
  2907. rawEmitter,
  2908. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  2909. if (!cont.listeners.size) return;
  2910. const info = fsevents.getInfo(fullPath, flags);
  2911. cont.listeners.forEach(list => {
  2912. list(fullPath, flags, info);
  2913. });
  2914. cont.rawEmitter(info.event, fullPath, info);
  2915. })
  2916. };
  2917. FSEventsWatchers.set(watchPath, cont);
  2918. }
  2919. // removes this instance's listeners and closes the underlying fsevents
  2920. // instance if there are no more listeners left
  2921. return () => {
  2922. const lst = cont.listeners;
  2923. lst.delete(filteredListener);
  2924. if (!lst.size) {
  2925. FSEventsWatchers.delete(watchPath);
  2926. if (cont.watcher) return cont.watcher.stop().then(() => {
  2927. cont.rawEmitter = cont.watcher = undefined;
  2928. Object.freeze(cont);
  2929. });
  2930. }
  2931. };
  2932. }
  2933. // Decide whether or not we should start a new higher-level
  2934. // parent watcher
  2935. const couldConsolidate = (path) => {
  2936. let count = 0;
  2937. for (const watchPath of FSEventsWatchers.keys()) {
  2938. if (watchPath.indexOf(path) === 0) {
  2939. count++;
  2940. if (count >= consolidateThreshhold) {
  2941. return true;
  2942. }
  2943. }
  2944. }
  2945. return false;
  2946. };
  2947. // returns boolean indicating whether fsevents can be used
  2948. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  2949. // determines subdirectory traversal levels from root to path
  2950. const calcDepth = (path, root) => {
  2951. let i = 0;
  2952. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  2953. return i;
  2954. };
  2955. // returns boolean indicating whether the fsevents' event info has the same type
  2956. // as the one returned by fs.stat
  2957. const sameTypes = (info, stats) => (
  2958. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  2959. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  2960. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  2961. );
  2962. /**
  2963. * @mixin
  2964. */
  2965. class FsEventsHandler$1 {
  2966. /**
  2967. * @param {import('../index').FSWatcher} fsw
  2968. */
  2969. constructor(fsw) {
  2970. this.fsw = fsw;
  2971. }
  2972. checkIgnored(path, stats) {
  2973. const ipaths = this.fsw._ignoredPaths;
  2974. if (this.fsw._isIgnored(path, stats)) {
  2975. ipaths.add(path);
  2976. if (stats && stats.isDirectory()) {
  2977. ipaths.add(path + ROOT_GLOBSTAR);
  2978. }
  2979. return true;
  2980. }
  2981. ipaths.delete(path);
  2982. ipaths.delete(path + ROOT_GLOBSTAR);
  2983. }
  2984. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  2985. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  2986. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2987. }
  2988. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  2989. try {
  2990. const stats = await stat$1(path);
  2991. if (this.fsw.closed) return;
  2992. if (sameTypes(info, stats)) {
  2993. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2994. } else {
  2995. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  2996. }
  2997. } catch (error) {
  2998. if (error.code === 'EACCES') {
  2999. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3000. } else {
  3001. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3002. }
  3003. }
  3004. }
  3005. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  3006. if (this.fsw.closed || this.checkIgnored(path)) return;
  3007. if (event === EV_UNLINK$1) {
  3008. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  3009. // suppress unlink events on never before seen files
  3010. if (isDirectory || watchedDir.has(item)) {
  3011. this.fsw._remove(parent, item, isDirectory);
  3012. }
  3013. } else {
  3014. if (event === EV_ADD$1) {
  3015. // track new directories
  3016. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  3017. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  3018. // push symlinks back to the top of the stack to get handled
  3019. const curDepth = opts.depth === undefined ?
  3020. undefined : calcDepth(fullPath, realPath) + 1;
  3021. return this._addToFsEvents(path, false, true, curDepth);
  3022. }
  3023. // track new paths
  3024. // (other than symlinks being followed, which will be tracked soon)
  3025. this.fsw._getWatchedDir(parent).add(item);
  3026. }
  3027. /**
  3028. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  3029. */
  3030. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  3031. this.fsw._emit(eventName, path);
  3032. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  3033. }
  3034. }
  3035. /**
  3036. * Handle symlinks encountered during directory scan
  3037. * @param {String} watchPath - file/dir path to be watched with fsevents
  3038. * @param {String} realPath - real path (in case of symlinks)
  3039. * @param {Function} transform - path transformer
  3040. * @param {Function} globFilter - path filter in case a glob pattern was provided
  3041. * @returns {Function} closer for the watcher instance
  3042. */
  3043. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  3044. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  3045. const opts = this.fsw.options;
  3046. const watchCallback = async (fullPath, flags, info) => {
  3047. if (this.fsw.closed) return;
  3048. if (
  3049. opts.depth !== undefined &&
  3050. calcDepth(fullPath, realPath) > opts.depth
  3051. ) return;
  3052. const path = transform(sysPath$1.join(
  3053. watchPath, sysPath$1.relative(watchPath, fullPath)
  3054. ));
  3055. if (globFilter && !globFilter(path)) return;
  3056. // ensure directories are tracked
  3057. const parent = sysPath$1.dirname(path);
  3058. const item = sysPath$1.basename(path);
  3059. const watchedDir = this.fsw._getWatchedDir(
  3060. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  3061. );
  3062. // correct for wrong events emitted
  3063. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  3064. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  3065. let stats;
  3066. try {
  3067. stats = await stat$1(path);
  3068. } catch (error) {}
  3069. if (this.fsw.closed) return;
  3070. if (this.checkIgnored(path, stats)) return;
  3071. if (sameTypes(info, stats)) {
  3072. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3073. } else {
  3074. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3075. }
  3076. } else {
  3077. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3078. }
  3079. } else {
  3080. switch (info.event) {
  3081. case FSEVENT_CREATED:
  3082. case FSEVENT_MODIFIED:
  3083. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3084. case FSEVENT_DELETED:
  3085. case FSEVENT_MOVED:
  3086. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  3087. }
  3088. }
  3089. };
  3090. const closer = setFSEventsListener(
  3091. watchPath,
  3092. realPath,
  3093. watchCallback,
  3094. this.fsw._emitRaw
  3095. );
  3096. this.fsw._emitReady();
  3097. return closer;
  3098. }
  3099. /**
  3100. * Handle symlinks encountered during directory scan
  3101. * @param {String} linkPath path to symlink
  3102. * @param {String} fullPath absolute path to the symlink
  3103. * @param {Function} transform pre-existing path transformer
  3104. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  3105. * @returns {Promise<void>}
  3106. */
  3107. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  3108. // don't follow the same symlink more than once
  3109. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  3110. this.fsw._symlinkPaths.set(fullPath, true);
  3111. this.fsw._incrReadyCount();
  3112. try {
  3113. const linkTarget = await realpath(linkPath);
  3114. if (this.fsw.closed) return;
  3115. if (this.fsw._isIgnored(linkTarget)) {
  3116. return this.fsw._emitReady();
  3117. }
  3118. this.fsw._incrReadyCount();
  3119. // add the linkTarget for watching with a wrapper for transform
  3120. // that causes emitted paths to incorporate the link's path
  3121. this._addToFsEvents(linkTarget || linkPath, (path) => {
  3122. let aliasedPath = linkPath;
  3123. if (linkTarget && linkTarget !== DOT_SLASH) {
  3124. aliasedPath = path.replace(linkTarget, linkPath);
  3125. } else if (path !== DOT_SLASH) {
  3126. aliasedPath = sysPath$1.join(linkPath, path);
  3127. }
  3128. return transform(aliasedPath);
  3129. }, false, curDepth);
  3130. } catch(error) {
  3131. if (this.fsw._handleError(error)) {
  3132. return this.fsw._emitReady();
  3133. }
  3134. }
  3135. }
  3136. /**
  3137. *
  3138. * @param {Path} newPath
  3139. * @param {fs.Stats} stats
  3140. */
  3141. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  3142. const pp = processPath(newPath);
  3143. const isDir = stats.isDirectory();
  3144. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  3145. const base = sysPath$1.basename(pp);
  3146. // ensure empty dirs get tracked
  3147. if (isDir) this.fsw._getWatchedDir(pp);
  3148. if (dirObj.has(base)) return;
  3149. dirObj.add(base);
  3150. if (!opts.ignoreInitial || forceAdd === true) {
  3151. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  3152. }
  3153. }
  3154. initWatch(realPath, path, wh, processPath) {
  3155. if (this.fsw.closed) return;
  3156. const closer = this._watchWithFsEvents(
  3157. wh.watchPath,
  3158. sysPath$1.resolve(realPath || wh.watchPath),
  3159. processPath,
  3160. wh.globFilter
  3161. );
  3162. this.fsw._addPathCloser(path, closer);
  3163. }
  3164. /**
  3165. * Handle added path with fsevents
  3166. * @param {String} path file/dir path or glob pattern
  3167. * @param {Function|Boolean=} transform converts working path to what the user expects
  3168. * @param {Boolean=} forceAdd ensure add is emitted
  3169. * @param {Number=} priorDepth Level of subdirectories already traversed.
  3170. * @returns {Promise<void>}
  3171. */
  3172. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  3173. if (this.fsw.closed) {
  3174. return;
  3175. }
  3176. const opts = this.fsw.options;
  3177. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  3178. const wh = this.fsw._getWatchHelpers(path);
  3179. // evaluate what is at the path we're being asked to watch
  3180. try {
  3181. const stats = await statMethods[wh.statMethod](wh.watchPath);
  3182. if (this.fsw.closed) return;
  3183. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  3184. throw null;
  3185. }
  3186. if (stats.isDirectory()) {
  3187. // emit addDir unless this is a glob parent
  3188. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  3189. // don't recurse further if it would exceed depth setting
  3190. if (priorDepth && priorDepth > opts.depth) return;
  3191. // scan the contents of the dir
  3192. this.fsw._readdirp(wh.watchPath, {
  3193. fileFilter: entry => wh.filterPath(entry),
  3194. directoryFilter: entry => wh.filterDir(entry),
  3195. ...Depth(opts.depth - (priorDepth || 0))
  3196. }).on(STR_DATA, (entry) => {
  3197. // need to check filterPath on dirs b/c filterDir is less restrictive
  3198. if (this.fsw.closed) {
  3199. return;
  3200. }
  3201. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  3202. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  3203. const {fullPath} = entry;
  3204. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  3205. // preserve the current depth here since it can't be derived from
  3206. // real paths past the symlink
  3207. const curDepth = opts.depth === undefined ?
  3208. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  3209. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  3210. } else {
  3211. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  3212. }
  3213. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  3214. this.fsw._emitReady();
  3215. });
  3216. } else {
  3217. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  3218. this.fsw._emitReady();
  3219. }
  3220. } catch (error) {
  3221. if (!error || this.fsw._handleError(error)) {
  3222. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  3223. this.fsw._emitReady();
  3224. this.fsw._emitReady();
  3225. }
  3226. }
  3227. if (opts.persistent && forceAdd !== true) {
  3228. if (typeof transform === FUNCTION_TYPE$1) {
  3229. // realpath has already been resolved
  3230. this.initWatch(undefined, path, wh, processPath);
  3231. } else {
  3232. let realPath;
  3233. try {
  3234. realPath = await realpath(wh.watchPath);
  3235. } catch (e) {}
  3236. this.initWatch(realPath, path, wh, processPath);
  3237. }
  3238. }
  3239. }
  3240. }
  3241. fseventsHandler.exports = FsEventsHandler$1;
  3242. fseventsHandler.exports.canUse = canUse;
  3243. const { EventEmitter } = require$$0$3;
  3244. const fs = require$$0$1;
  3245. const sysPath = require$$0$2;
  3246. const { promisify } = require$$2;
  3247. const readdirp = readdirp_1;
  3248. const anymatch = anymatch$2.exports.default;
  3249. const globParent = globParent$1;
  3250. const isGlob = isGlob$2;
  3251. const braces = braces_1;
  3252. const normalizePath = normalizePath$2;
  3253. const NodeFsHandler = nodefsHandler;
  3254. const FsEventsHandler = fseventsHandler.exports;
  3255. const {
  3256. EV_ALL,
  3257. EV_READY,
  3258. EV_ADD,
  3259. EV_CHANGE,
  3260. EV_UNLINK,
  3261. EV_ADD_DIR,
  3262. EV_UNLINK_DIR,
  3263. EV_RAW,
  3264. EV_ERROR,
  3265. STR_CLOSE,
  3266. STR_END,
  3267. BACK_SLASH_RE,
  3268. DOUBLE_SLASH_RE,
  3269. SLASH_OR_BACK_SLASH_RE,
  3270. DOT_RE,
  3271. REPLACER_RE,
  3272. SLASH,
  3273. SLASH_SLASH,
  3274. BRACE_START,
  3275. BANG,
  3276. ONE_DOT,
  3277. TWO_DOTS,
  3278. GLOBSTAR,
  3279. SLASH_GLOBSTAR,
  3280. ANYMATCH_OPTS,
  3281. STRING_TYPE,
  3282. FUNCTION_TYPE,
  3283. EMPTY_STR,
  3284. EMPTY_FN,
  3285. isWindows,
  3286. isMacos,
  3287. isIBMi
  3288. } = constants;
  3289. const stat = promisify(fs.stat);
  3290. const readdir = promisify(fs.readdir);
  3291. /**
  3292. * @typedef {String} Path
  3293. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  3294. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  3295. */
  3296. /**
  3297. *
  3298. * @typedef {Object} WatchHelpers
  3299. * @property {Boolean} followSymlinks
  3300. * @property {'stat'|'lstat'} statMethod
  3301. * @property {Path} path
  3302. * @property {Path} watchPath
  3303. * @property {Function} entryPath
  3304. * @property {Boolean} hasGlob
  3305. * @property {Object} globFilter
  3306. * @property {Function} filterPath
  3307. * @property {Function} filterDir
  3308. */
  3309. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  3310. const flatten = (list, result = []) => {
  3311. list.forEach(item => {
  3312. if (Array.isArray(item)) {
  3313. flatten(item, result);
  3314. } else {
  3315. result.push(item);
  3316. }
  3317. });
  3318. return result;
  3319. };
  3320. const unifyPaths = (paths_) => {
  3321. /**
  3322. * @type {Array<String>}
  3323. */
  3324. const paths = flatten(arrify(paths_));
  3325. if (!paths.every(p => typeof p === STRING_TYPE)) {
  3326. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  3327. }
  3328. return paths.map(normalizePathToUnix);
  3329. };
  3330. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  3331. // because "//StoragePC/DrivePool/Movies" is a valid network path
  3332. const toUnix = (string) => {
  3333. let str = string.replace(BACK_SLASH_RE, SLASH);
  3334. let prepend = false;
  3335. if (str.startsWith(SLASH_SLASH)) {
  3336. prepend = true;
  3337. }
  3338. while (str.match(DOUBLE_SLASH_RE)) {
  3339. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  3340. }
  3341. if (prepend) {
  3342. str = SLASH + str;
  3343. }
  3344. return str;
  3345. };
  3346. // Our version of upath.normalize
  3347. // TODO: this is not equal to path-normalize module - investigate why
  3348. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  3349. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  3350. if (typeof path !== STRING_TYPE) return path;
  3351. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  3352. };
  3353. const getAbsolutePath = (path, cwd) => {
  3354. if (sysPath.isAbsolute(path)) {
  3355. return path;
  3356. }
  3357. if (path.startsWith(BANG)) {
  3358. return BANG + sysPath.join(cwd, path.slice(1));
  3359. }
  3360. return sysPath.join(cwd, path);
  3361. };
  3362. const undef = (opts, key) => opts[key] === undefined;
  3363. /**
  3364. * Directory entry.
  3365. * @property {Path} path
  3366. * @property {Set<Path>} items
  3367. */
  3368. class DirEntry {
  3369. /**
  3370. * @param {Path} dir
  3371. * @param {Function} removeWatcher
  3372. */
  3373. constructor(dir, removeWatcher) {
  3374. this.path = dir;
  3375. this._removeWatcher = removeWatcher;
  3376. /** @type {Set<Path>} */
  3377. this.items = new Set();
  3378. }
  3379. add(item) {
  3380. const {items} = this;
  3381. if (!items) return;
  3382. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  3383. }
  3384. async remove(item) {
  3385. const {items} = this;
  3386. if (!items) return;
  3387. items.delete(item);
  3388. if (items.size > 0) return;
  3389. const dir = this.path;
  3390. try {
  3391. await readdir(dir);
  3392. } catch (err) {
  3393. if (this._removeWatcher) {
  3394. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  3395. }
  3396. }
  3397. }
  3398. has(item) {
  3399. const {items} = this;
  3400. if (!items) return;
  3401. return items.has(item);
  3402. }
  3403. /**
  3404. * @returns {Array<String>}
  3405. */
  3406. getChildren() {
  3407. const {items} = this;
  3408. if (!items) return;
  3409. return [...items.values()];
  3410. }
  3411. dispose() {
  3412. this.items.clear();
  3413. delete this.path;
  3414. delete this._removeWatcher;
  3415. delete this.items;
  3416. Object.freeze(this);
  3417. }
  3418. }
  3419. const STAT_METHOD_F = 'stat';
  3420. const STAT_METHOD_L = 'lstat';
  3421. class WatchHelper {
  3422. constructor(path, watchPath, follow, fsw) {
  3423. this.fsw = fsw;
  3424. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  3425. this.watchPath = watchPath;
  3426. this.fullWatchPath = sysPath.resolve(watchPath);
  3427. this.hasGlob = watchPath !== path;
  3428. /** @type {object|boolean} */
  3429. if (path === EMPTY_STR) this.hasGlob = false;
  3430. this.globSymlink = this.hasGlob && follow ? undefined : false;
  3431. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  3432. this.dirParts = this.getDirParts(path);
  3433. this.dirParts.forEach((parts) => {
  3434. if (parts.length > 1) parts.pop();
  3435. });
  3436. this.followSymlinks = follow;
  3437. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  3438. }
  3439. checkGlobSymlink(entry) {
  3440. // only need to resolve once
  3441. // first entry should always have entry.parentDir === EMPTY_STR
  3442. if (this.globSymlink === undefined) {
  3443. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  3444. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  3445. }
  3446. if (this.globSymlink) {
  3447. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  3448. }
  3449. return entry.fullPath;
  3450. }
  3451. entryPath(entry) {
  3452. return sysPath.join(this.watchPath,
  3453. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  3454. );
  3455. }
  3456. filterPath(entry) {
  3457. const {stats} = entry;
  3458. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  3459. const resolvedPath = this.entryPath(entry);
  3460. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  3461. this.globFilter(resolvedPath) : true;
  3462. return matchesGlob &&
  3463. this.fsw._isntIgnored(resolvedPath, stats) &&
  3464. this.fsw._hasReadPermissions(stats);
  3465. }
  3466. getDirParts(path) {
  3467. if (!this.hasGlob) return [];
  3468. const parts = [];
  3469. const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
  3470. expandedPath.forEach((path) => {
  3471. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  3472. });
  3473. return parts;
  3474. }
  3475. filterDir(entry) {
  3476. if (this.hasGlob) {
  3477. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  3478. let globstar = false;
  3479. this.unmatchedGlob = !this.dirParts.some((parts) => {
  3480. return parts.every((part, i) => {
  3481. if (part === GLOBSTAR) globstar = true;
  3482. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  3483. });
  3484. });
  3485. }
  3486. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  3487. }
  3488. }
  3489. /**
  3490. * Watches files & directories for changes. Emitted events:
  3491. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  3492. *
  3493. * new FSWatcher()
  3494. * .add(directories)
  3495. * .on('add', path => log('File', path, 'was added'))
  3496. */
  3497. class FSWatcher extends EventEmitter {
  3498. // Not indenting methods for history sake; for now.
  3499. constructor(_opts) {
  3500. super();
  3501. const opts = {};
  3502. if (_opts) Object.assign(opts, _opts); // for frozen objects
  3503. /** @type {Map<String, DirEntry>} */
  3504. this._watched = new Map();
  3505. /** @type {Map<String, Array>} */
  3506. this._closers = new Map();
  3507. /** @type {Set<String>} */
  3508. this._ignoredPaths = new Set();
  3509. /** @type {Map<ThrottleType, Map>} */
  3510. this._throttled = new Map();
  3511. /** @type {Map<Path, String|Boolean>} */
  3512. this._symlinkPaths = new Map();
  3513. this._streams = new Set();
  3514. this.closed = false;
  3515. // Set up default options.
  3516. if (undef(opts, 'persistent')) opts.persistent = true;
  3517. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  3518. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  3519. if (undef(opts, 'interval')) opts.interval = 100;
  3520. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  3521. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  3522. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  3523. // Enable fsevents on OS X when polling isn't explicitly enabled.
  3524. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  3525. // If we can't use fsevents, ensure the options reflect it's disabled.
  3526. const canUseFsEvents = FsEventsHandler.canUse();
  3527. if (!canUseFsEvents) opts.useFsEvents = false;
  3528. // Use polling on Mac if not using fsevents.
  3529. // Other platforms use non-polling fs_watch.
  3530. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  3531. opts.usePolling = isMacos;
  3532. }
  3533. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  3534. if(isIBMi) {
  3535. opts.usePolling = true;
  3536. }
  3537. // Global override (useful for end-developers that need to force polling for all
  3538. // instances of chokidar, regardless of usage/dependency depth)
  3539. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  3540. if (envPoll !== undefined) {
  3541. const envLower = envPoll.toLowerCase();
  3542. if (envLower === 'false' || envLower === '0') {
  3543. opts.usePolling = false;
  3544. } else if (envLower === 'true' || envLower === '1') {
  3545. opts.usePolling = true;
  3546. } else {
  3547. opts.usePolling = !!envLower;
  3548. }
  3549. }
  3550. const envInterval = process.env.CHOKIDAR_INTERVAL;
  3551. if (envInterval) {
  3552. opts.interval = Number.parseInt(envInterval, 10);
  3553. }
  3554. // Editor atomic write normalization enabled by default with fs.watch
  3555. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  3556. if (opts.atomic) this._pendingUnlinks = new Map();
  3557. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  3558. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  3559. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  3560. const awf = opts.awaitWriteFinish;
  3561. if (awf) {
  3562. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  3563. if (!awf.pollInterval) awf.pollInterval = 100;
  3564. this._pendingWrites = new Map();
  3565. }
  3566. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  3567. let readyCalls = 0;
  3568. this._emitReady = () => {
  3569. readyCalls++;
  3570. if (readyCalls >= this._readyCount) {
  3571. this._emitReady = EMPTY_FN;
  3572. this._readyEmitted = true;
  3573. // use process.nextTick to allow time for listener to be bound
  3574. process.nextTick(() => this.emit(EV_READY));
  3575. }
  3576. };
  3577. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  3578. this._readyEmitted = false;
  3579. this.options = opts;
  3580. // Initialize with proper watcher.
  3581. if (opts.useFsEvents) {
  3582. this._fsEventsHandler = new FsEventsHandler(this);
  3583. } else {
  3584. this._nodeFsHandler = new NodeFsHandler(this);
  3585. }
  3586. // You’re frozen when your heart’s not open.
  3587. Object.freeze(opts);
  3588. }
  3589. // Public methods
  3590. /**
  3591. * Adds paths to be watched on an existing FSWatcher instance
  3592. * @param {Path|Array<Path>} paths_
  3593. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  3594. * @param {Boolean=} _internal private; indicates a non-user add
  3595. * @returns {FSWatcher} for chaining
  3596. */
  3597. add(paths_, _origAdd, _internal) {
  3598. const {cwd, disableGlobbing} = this.options;
  3599. this.closed = false;
  3600. let paths = unifyPaths(paths_);
  3601. if (cwd) {
  3602. paths = paths.map((path) => {
  3603. const absPath = getAbsolutePath(path, cwd);
  3604. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  3605. if (disableGlobbing || !isGlob(path)) {
  3606. return absPath;
  3607. }
  3608. return normalizePath(absPath);
  3609. });
  3610. }
  3611. // set aside negated glob strings
  3612. paths = paths.filter((path) => {
  3613. if (path.startsWith(BANG)) {
  3614. this._ignoredPaths.add(path.slice(1));
  3615. return false;
  3616. }
  3617. // if a path is being added that was previously ignored, stop ignoring it
  3618. this._ignoredPaths.delete(path);
  3619. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  3620. // reset the cached userIgnored anymatch fn
  3621. // to make ignoredPaths changes effective
  3622. this._userIgnored = undefined;
  3623. return true;
  3624. });
  3625. if (this.options.useFsEvents && this._fsEventsHandler) {
  3626. if (!this._readyCount) this._readyCount = paths.length;
  3627. if (this.options.persistent) this._readyCount *= 2;
  3628. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  3629. } else {
  3630. if (!this._readyCount) this._readyCount = 0;
  3631. this._readyCount += paths.length;
  3632. Promise.all(
  3633. paths.map(async path => {
  3634. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  3635. if (res) this._emitReady();
  3636. return res;
  3637. })
  3638. ).then(results => {
  3639. if (this.closed) return;
  3640. results.filter(item => item).forEach(item => {
  3641. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  3642. });
  3643. });
  3644. }
  3645. return this;
  3646. }
  3647. /**
  3648. * Close watchers or start ignoring events from specified paths.
  3649. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  3650. * @returns {FSWatcher} for chaining
  3651. */
  3652. unwatch(paths_) {
  3653. if (this.closed) return this;
  3654. const paths = unifyPaths(paths_);
  3655. const {cwd} = this.options;
  3656. paths.forEach((path) => {
  3657. // convert to absolute path unless relative path already matches
  3658. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  3659. if (cwd) path = sysPath.join(cwd, path);
  3660. path = sysPath.resolve(path);
  3661. }
  3662. this._closePath(path);
  3663. this._ignoredPaths.add(path);
  3664. if (this._watched.has(path)) {
  3665. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  3666. }
  3667. // reset the cached userIgnored anymatch fn
  3668. // to make ignoredPaths changes effective
  3669. this._userIgnored = undefined;
  3670. });
  3671. return this;
  3672. }
  3673. /**
  3674. * Close watchers and remove all listeners from watched paths.
  3675. * @returns {Promise<void>}.
  3676. */
  3677. close() {
  3678. if (this.closed) return this._closePromise;
  3679. this.closed = true;
  3680. // Memory management.
  3681. this.removeAllListeners();
  3682. const closers = [];
  3683. this._closers.forEach(closerList => closerList.forEach(closer => {
  3684. const promise = closer();
  3685. if (promise instanceof Promise) closers.push(promise);
  3686. }));
  3687. this._streams.forEach(stream => stream.destroy());
  3688. this._userIgnored = undefined;
  3689. this._readyCount = 0;
  3690. this._readyEmitted = false;
  3691. this._watched.forEach(dirent => dirent.dispose());
  3692. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  3693. this[`_${key}`].clear();
  3694. });
  3695. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  3696. return this._closePromise;
  3697. }
  3698. /**
  3699. * Expose list of watched paths
  3700. * @returns {Object} for chaining
  3701. */
  3702. getWatched() {
  3703. const watchList = {};
  3704. this._watched.forEach((entry, dir) => {
  3705. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  3706. watchList[key || ONE_DOT] = entry.getChildren().sort();
  3707. });
  3708. return watchList;
  3709. }
  3710. emitWithAll(event, args) {
  3711. this.emit(...args);
  3712. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  3713. }
  3714. // Common helpers
  3715. // --------------
  3716. /**
  3717. * Normalize and emit events.
  3718. * Calling _emit DOES NOT MEAN emit() would be called!
  3719. * @param {EventName} event Type of event
  3720. * @param {Path} path File or directory path
  3721. * @param {*=} val1 arguments to be passed with event
  3722. * @param {*=} val2
  3723. * @param {*=} val3
  3724. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  3725. */
  3726. async _emit(event, path, val1, val2, val3) {
  3727. if (this.closed) return;
  3728. const opts = this.options;
  3729. if (isWindows) path = sysPath.normalize(path);
  3730. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  3731. /** @type Array<any> */
  3732. const args = [event, path];
  3733. if (val3 !== undefined) args.push(val1, val2, val3);
  3734. else if (val2 !== undefined) args.push(val1, val2);
  3735. else if (val1 !== undefined) args.push(val1);
  3736. const awf = opts.awaitWriteFinish;
  3737. let pw;
  3738. if (awf && (pw = this._pendingWrites.get(path))) {
  3739. pw.lastChange = new Date();
  3740. return this;
  3741. }
  3742. if (opts.atomic) {
  3743. if (event === EV_UNLINK) {
  3744. this._pendingUnlinks.set(path, args);
  3745. setTimeout(() => {
  3746. this._pendingUnlinks.forEach((entry, path) => {
  3747. this.emit(...entry);
  3748. this.emit(EV_ALL, ...entry);
  3749. this._pendingUnlinks.delete(path);
  3750. });
  3751. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  3752. return this;
  3753. }
  3754. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  3755. event = args[0] = EV_CHANGE;
  3756. this._pendingUnlinks.delete(path);
  3757. }
  3758. }
  3759. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  3760. const awfEmit = (err, stats) => {
  3761. if (err) {
  3762. event = args[0] = EV_ERROR;
  3763. args[1] = err;
  3764. this.emitWithAll(event, args);
  3765. } else if (stats) {
  3766. // if stats doesn't exist the file must have been deleted
  3767. if (args.length > 2) {
  3768. args[2] = stats;
  3769. } else {
  3770. args.push(stats);
  3771. }
  3772. this.emitWithAll(event, args);
  3773. }
  3774. };
  3775. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  3776. return this;
  3777. }
  3778. if (event === EV_CHANGE) {
  3779. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  3780. if (isThrottled) return this;
  3781. }
  3782. if (opts.alwaysStat && val1 === undefined &&
  3783. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  3784. ) {
  3785. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  3786. let stats;
  3787. try {
  3788. stats = await stat(fullPath);
  3789. } catch (err) {}
  3790. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  3791. if (!stats || this.closed) return;
  3792. args.push(stats);
  3793. }
  3794. this.emitWithAll(event, args);
  3795. return this;
  3796. }
  3797. /**
  3798. * Common handler for errors
  3799. * @param {Error} error
  3800. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  3801. */
  3802. _handleError(error) {
  3803. const code = error && error.code;
  3804. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  3805. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  3806. ) {
  3807. this.emit(EV_ERROR, error);
  3808. }
  3809. return error || this.closed;
  3810. }
  3811. /**
  3812. * Helper utility for throttling
  3813. * @param {ThrottleType} actionType type being throttled
  3814. * @param {Path} path being acted upon
  3815. * @param {Number} timeout duration of time to suppress duplicate actions
  3816. * @returns {Object|false} tracking object or false if action should be suppressed
  3817. */
  3818. _throttle(actionType, path, timeout) {
  3819. if (!this._throttled.has(actionType)) {
  3820. this._throttled.set(actionType, new Map());
  3821. }
  3822. /** @type {Map<Path, Object>} */
  3823. const action = this._throttled.get(actionType);
  3824. /** @type {Object} */
  3825. const actionPath = action.get(path);
  3826. if (actionPath) {
  3827. actionPath.count++;
  3828. return false;
  3829. }
  3830. let timeoutObject;
  3831. const clear = () => {
  3832. const item = action.get(path);
  3833. const count = item ? item.count : 0;
  3834. action.delete(path);
  3835. clearTimeout(timeoutObject);
  3836. if (item) clearTimeout(item.timeoutObject);
  3837. return count;
  3838. };
  3839. timeoutObject = setTimeout(clear, timeout);
  3840. const thr = {timeoutObject, clear, count: 0};
  3841. action.set(path, thr);
  3842. return thr;
  3843. }
  3844. _incrReadyCount() {
  3845. return this._readyCount++;
  3846. }
  3847. /**
  3848. * Awaits write operation to finish.
  3849. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  3850. * @param {Path} path being acted upon
  3851. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  3852. * @param {EventName} event
  3853. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  3854. */
  3855. _awaitWriteFinish(path, threshold, event, awfEmit) {
  3856. let timeoutHandler;
  3857. let fullPath = path;
  3858. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  3859. fullPath = sysPath.join(this.options.cwd, path);
  3860. }
  3861. const now = new Date();
  3862. const awaitWriteFinish = (prevStat) => {
  3863. fs.stat(fullPath, (err, curStat) => {
  3864. if (err || !this._pendingWrites.has(path)) {
  3865. if (err && err.code !== 'ENOENT') awfEmit(err);
  3866. return;
  3867. }
  3868. const now = Number(new Date());
  3869. if (prevStat && curStat.size !== prevStat.size) {
  3870. this._pendingWrites.get(path).lastChange = now;
  3871. }
  3872. const pw = this._pendingWrites.get(path);
  3873. const df = now - pw.lastChange;
  3874. if (df >= threshold) {
  3875. this._pendingWrites.delete(path);
  3876. awfEmit(undefined, curStat);
  3877. } else {
  3878. timeoutHandler = setTimeout(
  3879. awaitWriteFinish,
  3880. this.options.awaitWriteFinish.pollInterval,
  3881. curStat
  3882. );
  3883. }
  3884. });
  3885. };
  3886. if (!this._pendingWrites.has(path)) {
  3887. this._pendingWrites.set(path, {
  3888. lastChange: now,
  3889. cancelWait: () => {
  3890. this._pendingWrites.delete(path);
  3891. clearTimeout(timeoutHandler);
  3892. return event;
  3893. }
  3894. });
  3895. timeoutHandler = setTimeout(
  3896. awaitWriteFinish,
  3897. this.options.awaitWriteFinish.pollInterval
  3898. );
  3899. }
  3900. }
  3901. _getGlobIgnored() {
  3902. return [...this._ignoredPaths.values()];
  3903. }
  3904. /**
  3905. * Determines whether user has asked to ignore this path.
  3906. * @param {Path} path filepath or dir
  3907. * @param {fs.Stats=} stats result of fs.stat
  3908. * @returns {Boolean}
  3909. */
  3910. _isIgnored(path, stats) {
  3911. if (this.options.atomic && DOT_RE.test(path)) return true;
  3912. if (!this._userIgnored) {
  3913. const {cwd} = this.options;
  3914. const ign = this.options.ignored;
  3915. const ignored = ign && ign.map(normalizeIgnored(cwd));
  3916. const paths = arrify(ignored)
  3917. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  3918. .map((path) => path + SLASH_GLOBSTAR);
  3919. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  3920. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  3921. }
  3922. return this._userIgnored([path, stats]);
  3923. }
  3924. _isntIgnored(path, stat) {
  3925. return !this._isIgnored(path, stat);
  3926. }
  3927. /**
  3928. * Provides a set of common helpers and properties relating to symlink and glob handling.
  3929. * @param {Path} path file, directory, or glob pattern being watched
  3930. * @param {Number=} depth at any depth > 0, this isn't a glob
  3931. * @returns {WatchHelper} object containing helpers for this path
  3932. */
  3933. _getWatchHelpers(path, depth) {
  3934. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  3935. const follow = this.options.followSymlinks;
  3936. return new WatchHelper(path, watchPath, follow, this);
  3937. }
  3938. // Directory helpers
  3939. // -----------------
  3940. /**
  3941. * Provides directory tracking objects
  3942. * @param {String} directory path of the directory
  3943. * @returns {DirEntry} the directory's tracking object
  3944. */
  3945. _getWatchedDir(directory) {
  3946. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  3947. const dir = sysPath.resolve(directory);
  3948. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  3949. return this._watched.get(dir);
  3950. }
  3951. // File helpers
  3952. // ------------
  3953. /**
  3954. * Check for read permissions.
  3955. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  3956. * @param {fs.Stats} stats - object, result of fs_stat
  3957. * @returns {Boolean} indicates whether the file can be read
  3958. */
  3959. _hasReadPermissions(stats) {
  3960. if (this.options.ignorePermissionErrors) return true;
  3961. // stats.mode may be bigint
  3962. const md = stats && Number.parseInt(stats.mode, 10);
  3963. const st = md & 0o777;
  3964. const it = Number.parseInt(st.toString(8)[0], 10);
  3965. return Boolean(4 & it);
  3966. }
  3967. /**
  3968. * Handles emitting unlink events for
  3969. * files and directories, and via recursion, for
  3970. * files and directories within directories that are unlinked
  3971. * @param {String} directory within which the following item is located
  3972. * @param {String} item base path of item/directory
  3973. * @returns {void}
  3974. */
  3975. _remove(directory, item, isDirectory) {
  3976. // if what is being deleted is a directory, get that directory's paths
  3977. // for recursive deleting and cleaning of watched object
  3978. // if it is not a directory, nestedDirectoryChildren will be empty array
  3979. const path = sysPath.join(directory, item);
  3980. const fullPath = sysPath.resolve(path);
  3981. isDirectory = isDirectory != null
  3982. ? isDirectory
  3983. : this._watched.has(path) || this._watched.has(fullPath);
  3984. // prevent duplicate handling in case of arriving here nearly simultaneously
  3985. // via multiple paths (such as _handleFile and _handleDir)
  3986. if (!this._throttle('remove', path, 100)) return;
  3987. // if the only watched file is removed, watch for its return
  3988. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  3989. this.add(directory, item, true);
  3990. }
  3991. // This will create a new entry in the watched object in either case
  3992. // so we got to do the directory check beforehand
  3993. const wp = this._getWatchedDir(path);
  3994. const nestedDirectoryChildren = wp.getChildren();
  3995. // Recursively remove children directories / files.
  3996. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  3997. // Check if item was on the watched list and remove it
  3998. const parent = this._getWatchedDir(directory);
  3999. const wasTracked = parent.has(item);
  4000. parent.remove(item);
  4001. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  4002. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  4003. // but never removed from the map in case the path was deleted.
  4004. // This leads to an incorrect state if the path was recreated:
  4005. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  4006. if (this._symlinkPaths.has(fullPath)) {
  4007. this._symlinkPaths.delete(fullPath);
  4008. }
  4009. // If we wait for this file to be fully written, cancel the wait.
  4010. let relPath = path;
  4011. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  4012. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  4013. const event = this._pendingWrites.get(relPath).cancelWait();
  4014. if (event === EV_ADD) return;
  4015. }
  4016. // The Entry will either be a directory that just got removed
  4017. // or a bogus entry to a file, in either case we have to remove it
  4018. this._watched.delete(path);
  4019. this._watched.delete(fullPath);
  4020. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  4021. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  4022. // Avoid conflicts if we later create another file with the same name
  4023. if (!this.options.useFsEvents) {
  4024. this._closePath(path);
  4025. }
  4026. }
  4027. /**
  4028. * Closes all watchers for a path
  4029. * @param {Path} path
  4030. */
  4031. _closePath(path) {
  4032. this._closeFile(path);
  4033. const dir = sysPath.dirname(path);
  4034. this._getWatchedDir(dir).remove(sysPath.basename(path));
  4035. }
  4036. /**
  4037. * Closes only file-specific watchers
  4038. * @param {Path} path
  4039. */
  4040. _closeFile(path) {
  4041. const closers = this._closers.get(path);
  4042. if (!closers) return;
  4043. closers.forEach(closer => closer());
  4044. this._closers.delete(path);
  4045. }
  4046. /**
  4047. *
  4048. * @param {Path} path
  4049. * @param {Function} closer
  4050. */
  4051. _addPathCloser(path, closer) {
  4052. if (!closer) return;
  4053. let list = this._closers.get(path);
  4054. if (!list) {
  4055. list = [];
  4056. this._closers.set(path, list);
  4057. }
  4058. list.push(closer);
  4059. }
  4060. _readdirp(root, opts) {
  4061. if (this.closed) return;
  4062. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  4063. let stream = readdirp(root, options);
  4064. this._streams.add(stream);
  4065. stream.once(STR_CLOSE, () => {
  4066. stream = undefined;
  4067. });
  4068. stream.once(STR_END, () => {
  4069. if (stream) {
  4070. this._streams.delete(stream);
  4071. stream = undefined;
  4072. }
  4073. });
  4074. return stream;
  4075. }
  4076. }
  4077. // Export FSWatcher class
  4078. chokidar.FSWatcher = FSWatcher;
  4079. /**
  4080. * Instantiates watcher with paths to be tracked.
  4081. * @param {String|Array<String>} paths file/directory paths and/or globs
  4082. * @param {Object=} options chokidar opts
  4083. * @returns an instance of FSWatcher for chaining.
  4084. */
  4085. const watch = (paths, options) => {
  4086. const watcher = new FSWatcher(options);
  4087. watcher.add(paths);
  4088. return watcher;
  4089. };
  4090. chokidar.watch = watch;
  4091. class FileWatcher {
  4092. constructor(task, chokidarOptions) {
  4093. this.transformWatchers = new Map();
  4094. this.chokidarOptions = chokidarOptions;
  4095. this.task = task;
  4096. this.watcher = this.createWatcher(null);
  4097. }
  4098. close() {
  4099. this.watcher.close();
  4100. for (const watcher of this.transformWatchers.values()) {
  4101. watcher.close();
  4102. }
  4103. }
  4104. unwatch(id) {
  4105. this.watcher.unwatch(id);
  4106. const transformWatcher = this.transformWatchers.get(id);
  4107. if (transformWatcher) {
  4108. this.transformWatchers.delete(id);
  4109. transformWatcher.close();
  4110. }
  4111. }
  4112. watch(id, isTransformDependency) {
  4113. var _a;
  4114. if (isTransformDependency) {
  4115. const watcher = (_a = this.transformWatchers.get(id)) !== null && _a !== void 0 ? _a : this.createWatcher(id);
  4116. watcher.add(id);
  4117. this.transformWatchers.set(id, watcher);
  4118. }
  4119. else {
  4120. this.watcher.add(id);
  4121. }
  4122. }
  4123. createWatcher(transformWatcherId) {
  4124. const task = this.task;
  4125. const isLinux = platform() === 'linux';
  4126. const isTransformDependency = transformWatcherId !== null;
  4127. const handleChange = (id, event) => {
  4128. const changedId = transformWatcherId || id;
  4129. if (isLinux) {
  4130. // unwatching and watching fixes an issue with chokidar where on certain systems,
  4131. // a file that was unlinked and immediately recreated would create a change event
  4132. // but then no longer any further events
  4133. watcher.unwatch(changedId);
  4134. watcher.add(changedId);
  4135. }
  4136. task.invalidate(changedId, { event, isTransformDependency });
  4137. };
  4138. const watcher = chokidar
  4139. .watch([], this.chokidarOptions)
  4140. .on('add', id => handleChange(id, 'create'))
  4141. .on('change', id => handleChange(id, 'update'))
  4142. .on('unlink', id => handleChange(id, 'delete'));
  4143. return watcher;
  4144. }
  4145. }
  4146. const eventsRewrites = {
  4147. create: {
  4148. create: 'buggy',
  4149. delete: null,
  4150. update: 'create'
  4151. },
  4152. delete: {
  4153. create: 'update',
  4154. delete: 'buggy',
  4155. update: 'buggy'
  4156. },
  4157. update: {
  4158. create: 'buggy',
  4159. delete: 'delete',
  4160. update: 'update'
  4161. }
  4162. };
  4163. class Watcher {
  4164. constructor(configs, emitter) {
  4165. this.buildDelay = 0;
  4166. this.buildTimeout = null;
  4167. this.invalidatedIds = new Map();
  4168. this.rerun = false;
  4169. this.running = true;
  4170. this.emitter = emitter;
  4171. emitter.close = this.close.bind(this);
  4172. this.tasks = configs.map(config => new Task(this, config));
  4173. this.buildDelay = configs.reduce((buildDelay, { watch }) => watch && typeof watch.buildDelay === 'number'
  4174. ? Math.max(buildDelay, watch.buildDelay)
  4175. : buildDelay, this.buildDelay);
  4176. process$1.nextTick(() => this.run());
  4177. }
  4178. async close() {
  4179. if (this.buildTimeout)
  4180. clearTimeout(this.buildTimeout);
  4181. for (const task of this.tasks) {
  4182. task.close();
  4183. }
  4184. await this.emitter.emitAndAwait('close');
  4185. this.emitter.removeAllListeners();
  4186. }
  4187. invalidate(file) {
  4188. if (file) {
  4189. const prevEvent = this.invalidatedIds.get(file.id);
  4190. const event = prevEvent ? eventsRewrites[prevEvent][file.event] : file.event;
  4191. if (event === 'buggy') {
  4192. //TODO: throws or warn? Currently just ignore, uses new event
  4193. this.invalidatedIds.set(file.id, file.event);
  4194. }
  4195. else if (event === null) {
  4196. this.invalidatedIds.delete(file.id);
  4197. }
  4198. else {
  4199. this.invalidatedIds.set(file.id, event);
  4200. }
  4201. }
  4202. if (this.running) {
  4203. this.rerun = true;
  4204. return;
  4205. }
  4206. if (this.buildTimeout)
  4207. clearTimeout(this.buildTimeout);
  4208. this.buildTimeout = setTimeout(async () => {
  4209. this.buildTimeout = null;
  4210. try {
  4211. await Promise.all([...this.invalidatedIds].map(([id, event]) => this.emitter.emitAndAwait('change', id, { event })));
  4212. this.invalidatedIds.clear();
  4213. this.emitter.emit('restart');
  4214. this.emitter.removeAwaited();
  4215. this.run();
  4216. }
  4217. catch (error) {
  4218. this.invalidatedIds.clear();
  4219. this.emitter.emit('event', {
  4220. code: 'ERROR',
  4221. error,
  4222. result: null
  4223. });
  4224. this.emitter.emit('event', {
  4225. code: 'END'
  4226. });
  4227. }
  4228. }, this.buildDelay);
  4229. }
  4230. async run() {
  4231. this.running = true;
  4232. this.emitter.emit('event', {
  4233. code: 'START'
  4234. });
  4235. for (const task of this.tasks) {
  4236. await task.run();
  4237. }
  4238. this.running = false;
  4239. this.emitter.emit('event', {
  4240. code: 'END'
  4241. });
  4242. if (this.rerun) {
  4243. this.rerun = false;
  4244. this.invalidate();
  4245. }
  4246. }
  4247. }
  4248. class Task {
  4249. constructor(watcher, config) {
  4250. this.cache = { modules: [] };
  4251. this.watchFiles = [];
  4252. this.closed = false;
  4253. this.invalidated = true;
  4254. this.watched = new Set();
  4255. this.watcher = watcher;
  4256. this.skipWrite = Boolean(config.watch && config.watch.skipWrite);
  4257. this.options = mergeOptions(config);
  4258. this.outputs = this.options.output;
  4259. this.outputFiles = this.outputs.map(output => {
  4260. if (output.file || output.dir)
  4261. return resolve(output.file || output.dir);
  4262. return undefined;
  4263. });
  4264. const watchOptions = this.options.watch || {};
  4265. this.filter = createFilter(watchOptions.include, watchOptions.exclude);
  4266. this.fileWatcher = new FileWatcher(this, {
  4267. ...watchOptions.chokidar,
  4268. disableGlobbing: true,
  4269. ignoreInitial: true
  4270. });
  4271. }
  4272. close() {
  4273. this.closed = true;
  4274. this.fileWatcher.close();
  4275. }
  4276. invalidate(id, details) {
  4277. this.invalidated = true;
  4278. if (details.isTransformDependency) {
  4279. for (const module of this.cache.modules) {
  4280. if (!module.transformDependencies.includes(id))
  4281. continue;
  4282. // effective invalidation
  4283. module.originalCode = null;
  4284. }
  4285. }
  4286. this.watcher.invalidate({ event: details.event, id });
  4287. }
  4288. async run() {
  4289. if (!this.invalidated)
  4290. return;
  4291. this.invalidated = false;
  4292. const options = {
  4293. ...this.options,
  4294. cache: this.cache
  4295. };
  4296. const start = Date.now();
  4297. this.watcher.emitter.emit('event', {
  4298. code: 'BUNDLE_START',
  4299. input: this.options.input,
  4300. output: this.outputFiles
  4301. });
  4302. let result = null;
  4303. try {
  4304. result = await rollupInternal(options, this.watcher.emitter);
  4305. if (this.closed) {
  4306. return;
  4307. }
  4308. this.updateWatchedFiles(result);
  4309. this.skipWrite || (await Promise.all(this.outputs.map(output => result.write(output))));
  4310. this.watcher.emitter.emit('event', {
  4311. code: 'BUNDLE_END',
  4312. duration: Date.now() - start,
  4313. input: this.options.input,
  4314. output: this.outputFiles,
  4315. result
  4316. });
  4317. }
  4318. catch (error) {
  4319. if (!this.closed) {
  4320. if (Array.isArray(error.watchFiles)) {
  4321. for (const id of error.watchFiles) {
  4322. this.watchFile(id);
  4323. }
  4324. }
  4325. if (error.id) {
  4326. this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);
  4327. }
  4328. }
  4329. this.watcher.emitter.emit('event', {
  4330. code: 'ERROR',
  4331. error,
  4332. result
  4333. });
  4334. }
  4335. }
  4336. updateWatchedFiles(result) {
  4337. const previouslyWatched = this.watched;
  4338. this.watched = new Set();
  4339. this.watchFiles = result.watchFiles;
  4340. this.cache = result.cache;
  4341. for (const id of this.watchFiles) {
  4342. this.watchFile(id);
  4343. }
  4344. for (const module of this.cache.modules) {
  4345. for (const depId of module.transformDependencies) {
  4346. this.watchFile(depId, true);
  4347. }
  4348. }
  4349. for (const id of previouslyWatched) {
  4350. if (!this.watched.has(id)) {
  4351. this.fileWatcher.unwatch(id);
  4352. }
  4353. }
  4354. }
  4355. watchFile(id, isTransformDependency = false) {
  4356. if (!this.filter(id))
  4357. return;
  4358. this.watched.add(id);
  4359. if (this.outputFiles.some(file => file === id)) {
  4360. throw new Error('Cannot import the generated bundle');
  4361. }
  4362. // this is necessary to ensure that any 'renamed' files
  4363. // continue to be watched following an error
  4364. this.fileWatcher.watch(id, isTransformDependency);
  4365. }
  4366. }
  4367. export { Task, Watcher };