watch.js 128 KB

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