publicUtils.cjs 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555
  1. 'use strict';
  2. var path$3 = require('node:path');
  3. var node_url = require('node:url');
  4. var fs$1 = require('node:fs');
  5. var esbuild = require('esbuild');
  6. var rollup = require('rollup');
  7. var os$1 = require('node:os');
  8. var node_module = require('node:module');
  9. var require$$0 = require('tty');
  10. var require$$1 = require('util');
  11. var require$$0$1 = require('path');
  12. var require$$0$2 = require('crypto');
  13. var fs$2 = require('fs');
  14. var readline = require('node:readline');
  15. var require$$2 = require('os');
  16. const { version: version$2 } = JSON.parse(fs$1.readFileSync(new URL('../../package.json', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))).toString());
  17. const VERSION = version$2;
  18. /**
  19. * Prefix for resolved fs paths, since windows paths may not be valid as URLs.
  20. */
  21. const FS_PREFIX = `/@fs/`;
  22. const VITE_PACKAGE_DIR = path$3.resolve(
  23. // import.meta.url is `dist/node/constants.js` after bundle
  24. node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))), '../../..');
  25. const CLIENT_ENTRY = path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/client.mjs');
  26. path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/env.mjs');
  27. path$3.dirname(CLIENT_ENTRY);
  28. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  29. const intToChar$1 = new Uint8Array(64); // 64 possible chars.
  30. const charToInt$1 = new Uint8Array(128); // z is 122 in ASCII
  31. for (let i = 0; i < chars$1.length; i++) {
  32. const c = chars$1.charCodeAt(i);
  33. intToChar$1[i] = c;
  34. charToInt$1[c] = i;
  35. }
  36. // Matches the scheme of a URL, eg "http://"
  37. var UrlType;
  38. (function (UrlType) {
  39. UrlType[UrlType["Empty"] = 1] = "Empty";
  40. UrlType[UrlType["Hash"] = 2] = "Hash";
  41. UrlType[UrlType["Query"] = 3] = "Query";
  42. UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
  43. UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
  44. UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
  45. UrlType[UrlType["Absolute"] = 7] = "Absolute";
  46. })(UrlType || (UrlType = {}));
  47. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  48. const intToChar = new Uint8Array(64); // 64 possible chars.
  49. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  50. for (let i = 0; i < chars.length; i++) {
  51. const c = chars.charCodeAt(i);
  52. intToChar[i] = c;
  53. charToInt[c] = i;
  54. }
  55. function getDefaultExportFromCjs (x) {
  56. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  57. }
  58. var picocolors = {exports: {}};
  59. let tty = require$$0;
  60. let isColorSupported =
  61. !("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
  62. ("FORCE_COLOR" in process.env ||
  63. process.argv.includes("--color") ||
  64. process.platform === "win32" ||
  65. (tty.isatty(1) && process.env.TERM !== "dumb") ||
  66. "CI" in process.env);
  67. let formatter =
  68. (open, close, replace = open) =>
  69. input => {
  70. let string = "" + input;
  71. let index = string.indexOf(close, open.length);
  72. return ~index
  73. ? open + replaceClose(string, close, replace, index) + close
  74. : open + string + close
  75. };
  76. let replaceClose = (string, close, replace, index) => {
  77. let start = string.substring(0, index) + replace;
  78. let end = string.substring(index + close.length);
  79. let nextIndex = end.indexOf(close);
  80. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  81. };
  82. let createColors = (enabled = isColorSupported) => ({
  83. isColorSupported: enabled,
  84. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  85. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  86. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  87. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  88. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  89. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  90. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  91. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  92. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  93. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  94. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  95. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  96. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  97. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  98. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  99. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  100. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  101. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  102. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  103. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  104. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  105. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  106. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  107. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  108. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  109. });
  110. picocolors.exports = createColors();
  111. picocolors.exports.createColors = createColors;
  112. var picocolorsExports = picocolors.exports;
  113. var colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  114. var src = {exports: {}};
  115. var browser$1 = {exports: {}};
  116. /**
  117. * Helpers.
  118. */
  119. var ms;
  120. var hasRequiredMs;
  121. function requireMs () {
  122. if (hasRequiredMs) return ms;
  123. hasRequiredMs = 1;
  124. var s = 1000;
  125. var m = s * 60;
  126. var h = m * 60;
  127. var d = h * 24;
  128. var w = d * 7;
  129. var y = d * 365.25;
  130. /**
  131. * Parse or format the given `val`.
  132. *
  133. * Options:
  134. *
  135. * - `long` verbose formatting [false]
  136. *
  137. * @param {String|Number} val
  138. * @param {Object} [options]
  139. * @throws {Error} throw an error if val is not a non-empty string or a number
  140. * @return {String|Number}
  141. * @api public
  142. */
  143. ms = function(val, options) {
  144. options = options || {};
  145. var type = typeof val;
  146. if (type === 'string' && val.length > 0) {
  147. return parse(val);
  148. } else if (type === 'number' && isFinite(val)) {
  149. return options.long ? fmtLong(val) : fmtShort(val);
  150. }
  151. throw new Error(
  152. 'val is not a non-empty string or a valid number. val=' +
  153. JSON.stringify(val)
  154. );
  155. };
  156. /**
  157. * Parse the given `str` and return milliseconds.
  158. *
  159. * @param {String} str
  160. * @return {Number}
  161. * @api private
  162. */
  163. function parse(str) {
  164. str = String(str);
  165. if (str.length > 100) {
  166. return;
  167. }
  168. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  169. str
  170. );
  171. if (!match) {
  172. return;
  173. }
  174. var n = parseFloat(match[1]);
  175. var type = (match[2] || 'ms').toLowerCase();
  176. switch (type) {
  177. case 'years':
  178. case 'year':
  179. case 'yrs':
  180. case 'yr':
  181. case 'y':
  182. return n * y;
  183. case 'weeks':
  184. case 'week':
  185. case 'w':
  186. return n * w;
  187. case 'days':
  188. case 'day':
  189. case 'd':
  190. return n * d;
  191. case 'hours':
  192. case 'hour':
  193. case 'hrs':
  194. case 'hr':
  195. case 'h':
  196. return n * h;
  197. case 'minutes':
  198. case 'minute':
  199. case 'mins':
  200. case 'min':
  201. case 'm':
  202. return n * m;
  203. case 'seconds':
  204. case 'second':
  205. case 'secs':
  206. case 'sec':
  207. case 's':
  208. return n * s;
  209. case 'milliseconds':
  210. case 'millisecond':
  211. case 'msecs':
  212. case 'msec':
  213. case 'ms':
  214. return n;
  215. default:
  216. return undefined;
  217. }
  218. }
  219. /**
  220. * Short format for `ms`.
  221. *
  222. * @param {Number} ms
  223. * @return {String}
  224. * @api private
  225. */
  226. function fmtShort(ms) {
  227. var msAbs = Math.abs(ms);
  228. if (msAbs >= d) {
  229. return Math.round(ms / d) + 'd';
  230. }
  231. if (msAbs >= h) {
  232. return Math.round(ms / h) + 'h';
  233. }
  234. if (msAbs >= m) {
  235. return Math.round(ms / m) + 'm';
  236. }
  237. if (msAbs >= s) {
  238. return Math.round(ms / s) + 's';
  239. }
  240. return ms + 'ms';
  241. }
  242. /**
  243. * Long format for `ms`.
  244. *
  245. * @param {Number} ms
  246. * @return {String}
  247. * @api private
  248. */
  249. function fmtLong(ms) {
  250. var msAbs = Math.abs(ms);
  251. if (msAbs >= d) {
  252. return plural(ms, msAbs, d, 'day');
  253. }
  254. if (msAbs >= h) {
  255. return plural(ms, msAbs, h, 'hour');
  256. }
  257. if (msAbs >= m) {
  258. return plural(ms, msAbs, m, 'minute');
  259. }
  260. if (msAbs >= s) {
  261. return plural(ms, msAbs, s, 'second');
  262. }
  263. return ms + ' ms';
  264. }
  265. /**
  266. * Pluralization helper.
  267. */
  268. function plural(ms, msAbs, n, name) {
  269. var isPlural = msAbs >= n * 1.5;
  270. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  271. }
  272. return ms;
  273. }
  274. var common;
  275. var hasRequiredCommon;
  276. function requireCommon () {
  277. if (hasRequiredCommon) return common;
  278. hasRequiredCommon = 1;
  279. /**
  280. * This is the common logic for both the Node.js and web browser
  281. * implementations of `debug()`.
  282. */
  283. function setup(env) {
  284. createDebug.debug = createDebug;
  285. createDebug.default = createDebug;
  286. createDebug.coerce = coerce;
  287. createDebug.disable = disable;
  288. createDebug.enable = enable;
  289. createDebug.enabled = enabled;
  290. createDebug.humanize = requireMs();
  291. createDebug.destroy = destroy;
  292. Object.keys(env).forEach(key => {
  293. createDebug[key] = env[key];
  294. });
  295. /**
  296. * The currently active debug mode names, and names to skip.
  297. */
  298. createDebug.names = [];
  299. createDebug.skips = [];
  300. /**
  301. * Map of special "%n" handling functions, for the debug "format" argument.
  302. *
  303. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  304. */
  305. createDebug.formatters = {};
  306. /**
  307. * Selects a color for a debug namespace
  308. * @param {String} namespace The namespace string for the debug instance to be colored
  309. * @return {Number|String} An ANSI color code for the given namespace
  310. * @api private
  311. */
  312. function selectColor(namespace) {
  313. let hash = 0;
  314. for (let i = 0; i < namespace.length; i++) {
  315. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  316. hash |= 0; // Convert to 32bit integer
  317. }
  318. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  319. }
  320. createDebug.selectColor = selectColor;
  321. /**
  322. * Create a debugger with the given `namespace`.
  323. *
  324. * @param {String} namespace
  325. * @return {Function}
  326. * @api public
  327. */
  328. function createDebug(namespace) {
  329. let prevTime;
  330. let enableOverride = null;
  331. let namespacesCache;
  332. let enabledCache;
  333. function debug(...args) {
  334. // Disabled?
  335. if (!debug.enabled) {
  336. return;
  337. }
  338. const self = debug;
  339. // Set `diff` timestamp
  340. const curr = Number(new Date());
  341. const ms = curr - (prevTime || curr);
  342. self.diff = ms;
  343. self.prev = prevTime;
  344. self.curr = curr;
  345. prevTime = curr;
  346. args[0] = createDebug.coerce(args[0]);
  347. if (typeof args[0] !== 'string') {
  348. // Anything else let's inspect with %O
  349. args.unshift('%O');
  350. }
  351. // Apply any `formatters` transformations
  352. let index = 0;
  353. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  354. // If we encounter an escaped % then don't increase the array index
  355. if (match === '%%') {
  356. return '%';
  357. }
  358. index++;
  359. const formatter = createDebug.formatters[format];
  360. if (typeof formatter === 'function') {
  361. const val = args[index];
  362. match = formatter.call(self, val);
  363. // Now we need to remove `args[index]` since it's inlined in the `format`
  364. args.splice(index, 1);
  365. index--;
  366. }
  367. return match;
  368. });
  369. // Apply env-specific formatting (colors, etc.)
  370. createDebug.formatArgs.call(self, args);
  371. const logFn = self.log || createDebug.log;
  372. logFn.apply(self, args);
  373. }
  374. debug.namespace = namespace;
  375. debug.useColors = createDebug.useColors();
  376. debug.color = createDebug.selectColor(namespace);
  377. debug.extend = extend;
  378. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  379. Object.defineProperty(debug, 'enabled', {
  380. enumerable: true,
  381. configurable: false,
  382. get: () => {
  383. if (enableOverride !== null) {
  384. return enableOverride;
  385. }
  386. if (namespacesCache !== createDebug.namespaces) {
  387. namespacesCache = createDebug.namespaces;
  388. enabledCache = createDebug.enabled(namespace);
  389. }
  390. return enabledCache;
  391. },
  392. set: v => {
  393. enableOverride = v;
  394. }
  395. });
  396. // Env-specific initialization logic for debug instances
  397. if (typeof createDebug.init === 'function') {
  398. createDebug.init(debug);
  399. }
  400. return debug;
  401. }
  402. function extend(namespace, delimiter) {
  403. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  404. newDebug.log = this.log;
  405. return newDebug;
  406. }
  407. /**
  408. * Enables a debug mode by namespaces. This can include modes
  409. * separated by a colon and wildcards.
  410. *
  411. * @param {String} namespaces
  412. * @api public
  413. */
  414. function enable(namespaces) {
  415. createDebug.save(namespaces);
  416. createDebug.namespaces = namespaces;
  417. createDebug.names = [];
  418. createDebug.skips = [];
  419. let i;
  420. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  421. const len = split.length;
  422. for (i = 0; i < len; i++) {
  423. if (!split[i]) {
  424. // ignore empty strings
  425. continue;
  426. }
  427. namespaces = split[i].replace(/\*/g, '.*?');
  428. if (namespaces[0] === '-') {
  429. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  430. } else {
  431. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  432. }
  433. }
  434. }
  435. /**
  436. * Disable debug output.
  437. *
  438. * @return {String} namespaces
  439. * @api public
  440. */
  441. function disable() {
  442. const namespaces = [
  443. ...createDebug.names.map(toNamespace),
  444. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  445. ].join(',');
  446. createDebug.enable('');
  447. return namespaces;
  448. }
  449. /**
  450. * Returns true if the given mode name is enabled, false otherwise.
  451. *
  452. * @param {String} name
  453. * @return {Boolean}
  454. * @api public
  455. */
  456. function enabled(name) {
  457. if (name[name.length - 1] === '*') {
  458. return true;
  459. }
  460. let i;
  461. let len;
  462. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  463. if (createDebug.skips[i].test(name)) {
  464. return false;
  465. }
  466. }
  467. for (i = 0, len = createDebug.names.length; i < len; i++) {
  468. if (createDebug.names[i].test(name)) {
  469. return true;
  470. }
  471. }
  472. return false;
  473. }
  474. /**
  475. * Convert regexp to namespace
  476. *
  477. * @param {RegExp} regxep
  478. * @return {String} namespace
  479. * @api private
  480. */
  481. function toNamespace(regexp) {
  482. return regexp.toString()
  483. .substring(2, regexp.toString().length - 2)
  484. .replace(/\.\*\?$/, '*');
  485. }
  486. /**
  487. * Coerce `val`.
  488. *
  489. * @param {Mixed} val
  490. * @return {Mixed}
  491. * @api private
  492. */
  493. function coerce(val) {
  494. if (val instanceof Error) {
  495. return val.stack || val.message;
  496. }
  497. return val;
  498. }
  499. /**
  500. * XXX DO NOT USE. This is a temporary stub function.
  501. * XXX It WILL be removed in the next major release.
  502. */
  503. function destroy() {
  504. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  505. }
  506. createDebug.enable(createDebug.load());
  507. return createDebug;
  508. }
  509. common = setup;
  510. return common;
  511. }
  512. /* eslint-env browser */
  513. var hasRequiredBrowser;
  514. function requireBrowser () {
  515. if (hasRequiredBrowser) return browser$1.exports;
  516. hasRequiredBrowser = 1;
  517. (function (module, exports) {
  518. /**
  519. * This is the web browser implementation of `debug()`.
  520. */
  521. exports.formatArgs = formatArgs;
  522. exports.save = save;
  523. exports.load = load;
  524. exports.useColors = useColors;
  525. exports.storage = localstorage();
  526. exports.destroy = (() => {
  527. let warned = false;
  528. return () => {
  529. if (!warned) {
  530. warned = true;
  531. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  532. }
  533. };
  534. })();
  535. /**
  536. * Colors.
  537. */
  538. exports.colors = [
  539. '#0000CC',
  540. '#0000FF',
  541. '#0033CC',
  542. '#0033FF',
  543. '#0066CC',
  544. '#0066FF',
  545. '#0099CC',
  546. '#0099FF',
  547. '#00CC00',
  548. '#00CC33',
  549. '#00CC66',
  550. '#00CC99',
  551. '#00CCCC',
  552. '#00CCFF',
  553. '#3300CC',
  554. '#3300FF',
  555. '#3333CC',
  556. '#3333FF',
  557. '#3366CC',
  558. '#3366FF',
  559. '#3399CC',
  560. '#3399FF',
  561. '#33CC00',
  562. '#33CC33',
  563. '#33CC66',
  564. '#33CC99',
  565. '#33CCCC',
  566. '#33CCFF',
  567. '#6600CC',
  568. '#6600FF',
  569. '#6633CC',
  570. '#6633FF',
  571. '#66CC00',
  572. '#66CC33',
  573. '#9900CC',
  574. '#9900FF',
  575. '#9933CC',
  576. '#9933FF',
  577. '#99CC00',
  578. '#99CC33',
  579. '#CC0000',
  580. '#CC0033',
  581. '#CC0066',
  582. '#CC0099',
  583. '#CC00CC',
  584. '#CC00FF',
  585. '#CC3300',
  586. '#CC3333',
  587. '#CC3366',
  588. '#CC3399',
  589. '#CC33CC',
  590. '#CC33FF',
  591. '#CC6600',
  592. '#CC6633',
  593. '#CC9900',
  594. '#CC9933',
  595. '#CCCC00',
  596. '#CCCC33',
  597. '#FF0000',
  598. '#FF0033',
  599. '#FF0066',
  600. '#FF0099',
  601. '#FF00CC',
  602. '#FF00FF',
  603. '#FF3300',
  604. '#FF3333',
  605. '#FF3366',
  606. '#FF3399',
  607. '#FF33CC',
  608. '#FF33FF',
  609. '#FF6600',
  610. '#FF6633',
  611. '#FF9900',
  612. '#FF9933',
  613. '#FFCC00',
  614. '#FFCC33'
  615. ];
  616. /**
  617. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  618. * and the Firebug extension (any Firefox version) are known
  619. * to support "%c" CSS customizations.
  620. *
  621. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  622. */
  623. // eslint-disable-next-line complexity
  624. function useColors() {
  625. // NB: In an Electron preload script, document will be defined but not fully
  626. // initialized. Since we know we're in Chrome, we'll just detect this case
  627. // explicitly
  628. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  629. return true;
  630. }
  631. // Internet Explorer and Edge do not support colors.
  632. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  633. return false;
  634. }
  635. // Is webkit? http://stackoverflow.com/a/16459606/376773
  636. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  637. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  638. // Is firebug? http://stackoverflow.com/a/398120/376773
  639. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  640. // Is firefox >= v31?
  641. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  642. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  643. // Double check webkit in userAgent just in case we are in a worker
  644. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  645. }
  646. /**
  647. * Colorize log arguments if enabled.
  648. *
  649. * @api public
  650. */
  651. function formatArgs(args) {
  652. args[0] = (this.useColors ? '%c' : '') +
  653. this.namespace +
  654. (this.useColors ? ' %c' : ' ') +
  655. args[0] +
  656. (this.useColors ? '%c ' : ' ') +
  657. '+' + module.exports.humanize(this.diff);
  658. if (!this.useColors) {
  659. return;
  660. }
  661. const c = 'color: ' + this.color;
  662. args.splice(1, 0, c, 'color: inherit');
  663. // The final "%c" is somewhat tricky, because there could be other
  664. // arguments passed either before or after the %c, so we need to
  665. // figure out the correct index to insert the CSS into
  666. let index = 0;
  667. let lastC = 0;
  668. args[0].replace(/%[a-zA-Z%]/g, match => {
  669. if (match === '%%') {
  670. return;
  671. }
  672. index++;
  673. if (match === '%c') {
  674. // We only are interested in the *last* %c
  675. // (the user may have provided their own)
  676. lastC = index;
  677. }
  678. });
  679. args.splice(lastC, 0, c);
  680. }
  681. /**
  682. * Invokes `console.debug()` when available.
  683. * No-op when `console.debug` is not a "function".
  684. * If `console.debug` is not available, falls back
  685. * to `console.log`.
  686. *
  687. * @api public
  688. */
  689. exports.log = console.debug || console.log || (() => {});
  690. /**
  691. * Save `namespaces`.
  692. *
  693. * @param {String} namespaces
  694. * @api private
  695. */
  696. function save(namespaces) {
  697. try {
  698. if (namespaces) {
  699. exports.storage.setItem('debug', namespaces);
  700. } else {
  701. exports.storage.removeItem('debug');
  702. }
  703. } catch (error) {
  704. // Swallow
  705. // XXX (@Qix-) should we be logging these?
  706. }
  707. }
  708. /**
  709. * Load `namespaces`.
  710. *
  711. * @return {String} returns the previously persisted debug modes
  712. * @api private
  713. */
  714. function load() {
  715. let r;
  716. try {
  717. r = exports.storage.getItem('debug');
  718. } catch (error) {
  719. // Swallow
  720. // XXX (@Qix-) should we be logging these?
  721. }
  722. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  723. if (!r && typeof process !== 'undefined' && 'env' in process) {
  724. r = process.env.DEBUG;
  725. }
  726. return r;
  727. }
  728. /**
  729. * Localstorage attempts to return the localstorage.
  730. *
  731. * This is necessary because safari throws
  732. * when a user disables cookies/localstorage
  733. * and you attempt to access it.
  734. *
  735. * @return {LocalStorage}
  736. * @api private
  737. */
  738. function localstorage() {
  739. try {
  740. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  741. // The Browser also has localStorage in the global context.
  742. return localStorage;
  743. } catch (error) {
  744. // Swallow
  745. // XXX (@Qix-) should we be logging these?
  746. }
  747. }
  748. module.exports = requireCommon()(exports);
  749. const {formatters} = module.exports;
  750. /**
  751. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  752. */
  753. formatters.j = function (v) {
  754. try {
  755. return JSON.stringify(v);
  756. } catch (error) {
  757. return '[UnexpectedJSONParseError]: ' + error.message;
  758. }
  759. };
  760. } (browser$1, browser$1.exports));
  761. return browser$1.exports;
  762. }
  763. var node = {exports: {}};
  764. /**
  765. * Module dependencies.
  766. */
  767. var hasRequiredNode;
  768. function requireNode () {
  769. if (hasRequiredNode) return node.exports;
  770. hasRequiredNode = 1;
  771. (function (module, exports) {
  772. const tty = require$$0;
  773. const util = require$$1;
  774. /**
  775. * This is the Node.js implementation of `debug()`.
  776. */
  777. exports.init = init;
  778. exports.log = log;
  779. exports.formatArgs = formatArgs;
  780. exports.save = save;
  781. exports.load = load;
  782. exports.useColors = useColors;
  783. exports.destroy = util.deprecate(
  784. () => {},
  785. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  786. );
  787. /**
  788. * Colors.
  789. */
  790. exports.colors = [6, 2, 3, 4, 5, 1];
  791. try {
  792. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  793. // eslint-disable-next-line import/no-extraneous-dependencies
  794. const supportsColor = require('supports-color');
  795. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  796. exports.colors = [
  797. 20,
  798. 21,
  799. 26,
  800. 27,
  801. 32,
  802. 33,
  803. 38,
  804. 39,
  805. 40,
  806. 41,
  807. 42,
  808. 43,
  809. 44,
  810. 45,
  811. 56,
  812. 57,
  813. 62,
  814. 63,
  815. 68,
  816. 69,
  817. 74,
  818. 75,
  819. 76,
  820. 77,
  821. 78,
  822. 79,
  823. 80,
  824. 81,
  825. 92,
  826. 93,
  827. 98,
  828. 99,
  829. 112,
  830. 113,
  831. 128,
  832. 129,
  833. 134,
  834. 135,
  835. 148,
  836. 149,
  837. 160,
  838. 161,
  839. 162,
  840. 163,
  841. 164,
  842. 165,
  843. 166,
  844. 167,
  845. 168,
  846. 169,
  847. 170,
  848. 171,
  849. 172,
  850. 173,
  851. 178,
  852. 179,
  853. 184,
  854. 185,
  855. 196,
  856. 197,
  857. 198,
  858. 199,
  859. 200,
  860. 201,
  861. 202,
  862. 203,
  863. 204,
  864. 205,
  865. 206,
  866. 207,
  867. 208,
  868. 209,
  869. 214,
  870. 215,
  871. 220,
  872. 221
  873. ];
  874. }
  875. } catch (error) {
  876. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  877. }
  878. /**
  879. * Build up the default `inspectOpts` object from the environment variables.
  880. *
  881. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  882. */
  883. exports.inspectOpts = Object.keys(process.env).filter(key => {
  884. return /^debug_/i.test(key);
  885. }).reduce((obj, key) => {
  886. // Camel-case
  887. const prop = key
  888. .substring(6)
  889. .toLowerCase()
  890. .replace(/_([a-z])/g, (_, k) => {
  891. return k.toUpperCase();
  892. });
  893. // Coerce string value into JS value
  894. let val = process.env[key];
  895. if (/^(yes|on|true|enabled)$/i.test(val)) {
  896. val = true;
  897. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  898. val = false;
  899. } else if (val === 'null') {
  900. val = null;
  901. } else {
  902. val = Number(val);
  903. }
  904. obj[prop] = val;
  905. return obj;
  906. }, {});
  907. /**
  908. * Is stdout a TTY? Colored output is enabled when `true`.
  909. */
  910. function useColors() {
  911. return 'colors' in exports.inspectOpts ?
  912. Boolean(exports.inspectOpts.colors) :
  913. tty.isatty(process.stderr.fd);
  914. }
  915. /**
  916. * Adds ANSI color escape codes if enabled.
  917. *
  918. * @api public
  919. */
  920. function formatArgs(args) {
  921. const {namespace: name, useColors} = this;
  922. if (useColors) {
  923. const c = this.color;
  924. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  925. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  926. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  927. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  928. } else {
  929. args[0] = getDate() + name + ' ' + args[0];
  930. }
  931. }
  932. function getDate() {
  933. if (exports.inspectOpts.hideDate) {
  934. return '';
  935. }
  936. return new Date().toISOString() + ' ';
  937. }
  938. /**
  939. * Invokes `util.format()` with the specified arguments and writes to stderr.
  940. */
  941. function log(...args) {
  942. return process.stderr.write(util.format(...args) + '\n');
  943. }
  944. /**
  945. * Save `namespaces`.
  946. *
  947. * @param {String} namespaces
  948. * @api private
  949. */
  950. function save(namespaces) {
  951. if (namespaces) {
  952. process.env.DEBUG = namespaces;
  953. } else {
  954. // If you set a process.env field to null or undefined, it gets cast to the
  955. // string 'null' or 'undefined'. Just delete instead.
  956. delete process.env.DEBUG;
  957. }
  958. }
  959. /**
  960. * Load `namespaces`.
  961. *
  962. * @return {String} returns the previously persisted debug modes
  963. * @api private
  964. */
  965. function load() {
  966. return process.env.DEBUG;
  967. }
  968. /**
  969. * Init logic for `debug` instances.
  970. *
  971. * Create a new `inspectOpts` object in case `useColors` is set
  972. * differently for a particular `debug` instance.
  973. */
  974. function init(debug) {
  975. debug.inspectOpts = {};
  976. const keys = Object.keys(exports.inspectOpts);
  977. for (let i = 0; i < keys.length; i++) {
  978. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  979. }
  980. }
  981. module.exports = requireCommon()(exports);
  982. const {formatters} = module.exports;
  983. /**
  984. * Map %o to `util.inspect()`, all on a single line.
  985. */
  986. formatters.o = function (v) {
  987. this.inspectOpts.colors = this.useColors;
  988. return util.inspect(v, this.inspectOpts)
  989. .split('\n')
  990. .map(str => str.trim())
  991. .join(' ');
  992. };
  993. /**
  994. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  995. */
  996. formatters.O = function (v) {
  997. this.inspectOpts.colors = this.useColors;
  998. return util.inspect(v, this.inspectOpts);
  999. };
  1000. } (node, node.exports));
  1001. return node.exports;
  1002. }
  1003. /**
  1004. * Detect Electron renderer / nwjs process, which is node, but we should
  1005. * treat as a browser.
  1006. */
  1007. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  1008. src.exports = requireBrowser();
  1009. } else {
  1010. src.exports = requireNode();
  1011. }
  1012. var srcExports = src.exports;
  1013. var debug$1 = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
  1014. var utils$3 = {};
  1015. const path$2 = require$$0$1;
  1016. const WIN_SLASH = '\\\\/';
  1017. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  1018. /**
  1019. * Posix glob regex
  1020. */
  1021. const DOT_LITERAL = '\\.';
  1022. const PLUS_LITERAL = '\\+';
  1023. const QMARK_LITERAL = '\\?';
  1024. const SLASH_LITERAL = '\\/';
  1025. const ONE_CHAR = '(?=.)';
  1026. const QMARK = '[^/]';
  1027. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  1028. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  1029. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  1030. const NO_DOT = `(?!${DOT_LITERAL})`;
  1031. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  1032. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  1033. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  1034. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  1035. const STAR = `${QMARK}*?`;
  1036. const POSIX_CHARS = {
  1037. DOT_LITERAL,
  1038. PLUS_LITERAL,
  1039. QMARK_LITERAL,
  1040. SLASH_LITERAL,
  1041. ONE_CHAR,
  1042. QMARK,
  1043. END_ANCHOR,
  1044. DOTS_SLASH,
  1045. NO_DOT,
  1046. NO_DOTS,
  1047. NO_DOT_SLASH,
  1048. NO_DOTS_SLASH,
  1049. QMARK_NO_DOT,
  1050. STAR,
  1051. START_ANCHOR
  1052. };
  1053. /**
  1054. * Windows glob regex
  1055. */
  1056. const WINDOWS_CHARS = {
  1057. ...POSIX_CHARS,
  1058. SLASH_LITERAL: `[${WIN_SLASH}]`,
  1059. QMARK: WIN_NO_SLASH,
  1060. STAR: `${WIN_NO_SLASH}*?`,
  1061. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  1062. NO_DOT: `(?!${DOT_LITERAL})`,
  1063. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1064. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  1065. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1066. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  1067. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  1068. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  1069. };
  1070. /**
  1071. * POSIX Bracket Regex
  1072. */
  1073. const POSIX_REGEX_SOURCE$1 = {
  1074. alnum: 'a-zA-Z0-9',
  1075. alpha: 'a-zA-Z',
  1076. ascii: '\\x00-\\x7F',
  1077. blank: ' \\t',
  1078. cntrl: '\\x00-\\x1F\\x7F',
  1079. digit: '0-9',
  1080. graph: '\\x21-\\x7E',
  1081. lower: 'a-z',
  1082. print: '\\x20-\\x7E ',
  1083. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1084. space: ' \\t\\r\\n\\v\\f',
  1085. upper: 'A-Z',
  1086. word: 'A-Za-z0-9_',
  1087. xdigit: 'A-Fa-f0-9'
  1088. };
  1089. var constants$2 = {
  1090. MAX_LENGTH: 1024 * 64,
  1091. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  1092. // regular expressions
  1093. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1094. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1095. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1096. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1097. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1098. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1099. // Replace globs with equivalent patterns to reduce parsing time.
  1100. REPLACEMENTS: {
  1101. '***': '*',
  1102. '**/**': '**',
  1103. '**/**/**': '**'
  1104. },
  1105. // Digits
  1106. CHAR_0: 48, /* 0 */
  1107. CHAR_9: 57, /* 9 */
  1108. // Alphabet chars.
  1109. CHAR_UPPERCASE_A: 65, /* A */
  1110. CHAR_LOWERCASE_A: 97, /* a */
  1111. CHAR_UPPERCASE_Z: 90, /* Z */
  1112. CHAR_LOWERCASE_Z: 122, /* z */
  1113. CHAR_LEFT_PARENTHESES: 40, /* ( */
  1114. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  1115. CHAR_ASTERISK: 42, /* * */
  1116. // Non-alphabetic chars.
  1117. CHAR_AMPERSAND: 38, /* & */
  1118. CHAR_AT: 64, /* @ */
  1119. CHAR_BACKWARD_SLASH: 92, /* \ */
  1120. CHAR_CARRIAGE_RETURN: 13, /* \r */
  1121. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  1122. CHAR_COLON: 58, /* : */
  1123. CHAR_COMMA: 44, /* , */
  1124. CHAR_DOT: 46, /* . */
  1125. CHAR_DOUBLE_QUOTE: 34, /* " */
  1126. CHAR_EQUAL: 61, /* = */
  1127. CHAR_EXCLAMATION_MARK: 33, /* ! */
  1128. CHAR_FORM_FEED: 12, /* \f */
  1129. CHAR_FORWARD_SLASH: 47, /* / */
  1130. CHAR_GRAVE_ACCENT: 96, /* ` */
  1131. CHAR_HASH: 35, /* # */
  1132. CHAR_HYPHEN_MINUS: 45, /* - */
  1133. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  1134. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  1135. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  1136. CHAR_LINE_FEED: 10, /* \n */
  1137. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  1138. CHAR_PERCENT: 37, /* % */
  1139. CHAR_PLUS: 43, /* + */
  1140. CHAR_QUESTION_MARK: 63, /* ? */
  1141. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  1142. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  1143. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  1144. CHAR_SEMICOLON: 59, /* ; */
  1145. CHAR_SINGLE_QUOTE: 39, /* ' */
  1146. CHAR_SPACE: 32, /* */
  1147. CHAR_TAB: 9, /* \t */
  1148. CHAR_UNDERSCORE: 95, /* _ */
  1149. CHAR_VERTICAL_LINE: 124, /* | */
  1150. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  1151. SEP: path$2.sep,
  1152. /**
  1153. * Create EXTGLOB_CHARS
  1154. */
  1155. extglobChars(chars) {
  1156. return {
  1157. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1158. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1159. '+': { type: 'plus', open: '(?:', close: ')+' },
  1160. '*': { type: 'star', open: '(?:', close: ')*' },
  1161. '@': { type: 'at', open: '(?:', close: ')' }
  1162. };
  1163. },
  1164. /**
  1165. * Create GLOB_CHARS
  1166. */
  1167. globChars(win32) {
  1168. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1169. }
  1170. };
  1171. (function (exports) {
  1172. const path = require$$0$1;
  1173. const win32 = process.platform === 'win32';
  1174. const {
  1175. REGEX_BACKSLASH,
  1176. REGEX_REMOVE_BACKSLASH,
  1177. REGEX_SPECIAL_CHARS,
  1178. REGEX_SPECIAL_CHARS_GLOBAL
  1179. } = constants$2;
  1180. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1181. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1182. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  1183. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1184. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  1185. exports.removeBackslashes = str => {
  1186. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1187. return match === '\\' ? '' : match;
  1188. });
  1189. };
  1190. exports.supportsLookbehinds = () => {
  1191. const segs = process.version.slice(1).split('.').map(Number);
  1192. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  1193. return true;
  1194. }
  1195. return false;
  1196. };
  1197. exports.isWindows = options => {
  1198. if (options && typeof options.windows === 'boolean') {
  1199. return options.windows;
  1200. }
  1201. return win32 === true || path.sep === '\\';
  1202. };
  1203. exports.escapeLast = (input, char, lastIdx) => {
  1204. const idx = input.lastIndexOf(char, lastIdx);
  1205. if (idx === -1) return input;
  1206. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  1207. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  1208. };
  1209. exports.removePrefix = (input, state = {}) => {
  1210. let output = input;
  1211. if (output.startsWith('./')) {
  1212. output = output.slice(2);
  1213. state.prefix = './';
  1214. }
  1215. return output;
  1216. };
  1217. exports.wrapOutput = (input, state = {}, options = {}) => {
  1218. const prepend = options.contains ? '' : '^';
  1219. const append = options.contains ? '' : '$';
  1220. let output = `${prepend}(?:${input})${append}`;
  1221. if (state.negated === true) {
  1222. output = `(?:^(?!${output}).*$)`;
  1223. }
  1224. return output;
  1225. };
  1226. } (utils$3));
  1227. const utils$2 = utils$3;
  1228. const {
  1229. CHAR_ASTERISK, /* * */
  1230. CHAR_AT, /* @ */
  1231. CHAR_BACKWARD_SLASH, /* \ */
  1232. CHAR_COMMA, /* , */
  1233. CHAR_DOT, /* . */
  1234. CHAR_EXCLAMATION_MARK, /* ! */
  1235. CHAR_FORWARD_SLASH, /* / */
  1236. CHAR_LEFT_CURLY_BRACE, /* { */
  1237. CHAR_LEFT_PARENTHESES, /* ( */
  1238. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1239. CHAR_PLUS, /* + */
  1240. CHAR_QUESTION_MARK, /* ? */
  1241. CHAR_RIGHT_CURLY_BRACE, /* } */
  1242. CHAR_RIGHT_PARENTHESES, /* ) */
  1243. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  1244. } = constants$2;
  1245. const isPathSeparator = code => {
  1246. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1247. };
  1248. const depth = token => {
  1249. if (token.isPrefix !== true) {
  1250. token.depth = token.isGlobstar ? Infinity : 1;
  1251. }
  1252. };
  1253. /**
  1254. * Quickly scans a glob pattern and returns an object with a handful of
  1255. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1256. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  1257. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  1258. *
  1259. * ```js
  1260. * const pm = require('picomatch');
  1261. * console.log(pm.scan('foo/bar/*.js'));
  1262. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1263. * ```
  1264. * @param {String} `str`
  1265. * @param {Object} `options`
  1266. * @return {Object} Returns an object with tokens and regex source string.
  1267. * @api public
  1268. */
  1269. const scan$1 = (input, options) => {
  1270. const opts = options || {};
  1271. const length = input.length - 1;
  1272. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  1273. const slashes = [];
  1274. const tokens = [];
  1275. const parts = [];
  1276. let str = input;
  1277. let index = -1;
  1278. let start = 0;
  1279. let lastIndex = 0;
  1280. let isBrace = false;
  1281. let isBracket = false;
  1282. let isGlob = false;
  1283. let isExtglob = false;
  1284. let isGlobstar = false;
  1285. let braceEscaped = false;
  1286. let backslashes = false;
  1287. let negated = false;
  1288. let negatedExtglob = false;
  1289. let finished = false;
  1290. let braces = 0;
  1291. let prev;
  1292. let code;
  1293. let token = { value: '', depth: 0, isGlob: false };
  1294. const eos = () => index >= length;
  1295. const peek = () => str.charCodeAt(index + 1);
  1296. const advance = () => {
  1297. prev = code;
  1298. return str.charCodeAt(++index);
  1299. };
  1300. while (index < length) {
  1301. code = advance();
  1302. let next;
  1303. if (code === CHAR_BACKWARD_SLASH) {
  1304. backslashes = token.backslashes = true;
  1305. code = advance();
  1306. if (code === CHAR_LEFT_CURLY_BRACE) {
  1307. braceEscaped = true;
  1308. }
  1309. continue;
  1310. }
  1311. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  1312. braces++;
  1313. while (eos() !== true && (code = advance())) {
  1314. if (code === CHAR_BACKWARD_SLASH) {
  1315. backslashes = token.backslashes = true;
  1316. advance();
  1317. continue;
  1318. }
  1319. if (code === CHAR_LEFT_CURLY_BRACE) {
  1320. braces++;
  1321. continue;
  1322. }
  1323. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  1324. isBrace = token.isBrace = true;
  1325. isGlob = token.isGlob = true;
  1326. finished = true;
  1327. if (scanToEnd === true) {
  1328. continue;
  1329. }
  1330. break;
  1331. }
  1332. if (braceEscaped !== true && code === CHAR_COMMA) {
  1333. isBrace = token.isBrace = true;
  1334. isGlob = token.isGlob = true;
  1335. finished = true;
  1336. if (scanToEnd === true) {
  1337. continue;
  1338. }
  1339. break;
  1340. }
  1341. if (code === CHAR_RIGHT_CURLY_BRACE) {
  1342. braces--;
  1343. if (braces === 0) {
  1344. braceEscaped = false;
  1345. isBrace = token.isBrace = true;
  1346. finished = true;
  1347. break;
  1348. }
  1349. }
  1350. }
  1351. if (scanToEnd === true) {
  1352. continue;
  1353. }
  1354. break;
  1355. }
  1356. if (code === CHAR_FORWARD_SLASH) {
  1357. slashes.push(index);
  1358. tokens.push(token);
  1359. token = { value: '', depth: 0, isGlob: false };
  1360. if (finished === true) continue;
  1361. if (prev === CHAR_DOT && index === (start + 1)) {
  1362. start += 2;
  1363. continue;
  1364. }
  1365. lastIndex = index + 1;
  1366. continue;
  1367. }
  1368. if (opts.noext !== true) {
  1369. const isExtglobChar = code === CHAR_PLUS
  1370. || code === CHAR_AT
  1371. || code === CHAR_ASTERISK
  1372. || code === CHAR_QUESTION_MARK
  1373. || code === CHAR_EXCLAMATION_MARK;
  1374. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  1375. isGlob = token.isGlob = true;
  1376. isExtglob = token.isExtglob = true;
  1377. finished = true;
  1378. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  1379. negatedExtglob = true;
  1380. }
  1381. if (scanToEnd === true) {
  1382. while (eos() !== true && (code = advance())) {
  1383. if (code === CHAR_BACKWARD_SLASH) {
  1384. backslashes = token.backslashes = true;
  1385. code = advance();
  1386. continue;
  1387. }
  1388. if (code === CHAR_RIGHT_PARENTHESES) {
  1389. isGlob = token.isGlob = true;
  1390. finished = true;
  1391. break;
  1392. }
  1393. }
  1394. continue;
  1395. }
  1396. break;
  1397. }
  1398. }
  1399. if (code === CHAR_ASTERISK) {
  1400. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  1401. isGlob = token.isGlob = true;
  1402. finished = true;
  1403. if (scanToEnd === true) {
  1404. continue;
  1405. }
  1406. break;
  1407. }
  1408. if (code === CHAR_QUESTION_MARK) {
  1409. isGlob = token.isGlob = true;
  1410. finished = true;
  1411. if (scanToEnd === true) {
  1412. continue;
  1413. }
  1414. break;
  1415. }
  1416. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  1417. while (eos() !== true && (next = advance())) {
  1418. if (next === CHAR_BACKWARD_SLASH) {
  1419. backslashes = token.backslashes = true;
  1420. advance();
  1421. continue;
  1422. }
  1423. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1424. isBracket = token.isBracket = true;
  1425. isGlob = token.isGlob = true;
  1426. finished = true;
  1427. break;
  1428. }
  1429. }
  1430. if (scanToEnd === true) {
  1431. continue;
  1432. }
  1433. break;
  1434. }
  1435. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  1436. negated = token.negated = true;
  1437. start++;
  1438. continue;
  1439. }
  1440. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  1441. isGlob = token.isGlob = true;
  1442. if (scanToEnd === true) {
  1443. while (eos() !== true && (code = advance())) {
  1444. if (code === CHAR_LEFT_PARENTHESES) {
  1445. backslashes = token.backslashes = true;
  1446. code = advance();
  1447. continue;
  1448. }
  1449. if (code === CHAR_RIGHT_PARENTHESES) {
  1450. finished = true;
  1451. break;
  1452. }
  1453. }
  1454. continue;
  1455. }
  1456. break;
  1457. }
  1458. if (isGlob === true) {
  1459. finished = true;
  1460. if (scanToEnd === true) {
  1461. continue;
  1462. }
  1463. break;
  1464. }
  1465. }
  1466. if (opts.noext === true) {
  1467. isExtglob = false;
  1468. isGlob = false;
  1469. }
  1470. let base = str;
  1471. let prefix = '';
  1472. let glob = '';
  1473. if (start > 0) {
  1474. prefix = str.slice(0, start);
  1475. str = str.slice(start);
  1476. lastIndex -= start;
  1477. }
  1478. if (base && isGlob === true && lastIndex > 0) {
  1479. base = str.slice(0, lastIndex);
  1480. glob = str.slice(lastIndex);
  1481. } else if (isGlob === true) {
  1482. base = '';
  1483. glob = str;
  1484. } else {
  1485. base = str;
  1486. }
  1487. if (base && base !== '' && base !== '/' && base !== str) {
  1488. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  1489. base = base.slice(0, -1);
  1490. }
  1491. }
  1492. if (opts.unescape === true) {
  1493. if (glob) glob = utils$2.removeBackslashes(glob);
  1494. if (base && backslashes === true) {
  1495. base = utils$2.removeBackslashes(base);
  1496. }
  1497. }
  1498. const state = {
  1499. prefix,
  1500. input,
  1501. start,
  1502. base,
  1503. glob,
  1504. isBrace,
  1505. isBracket,
  1506. isGlob,
  1507. isExtglob,
  1508. isGlobstar,
  1509. negated,
  1510. negatedExtglob
  1511. };
  1512. if (opts.tokens === true) {
  1513. state.maxDepth = 0;
  1514. if (!isPathSeparator(code)) {
  1515. tokens.push(token);
  1516. }
  1517. state.tokens = tokens;
  1518. }
  1519. if (opts.parts === true || opts.tokens === true) {
  1520. let prevIndex;
  1521. for (let idx = 0; idx < slashes.length; idx++) {
  1522. const n = prevIndex ? prevIndex + 1 : start;
  1523. const i = slashes[idx];
  1524. const value = input.slice(n, i);
  1525. if (opts.tokens) {
  1526. if (idx === 0 && start !== 0) {
  1527. tokens[idx].isPrefix = true;
  1528. tokens[idx].value = prefix;
  1529. } else {
  1530. tokens[idx].value = value;
  1531. }
  1532. depth(tokens[idx]);
  1533. state.maxDepth += tokens[idx].depth;
  1534. }
  1535. if (idx !== 0 || value !== '') {
  1536. parts.push(value);
  1537. }
  1538. prevIndex = i;
  1539. }
  1540. if (prevIndex && prevIndex + 1 < input.length) {
  1541. const value = input.slice(prevIndex + 1);
  1542. parts.push(value);
  1543. if (opts.tokens) {
  1544. tokens[tokens.length - 1].value = value;
  1545. depth(tokens[tokens.length - 1]);
  1546. state.maxDepth += tokens[tokens.length - 1].depth;
  1547. }
  1548. }
  1549. state.slashes = slashes;
  1550. state.parts = parts;
  1551. }
  1552. return state;
  1553. };
  1554. var scan_1 = scan$1;
  1555. const constants$1 = constants$2;
  1556. const utils$1 = utils$3;
  1557. /**
  1558. * Constants
  1559. */
  1560. const {
  1561. MAX_LENGTH,
  1562. POSIX_REGEX_SOURCE,
  1563. REGEX_NON_SPECIAL_CHARS,
  1564. REGEX_SPECIAL_CHARS_BACKREF,
  1565. REPLACEMENTS
  1566. } = constants$1;
  1567. /**
  1568. * Helpers
  1569. */
  1570. const expandRange = (args, options) => {
  1571. if (typeof options.expandRange === 'function') {
  1572. return options.expandRange(...args, options);
  1573. }
  1574. args.sort();
  1575. const value = `[${args.join('-')}]`;
  1576. return value;
  1577. };
  1578. /**
  1579. * Create the message for a syntax error
  1580. */
  1581. const syntaxError = (type, char) => {
  1582. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  1583. };
  1584. /**
  1585. * Parse the given input string.
  1586. * @param {String} input
  1587. * @param {Object} options
  1588. * @return {Object}
  1589. */
  1590. const parse$2 = (input, options) => {
  1591. if (typeof input !== 'string') {
  1592. throw new TypeError('Expected a string');
  1593. }
  1594. input = REPLACEMENTS[input] || input;
  1595. const opts = { ...options };
  1596. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1597. let len = input.length;
  1598. if (len > max) {
  1599. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1600. }
  1601. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  1602. const tokens = [bos];
  1603. const capture = opts.capture ? '' : '?:';
  1604. const win32 = utils$1.isWindows(options);
  1605. // create constants based on platform, for windows or posix
  1606. const PLATFORM_CHARS = constants$1.globChars(win32);
  1607. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  1608. const {
  1609. DOT_LITERAL,
  1610. PLUS_LITERAL,
  1611. SLASH_LITERAL,
  1612. ONE_CHAR,
  1613. DOTS_SLASH,
  1614. NO_DOT,
  1615. NO_DOT_SLASH,
  1616. NO_DOTS_SLASH,
  1617. QMARK,
  1618. QMARK_NO_DOT,
  1619. STAR,
  1620. START_ANCHOR
  1621. } = PLATFORM_CHARS;
  1622. const globstar = opts => {
  1623. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1624. };
  1625. const nodot = opts.dot ? '' : NO_DOT;
  1626. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  1627. let star = opts.bash === true ? globstar(opts) : STAR;
  1628. if (opts.capture) {
  1629. star = `(${star})`;
  1630. }
  1631. // minimatch options support
  1632. if (typeof opts.noext === 'boolean') {
  1633. opts.noextglob = opts.noext;
  1634. }
  1635. const state = {
  1636. input,
  1637. index: -1,
  1638. start: 0,
  1639. dot: opts.dot === true,
  1640. consumed: '',
  1641. output: '',
  1642. prefix: '',
  1643. backtrack: false,
  1644. negated: false,
  1645. brackets: 0,
  1646. braces: 0,
  1647. parens: 0,
  1648. quotes: 0,
  1649. globstar: false,
  1650. tokens
  1651. };
  1652. input = utils$1.removePrefix(input, state);
  1653. len = input.length;
  1654. const extglobs = [];
  1655. const braces = [];
  1656. const stack = [];
  1657. let prev = bos;
  1658. let value;
  1659. /**
  1660. * Tokenizing helpers
  1661. */
  1662. const eos = () => state.index === len - 1;
  1663. const peek = state.peek = (n = 1) => input[state.index + n];
  1664. const advance = state.advance = () => input[++state.index] || '';
  1665. const remaining = () => input.slice(state.index + 1);
  1666. const consume = (value = '', num = 0) => {
  1667. state.consumed += value;
  1668. state.index += num;
  1669. };
  1670. const append = token => {
  1671. state.output += token.output != null ? token.output : token.value;
  1672. consume(token.value);
  1673. };
  1674. const negate = () => {
  1675. let count = 1;
  1676. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1677. advance();
  1678. state.start++;
  1679. count++;
  1680. }
  1681. if (count % 2 === 0) {
  1682. return false;
  1683. }
  1684. state.negated = true;
  1685. state.start++;
  1686. return true;
  1687. };
  1688. const increment = type => {
  1689. state[type]++;
  1690. stack.push(type);
  1691. };
  1692. const decrement = type => {
  1693. state[type]--;
  1694. stack.pop();
  1695. };
  1696. /**
  1697. * Push tokens onto the tokens array. This helper speeds up
  1698. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1699. * and 2) helping us avoid creating extra tokens when consecutive
  1700. * characters are plain text. This improves performance and simplifies
  1701. * lookbehinds.
  1702. */
  1703. const push = tok => {
  1704. if (prev.type === 'globstar') {
  1705. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1706. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1707. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1708. state.output = state.output.slice(0, -prev.output.length);
  1709. prev.type = 'star';
  1710. prev.value = '*';
  1711. prev.output = star;
  1712. state.output += prev.output;
  1713. }
  1714. }
  1715. if (extglobs.length && tok.type !== 'paren') {
  1716. extglobs[extglobs.length - 1].inner += tok.value;
  1717. }
  1718. if (tok.value || tok.output) append(tok);
  1719. if (prev && prev.type === 'text' && tok.type === 'text') {
  1720. prev.value += tok.value;
  1721. prev.output = (prev.output || '') + tok.value;
  1722. return;
  1723. }
  1724. tok.prev = prev;
  1725. tokens.push(tok);
  1726. prev = tok;
  1727. };
  1728. const extglobOpen = (type, value) => {
  1729. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1730. token.prev = prev;
  1731. token.parens = state.parens;
  1732. token.output = state.output;
  1733. const output = (opts.capture ? '(' : '') + token.open;
  1734. increment('parens');
  1735. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1736. push({ type: 'paren', extglob: true, value: advance(), output });
  1737. extglobs.push(token);
  1738. };
  1739. const extglobClose = token => {
  1740. let output = token.close + (opts.capture ? ')' : '');
  1741. let rest;
  1742. if (token.type === 'negate') {
  1743. let extglobStar = star;
  1744. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1745. extglobStar = globstar(opts);
  1746. }
  1747. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1748. output = token.close = `)$))${extglobStar}`;
  1749. }
  1750. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1751. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1752. // In this case, we need to parse the string and use it in the output of the original pattern.
  1753. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1754. //
  1755. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1756. const expression = parse$2(rest, { ...options, fastpaths: false }).output;
  1757. output = token.close = `)${expression})${extglobStar})`;
  1758. }
  1759. if (token.prev.type === 'bos') {
  1760. state.negatedExtglob = true;
  1761. }
  1762. }
  1763. push({ type: 'paren', extglob: true, value, output });
  1764. decrement('parens');
  1765. };
  1766. /**
  1767. * Fast paths
  1768. */
  1769. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1770. let backslashes = false;
  1771. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1772. if (first === '\\') {
  1773. backslashes = true;
  1774. return m;
  1775. }
  1776. if (first === '?') {
  1777. if (esc) {
  1778. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1779. }
  1780. if (index === 0) {
  1781. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1782. }
  1783. return QMARK.repeat(chars.length);
  1784. }
  1785. if (first === '.') {
  1786. return DOT_LITERAL.repeat(chars.length);
  1787. }
  1788. if (first === '*') {
  1789. if (esc) {
  1790. return esc + first + (rest ? star : '');
  1791. }
  1792. return star;
  1793. }
  1794. return esc ? m : `\\${m}`;
  1795. });
  1796. if (backslashes === true) {
  1797. if (opts.unescape === true) {
  1798. output = output.replace(/\\/g, '');
  1799. } else {
  1800. output = output.replace(/\\+/g, m => {
  1801. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1802. });
  1803. }
  1804. }
  1805. if (output === input && opts.contains === true) {
  1806. state.output = input;
  1807. return state;
  1808. }
  1809. state.output = utils$1.wrapOutput(output, state, options);
  1810. return state;
  1811. }
  1812. /**
  1813. * Tokenize input until we reach end-of-string
  1814. */
  1815. while (!eos()) {
  1816. value = advance();
  1817. if (value === '\u0000') {
  1818. continue;
  1819. }
  1820. /**
  1821. * Escaped characters
  1822. */
  1823. if (value === '\\') {
  1824. const next = peek();
  1825. if (next === '/' && opts.bash !== true) {
  1826. continue;
  1827. }
  1828. if (next === '.' || next === ';') {
  1829. continue;
  1830. }
  1831. if (!next) {
  1832. value += '\\';
  1833. push({ type: 'text', value });
  1834. continue;
  1835. }
  1836. // collapse slashes to reduce potential for exploits
  1837. const match = /^\\+/.exec(remaining());
  1838. let slashes = 0;
  1839. if (match && match[0].length > 2) {
  1840. slashes = match[0].length;
  1841. state.index += slashes;
  1842. if (slashes % 2 !== 0) {
  1843. value += '\\';
  1844. }
  1845. }
  1846. if (opts.unescape === true) {
  1847. value = advance();
  1848. } else {
  1849. value += advance();
  1850. }
  1851. if (state.brackets === 0) {
  1852. push({ type: 'text', value });
  1853. continue;
  1854. }
  1855. }
  1856. /**
  1857. * If we're inside a regex character class, continue
  1858. * until we reach the closing bracket.
  1859. */
  1860. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1861. if (opts.posix !== false && value === ':') {
  1862. const inner = prev.value.slice(1);
  1863. if (inner.includes('[')) {
  1864. prev.posix = true;
  1865. if (inner.includes(':')) {
  1866. const idx = prev.value.lastIndexOf('[');
  1867. const pre = prev.value.slice(0, idx);
  1868. const rest = prev.value.slice(idx + 2);
  1869. const posix = POSIX_REGEX_SOURCE[rest];
  1870. if (posix) {
  1871. prev.value = pre + posix;
  1872. state.backtrack = true;
  1873. advance();
  1874. if (!bos.output && tokens.indexOf(prev) === 1) {
  1875. bos.output = ONE_CHAR;
  1876. }
  1877. continue;
  1878. }
  1879. }
  1880. }
  1881. }
  1882. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1883. value = `\\${value}`;
  1884. }
  1885. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1886. value = `\\${value}`;
  1887. }
  1888. if (opts.posix === true && value === '!' && prev.value === '[') {
  1889. value = '^';
  1890. }
  1891. prev.value += value;
  1892. append({ value });
  1893. continue;
  1894. }
  1895. /**
  1896. * If we're inside a quoted string, continue
  1897. * until we reach the closing double quote.
  1898. */
  1899. if (state.quotes === 1 && value !== '"') {
  1900. value = utils$1.escapeRegex(value);
  1901. prev.value += value;
  1902. append({ value });
  1903. continue;
  1904. }
  1905. /**
  1906. * Double quotes
  1907. */
  1908. if (value === '"') {
  1909. state.quotes = state.quotes === 1 ? 0 : 1;
  1910. if (opts.keepQuotes === true) {
  1911. push({ type: 'text', value });
  1912. }
  1913. continue;
  1914. }
  1915. /**
  1916. * Parentheses
  1917. */
  1918. if (value === '(') {
  1919. increment('parens');
  1920. push({ type: 'paren', value });
  1921. continue;
  1922. }
  1923. if (value === ')') {
  1924. if (state.parens === 0 && opts.strictBrackets === true) {
  1925. throw new SyntaxError(syntaxError('opening', '('));
  1926. }
  1927. const extglob = extglobs[extglobs.length - 1];
  1928. if (extglob && state.parens === extglob.parens + 1) {
  1929. extglobClose(extglobs.pop());
  1930. continue;
  1931. }
  1932. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1933. decrement('parens');
  1934. continue;
  1935. }
  1936. /**
  1937. * Square brackets
  1938. */
  1939. if (value === '[') {
  1940. if (opts.nobracket === true || !remaining().includes(']')) {
  1941. if (opts.nobracket !== true && opts.strictBrackets === true) {
  1942. throw new SyntaxError(syntaxError('closing', ']'));
  1943. }
  1944. value = `\\${value}`;
  1945. } else {
  1946. increment('brackets');
  1947. }
  1948. push({ type: 'bracket', value });
  1949. continue;
  1950. }
  1951. if (value === ']') {
  1952. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  1953. push({ type: 'text', value, output: `\\${value}` });
  1954. continue;
  1955. }
  1956. if (state.brackets === 0) {
  1957. if (opts.strictBrackets === true) {
  1958. throw new SyntaxError(syntaxError('opening', '['));
  1959. }
  1960. push({ type: 'text', value, output: `\\${value}` });
  1961. continue;
  1962. }
  1963. decrement('brackets');
  1964. const prevValue = prev.value.slice(1);
  1965. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  1966. value = `/${value}`;
  1967. }
  1968. prev.value += value;
  1969. append({ value });
  1970. // when literal brackets are explicitly disabled
  1971. // assume we should match with a regex character class
  1972. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  1973. continue;
  1974. }
  1975. const escaped = utils$1.escapeRegex(prev.value);
  1976. state.output = state.output.slice(0, -prev.value.length);
  1977. // when literal brackets are explicitly enabled
  1978. // assume we should escape the brackets to match literal characters
  1979. if (opts.literalBrackets === true) {
  1980. state.output += escaped;
  1981. prev.value = escaped;
  1982. continue;
  1983. }
  1984. // when the user specifies nothing, try to match both
  1985. prev.value = `(${capture}${escaped}|${prev.value})`;
  1986. state.output += prev.value;
  1987. continue;
  1988. }
  1989. /**
  1990. * Braces
  1991. */
  1992. if (value === '{' && opts.nobrace !== true) {
  1993. increment('braces');
  1994. const open = {
  1995. type: 'brace',
  1996. value,
  1997. output: '(',
  1998. outputIndex: state.output.length,
  1999. tokensIndex: state.tokens.length
  2000. };
  2001. braces.push(open);
  2002. push(open);
  2003. continue;
  2004. }
  2005. if (value === '}') {
  2006. const brace = braces[braces.length - 1];
  2007. if (opts.nobrace === true || !brace) {
  2008. push({ type: 'text', value, output: value });
  2009. continue;
  2010. }
  2011. let output = ')';
  2012. if (brace.dots === true) {
  2013. const arr = tokens.slice();
  2014. const range = [];
  2015. for (let i = arr.length - 1; i >= 0; i--) {
  2016. tokens.pop();
  2017. if (arr[i].type === 'brace') {
  2018. break;
  2019. }
  2020. if (arr[i].type !== 'dots') {
  2021. range.unshift(arr[i].value);
  2022. }
  2023. }
  2024. output = expandRange(range, opts);
  2025. state.backtrack = true;
  2026. }
  2027. if (brace.comma !== true && brace.dots !== true) {
  2028. const out = state.output.slice(0, brace.outputIndex);
  2029. const toks = state.tokens.slice(brace.tokensIndex);
  2030. brace.value = brace.output = '\\{';
  2031. value = output = '\\}';
  2032. state.output = out;
  2033. for (const t of toks) {
  2034. state.output += (t.output || t.value);
  2035. }
  2036. }
  2037. push({ type: 'brace', value, output });
  2038. decrement('braces');
  2039. braces.pop();
  2040. continue;
  2041. }
  2042. /**
  2043. * Pipes
  2044. */
  2045. if (value === '|') {
  2046. if (extglobs.length > 0) {
  2047. extglobs[extglobs.length - 1].conditions++;
  2048. }
  2049. push({ type: 'text', value });
  2050. continue;
  2051. }
  2052. /**
  2053. * Commas
  2054. */
  2055. if (value === ',') {
  2056. let output = value;
  2057. const brace = braces[braces.length - 1];
  2058. if (brace && stack[stack.length - 1] === 'braces') {
  2059. brace.comma = true;
  2060. output = '|';
  2061. }
  2062. push({ type: 'comma', value, output });
  2063. continue;
  2064. }
  2065. /**
  2066. * Slashes
  2067. */
  2068. if (value === '/') {
  2069. // if the beginning of the glob is "./", advance the start
  2070. // to the current index, and don't add the "./" characters
  2071. // to the state. This greatly simplifies lookbehinds when
  2072. // checking for BOS characters like "!" and "." (not "./")
  2073. if (prev.type === 'dot' && state.index === state.start + 1) {
  2074. state.start = state.index + 1;
  2075. state.consumed = '';
  2076. state.output = '';
  2077. tokens.pop();
  2078. prev = bos; // reset "prev" to the first token
  2079. continue;
  2080. }
  2081. push({ type: 'slash', value, output: SLASH_LITERAL });
  2082. continue;
  2083. }
  2084. /**
  2085. * Dots
  2086. */
  2087. if (value === '.') {
  2088. if (state.braces > 0 && prev.type === 'dot') {
  2089. if (prev.value === '.') prev.output = DOT_LITERAL;
  2090. const brace = braces[braces.length - 1];
  2091. prev.type = 'dots';
  2092. prev.output += value;
  2093. prev.value += value;
  2094. brace.dots = true;
  2095. continue;
  2096. }
  2097. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2098. push({ type: 'text', value, output: DOT_LITERAL });
  2099. continue;
  2100. }
  2101. push({ type: 'dot', value, output: DOT_LITERAL });
  2102. continue;
  2103. }
  2104. /**
  2105. * Question marks
  2106. */
  2107. if (value === '?') {
  2108. const isGroup = prev && prev.value === '(';
  2109. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2110. extglobOpen('qmark', value);
  2111. continue;
  2112. }
  2113. if (prev && prev.type === 'paren') {
  2114. const next = peek();
  2115. let output = value;
  2116. if (next === '<' && !utils$1.supportsLookbehinds()) {
  2117. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  2118. }
  2119. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  2120. output = `\\${value}`;
  2121. }
  2122. push({ type: 'text', value, output });
  2123. continue;
  2124. }
  2125. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2126. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2127. continue;
  2128. }
  2129. push({ type: 'qmark', value, output: QMARK });
  2130. continue;
  2131. }
  2132. /**
  2133. * Exclamation
  2134. */
  2135. if (value === '!') {
  2136. if (opts.noextglob !== true && peek() === '(') {
  2137. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2138. extglobOpen('negate', value);
  2139. continue;
  2140. }
  2141. }
  2142. if (opts.nonegate !== true && state.index === 0) {
  2143. negate();
  2144. continue;
  2145. }
  2146. }
  2147. /**
  2148. * Plus
  2149. */
  2150. if (value === '+') {
  2151. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2152. extglobOpen('plus', value);
  2153. continue;
  2154. }
  2155. if ((prev && prev.value === '(') || opts.regex === false) {
  2156. push({ type: 'plus', value, output: PLUS_LITERAL });
  2157. continue;
  2158. }
  2159. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  2160. push({ type: 'plus', value });
  2161. continue;
  2162. }
  2163. push({ type: 'plus', value: PLUS_LITERAL });
  2164. continue;
  2165. }
  2166. /**
  2167. * Plain text
  2168. */
  2169. if (value === '@') {
  2170. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2171. push({ type: 'at', extglob: true, value, output: '' });
  2172. continue;
  2173. }
  2174. push({ type: 'text', value });
  2175. continue;
  2176. }
  2177. /**
  2178. * Plain text
  2179. */
  2180. if (value !== '*') {
  2181. if (value === '$' || value === '^') {
  2182. value = `\\${value}`;
  2183. }
  2184. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  2185. if (match) {
  2186. value += match[0];
  2187. state.index += match[0].length;
  2188. }
  2189. push({ type: 'text', value });
  2190. continue;
  2191. }
  2192. /**
  2193. * Stars
  2194. */
  2195. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2196. prev.type = 'star';
  2197. prev.star = true;
  2198. prev.value += value;
  2199. prev.output = star;
  2200. state.backtrack = true;
  2201. state.globstar = true;
  2202. consume(value);
  2203. continue;
  2204. }
  2205. let rest = remaining();
  2206. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  2207. extglobOpen('star', value);
  2208. continue;
  2209. }
  2210. if (prev.type === 'star') {
  2211. if (opts.noglobstar === true) {
  2212. consume(value);
  2213. continue;
  2214. }
  2215. const prior = prev.prev;
  2216. const before = prior.prev;
  2217. const isStart = prior.type === 'slash' || prior.type === 'bos';
  2218. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2219. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  2220. push({ type: 'star', value, output: '' });
  2221. continue;
  2222. }
  2223. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2224. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2225. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2226. push({ type: 'star', value, output: '' });
  2227. continue;
  2228. }
  2229. // strip consecutive `/**/`
  2230. while (rest.slice(0, 3) === '/**') {
  2231. const after = input[state.index + 4];
  2232. if (after && after !== '/') {
  2233. break;
  2234. }
  2235. rest = rest.slice(3);
  2236. consume('/**', 3);
  2237. }
  2238. if (prior.type === 'bos' && eos()) {
  2239. prev.type = 'globstar';
  2240. prev.value += value;
  2241. prev.output = globstar(opts);
  2242. state.output = prev.output;
  2243. state.globstar = true;
  2244. consume(value);
  2245. continue;
  2246. }
  2247. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2248. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2249. prior.output = `(?:${prior.output}`;
  2250. prev.type = 'globstar';
  2251. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  2252. prev.value += value;
  2253. state.globstar = true;
  2254. state.output += prior.output + prev.output;
  2255. consume(value);
  2256. continue;
  2257. }
  2258. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  2259. const end = rest[1] !== void 0 ? '|$' : '';
  2260. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2261. prior.output = `(?:${prior.output}`;
  2262. prev.type = 'globstar';
  2263. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2264. prev.value += value;
  2265. state.output += prior.output + prev.output;
  2266. state.globstar = true;
  2267. consume(value + advance());
  2268. push({ type: 'slash', value: '/', output: '' });
  2269. continue;
  2270. }
  2271. if (prior.type === 'bos' && rest[0] === '/') {
  2272. prev.type = 'globstar';
  2273. prev.value += value;
  2274. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2275. state.output = prev.output;
  2276. state.globstar = true;
  2277. consume(value + advance());
  2278. push({ type: 'slash', value: '/', output: '' });
  2279. continue;
  2280. }
  2281. // remove single star from output
  2282. state.output = state.output.slice(0, -prev.output.length);
  2283. // reset previous token to globstar
  2284. prev.type = 'globstar';
  2285. prev.output = globstar(opts);
  2286. prev.value += value;
  2287. // reset output with globstar
  2288. state.output += prev.output;
  2289. state.globstar = true;
  2290. consume(value);
  2291. continue;
  2292. }
  2293. const token = { type: 'star', value, output: star };
  2294. if (opts.bash === true) {
  2295. token.output = '.*?';
  2296. if (prev.type === 'bos' || prev.type === 'slash') {
  2297. token.output = nodot + token.output;
  2298. }
  2299. push(token);
  2300. continue;
  2301. }
  2302. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2303. token.output = value;
  2304. push(token);
  2305. continue;
  2306. }
  2307. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2308. if (prev.type === 'dot') {
  2309. state.output += NO_DOT_SLASH;
  2310. prev.output += NO_DOT_SLASH;
  2311. } else if (opts.dot === true) {
  2312. state.output += NO_DOTS_SLASH;
  2313. prev.output += NO_DOTS_SLASH;
  2314. } else {
  2315. state.output += nodot;
  2316. prev.output += nodot;
  2317. }
  2318. if (peek() !== '*') {
  2319. state.output += ONE_CHAR;
  2320. prev.output += ONE_CHAR;
  2321. }
  2322. }
  2323. push(token);
  2324. }
  2325. while (state.brackets > 0) {
  2326. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  2327. state.output = utils$1.escapeLast(state.output, '[');
  2328. decrement('brackets');
  2329. }
  2330. while (state.parens > 0) {
  2331. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  2332. state.output = utils$1.escapeLast(state.output, '(');
  2333. decrement('parens');
  2334. }
  2335. while (state.braces > 0) {
  2336. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  2337. state.output = utils$1.escapeLast(state.output, '{');
  2338. decrement('braces');
  2339. }
  2340. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2341. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2342. }
  2343. // rebuild the output if we had to backtrack at any point
  2344. if (state.backtrack === true) {
  2345. state.output = '';
  2346. for (const token of state.tokens) {
  2347. state.output += token.output != null ? token.output : token.value;
  2348. if (token.suffix) {
  2349. state.output += token.suffix;
  2350. }
  2351. }
  2352. }
  2353. return state;
  2354. };
  2355. /**
  2356. * Fast paths for creating regular expressions for common glob patterns.
  2357. * This can significantly speed up processing and has very little downside
  2358. * impact when none of the fast paths match.
  2359. */
  2360. parse$2.fastpaths = (input, options) => {
  2361. const opts = { ...options };
  2362. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2363. const len = input.length;
  2364. if (len > max) {
  2365. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2366. }
  2367. input = REPLACEMENTS[input] || input;
  2368. const win32 = utils$1.isWindows(options);
  2369. // create constants based on platform, for windows or posix
  2370. const {
  2371. DOT_LITERAL,
  2372. SLASH_LITERAL,
  2373. ONE_CHAR,
  2374. DOTS_SLASH,
  2375. NO_DOT,
  2376. NO_DOTS,
  2377. NO_DOTS_SLASH,
  2378. STAR,
  2379. START_ANCHOR
  2380. } = constants$1.globChars(win32);
  2381. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  2382. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2383. const capture = opts.capture ? '' : '?:';
  2384. const state = { negated: false, prefix: '' };
  2385. let star = opts.bash === true ? '.*?' : STAR;
  2386. if (opts.capture) {
  2387. star = `(${star})`;
  2388. }
  2389. const globstar = opts => {
  2390. if (opts.noglobstar === true) return star;
  2391. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2392. };
  2393. const create = str => {
  2394. switch (str) {
  2395. case '*':
  2396. return `${nodot}${ONE_CHAR}${star}`;
  2397. case '.*':
  2398. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2399. case '*.*':
  2400. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2401. case '*/*':
  2402. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2403. case '**':
  2404. return nodot + globstar(opts);
  2405. case '**/*':
  2406. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2407. case '**/*.*':
  2408. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2409. case '**/.*':
  2410. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2411. default: {
  2412. const match = /^(.*?)\.(\w+)$/.exec(str);
  2413. if (!match) return;
  2414. const source = create(match[1]);
  2415. if (!source) return;
  2416. return source + DOT_LITERAL + match[2];
  2417. }
  2418. }
  2419. };
  2420. const output = utils$1.removePrefix(input, state);
  2421. let source = create(output);
  2422. if (source && opts.strictSlashes !== true) {
  2423. source += `${SLASH_LITERAL}?`;
  2424. }
  2425. return source;
  2426. };
  2427. var parse_1$1 = parse$2;
  2428. const path$1 = require$$0$1;
  2429. const scan = scan_1;
  2430. const parse$1 = parse_1$1;
  2431. const utils = utils$3;
  2432. const constants = constants$2;
  2433. const isObject$1 = val => val && typeof val === 'object' && !Array.isArray(val);
  2434. /**
  2435. * Creates a matcher function from one or more glob patterns. The
  2436. * returned function takes a string to match as its first argument,
  2437. * and returns true if the string is a match. The returned matcher
  2438. * function also takes a boolean as the second argument that, when true,
  2439. * returns an object with additional information.
  2440. *
  2441. * ```js
  2442. * const picomatch = require('picomatch');
  2443. * // picomatch(glob[, options]);
  2444. *
  2445. * const isMatch = picomatch('*.!(*a)');
  2446. * console.log(isMatch('a.a')); //=> false
  2447. * console.log(isMatch('a.b')); //=> true
  2448. * ```
  2449. * @name picomatch
  2450. * @param {String|Array} `globs` One or more glob patterns.
  2451. * @param {Object=} `options`
  2452. * @return {Function=} Returns a matcher function.
  2453. * @api public
  2454. */
  2455. const picomatch$1 = (glob, options, returnState = false) => {
  2456. if (Array.isArray(glob)) {
  2457. const fns = glob.map(input => picomatch$1(input, options, returnState));
  2458. const arrayMatcher = str => {
  2459. for (const isMatch of fns) {
  2460. const state = isMatch(str);
  2461. if (state) return state;
  2462. }
  2463. return false;
  2464. };
  2465. return arrayMatcher;
  2466. }
  2467. const isState = isObject$1(glob) && glob.tokens && glob.input;
  2468. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  2469. throw new TypeError('Expected pattern to be a non-empty string');
  2470. }
  2471. const opts = options || {};
  2472. const posix = utils.isWindows(options);
  2473. const regex = isState
  2474. ? picomatch$1.compileRe(glob, options)
  2475. : picomatch$1.makeRe(glob, options, false, true);
  2476. const state = regex.state;
  2477. delete regex.state;
  2478. let isIgnored = () => false;
  2479. if (opts.ignore) {
  2480. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  2481. isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
  2482. }
  2483. const matcher = (input, returnObject = false) => {
  2484. const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
  2485. const result = { glob, state, regex, posix, input, output, match, isMatch };
  2486. if (typeof opts.onResult === 'function') {
  2487. opts.onResult(result);
  2488. }
  2489. if (isMatch === false) {
  2490. result.isMatch = false;
  2491. return returnObject ? result : false;
  2492. }
  2493. if (isIgnored(input)) {
  2494. if (typeof opts.onIgnore === 'function') {
  2495. opts.onIgnore(result);
  2496. }
  2497. result.isMatch = false;
  2498. return returnObject ? result : false;
  2499. }
  2500. if (typeof opts.onMatch === 'function') {
  2501. opts.onMatch(result);
  2502. }
  2503. return returnObject ? result : true;
  2504. };
  2505. if (returnState) {
  2506. matcher.state = state;
  2507. }
  2508. return matcher;
  2509. };
  2510. /**
  2511. * Test `input` with the given `regex`. This is used by the main
  2512. * `picomatch()` function to test the input string.
  2513. *
  2514. * ```js
  2515. * const picomatch = require('picomatch');
  2516. * // picomatch.test(input, regex[, options]);
  2517. *
  2518. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  2519. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  2520. * ```
  2521. * @param {String} `input` String to test.
  2522. * @param {RegExp} `regex`
  2523. * @return {Object} Returns an object with matching info.
  2524. * @api public
  2525. */
  2526. picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
  2527. if (typeof input !== 'string') {
  2528. throw new TypeError('Expected input to be a string');
  2529. }
  2530. if (input === '') {
  2531. return { isMatch: false, output: '' };
  2532. }
  2533. const opts = options || {};
  2534. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  2535. let match = input === glob;
  2536. let output = (match && format) ? format(input) : input;
  2537. if (match === false) {
  2538. output = format ? format(input) : input;
  2539. match = output === glob;
  2540. }
  2541. if (match === false || opts.capture === true) {
  2542. if (opts.matchBase === true || opts.basename === true) {
  2543. match = picomatch$1.matchBase(input, regex, options, posix);
  2544. } else {
  2545. match = regex.exec(output);
  2546. }
  2547. }
  2548. return { isMatch: Boolean(match), match, output };
  2549. };
  2550. /**
  2551. * Match the basename of a filepath.
  2552. *
  2553. * ```js
  2554. * const picomatch = require('picomatch');
  2555. * // picomatch.matchBase(input, glob[, options]);
  2556. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  2557. * ```
  2558. * @param {String} `input` String to test.
  2559. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  2560. * @return {Boolean}
  2561. * @api public
  2562. */
  2563. picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  2564. const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
  2565. return regex.test(path$1.basename(input));
  2566. };
  2567. /**
  2568. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2569. *
  2570. * ```js
  2571. * const picomatch = require('picomatch');
  2572. * // picomatch.isMatch(string, patterns[, options]);
  2573. *
  2574. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2575. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  2576. * ```
  2577. * @param {String|Array} str The string to test.
  2578. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2579. * @param {Object} [options] See available [options](#options).
  2580. * @return {Boolean} Returns true if any patterns match `str`
  2581. * @api public
  2582. */
  2583. picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  2584. /**
  2585. * Parse a glob pattern to create the source string for a regular
  2586. * expression.
  2587. *
  2588. * ```js
  2589. * const picomatch = require('picomatch');
  2590. * const result = picomatch.parse(pattern[, options]);
  2591. * ```
  2592. * @param {String} `pattern`
  2593. * @param {Object} `options`
  2594. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  2595. * @api public
  2596. */
  2597. picomatch$1.parse = (pattern, options) => {
  2598. if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
  2599. return parse$1(pattern, { ...options, fastpaths: false });
  2600. };
  2601. /**
  2602. * Scan a glob pattern to separate the pattern into segments.
  2603. *
  2604. * ```js
  2605. * const picomatch = require('picomatch');
  2606. * // picomatch.scan(input[, options]);
  2607. *
  2608. * const result = picomatch.scan('!./foo/*.js');
  2609. * console.log(result);
  2610. * { prefix: '!./',
  2611. * input: '!./foo/*.js',
  2612. * start: 3,
  2613. * base: 'foo',
  2614. * glob: '*.js',
  2615. * isBrace: false,
  2616. * isBracket: false,
  2617. * isGlob: true,
  2618. * isExtglob: false,
  2619. * isGlobstar: false,
  2620. * negated: true }
  2621. * ```
  2622. * @param {String} `input` Glob pattern to scan.
  2623. * @param {Object} `options`
  2624. * @return {Object} Returns an object with
  2625. * @api public
  2626. */
  2627. picomatch$1.scan = (input, options) => scan(input, options);
  2628. /**
  2629. * Compile a regular expression from the `state` object returned by the
  2630. * [parse()](#parse) method.
  2631. *
  2632. * @param {Object} `state`
  2633. * @param {Object} `options`
  2634. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  2635. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  2636. * @return {RegExp}
  2637. * @api public
  2638. */
  2639. picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
  2640. if (returnOutput === true) {
  2641. return state.output;
  2642. }
  2643. const opts = options || {};
  2644. const prepend = opts.contains ? '' : '^';
  2645. const append = opts.contains ? '' : '$';
  2646. let source = `${prepend}(?:${state.output})${append}`;
  2647. if (state && state.negated === true) {
  2648. source = `^(?!${source}).*$`;
  2649. }
  2650. const regex = picomatch$1.toRegex(source, options);
  2651. if (returnState === true) {
  2652. regex.state = state;
  2653. }
  2654. return regex;
  2655. };
  2656. /**
  2657. * Create a regular expression from a parsed glob pattern.
  2658. *
  2659. * ```js
  2660. * const picomatch = require('picomatch');
  2661. * const state = picomatch.parse('*.js');
  2662. * // picomatch.compileRe(state[, options]);
  2663. *
  2664. * console.log(picomatch.compileRe(state));
  2665. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2666. * ```
  2667. * @param {String} `state` The object returned from the `.parse` method.
  2668. * @param {Object} `options`
  2669. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  2670. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  2671. * @return {RegExp} Returns a regex created from the given pattern.
  2672. * @api public
  2673. */
  2674. picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  2675. if (!input || typeof input !== 'string') {
  2676. throw new TypeError('Expected a non-empty string');
  2677. }
  2678. let parsed = { negated: false, fastpaths: true };
  2679. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2680. parsed.output = parse$1.fastpaths(input, options);
  2681. }
  2682. if (!parsed.output) {
  2683. parsed = parse$1(input, options);
  2684. }
  2685. return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
  2686. };
  2687. /**
  2688. * Create a regular expression from the given regex source string.
  2689. *
  2690. * ```js
  2691. * const picomatch = require('picomatch');
  2692. * // picomatch.toRegex(source[, options]);
  2693. *
  2694. * const { output } = picomatch.parse('*.js');
  2695. * console.log(picomatch.toRegex(output));
  2696. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2697. * ```
  2698. * @param {String} `source` Regular expression source string.
  2699. * @param {Object} `options`
  2700. * @return {RegExp}
  2701. * @api public
  2702. */
  2703. picomatch$1.toRegex = (source, options) => {
  2704. try {
  2705. const opts = options || {};
  2706. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2707. } catch (err) {
  2708. if (options && options.debug === true) throw err;
  2709. return /$^/;
  2710. }
  2711. };
  2712. /**
  2713. * Picomatch constants.
  2714. * @return {Object}
  2715. */
  2716. picomatch$1.constants = constants;
  2717. /**
  2718. * Expose "picomatch"
  2719. */
  2720. var picomatch_1 = picomatch$1;
  2721. var picomatch = picomatch_1;
  2722. var pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch);
  2723. // Helper since Typescript can't detect readonly arrays with Array.isArray
  2724. function isArray(arg) {
  2725. return Array.isArray(arg);
  2726. }
  2727. function ensureArray(thing) {
  2728. if (isArray(thing))
  2729. return thing;
  2730. if (thing == null)
  2731. return [];
  2732. return [thing];
  2733. }
  2734. const normalizePath$1 = function normalizePath(filename) {
  2735. return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep);
  2736. };
  2737. function getMatcherString(id, resolutionBase) {
  2738. if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('*')) {
  2739. return normalizePath$1(id);
  2740. }
  2741. // resolve('') is valid and will default to process.cwd()
  2742. const basePath = normalizePath$1(require$$0$1.resolve(resolutionBase || ''))
  2743. // escape all possible (posix + win) path characters that might interfere with regex
  2744. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  2745. // Note that we use posix.join because:
  2746. // 1. the basePath has been normalized to use /
  2747. // 2. the incoming glob (id) matcher, also uses /
  2748. // otherwise Node will force backslash (\) on windows
  2749. return require$$0$1.posix.join(basePath, normalizePath$1(id));
  2750. }
  2751. const createFilter$1 = function createFilter(include, exclude, options) {
  2752. const resolutionBase = options && options.resolve;
  2753. const getMatcher = (id) => id instanceof RegExp
  2754. ? id
  2755. : {
  2756. test: (what) => {
  2757. // this refactor is a tad overly verbose but makes for easy debugging
  2758. const pattern = getMatcherString(id, resolutionBase);
  2759. const fn = pm(pattern, { dot: true });
  2760. const result = fn(what);
  2761. return result;
  2762. }
  2763. };
  2764. const includeMatchers = ensureArray(include).map(getMatcher);
  2765. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  2766. return function result(id) {
  2767. if (typeof id !== 'string')
  2768. return false;
  2769. if (/\0/.test(id))
  2770. return false;
  2771. const pathId = normalizePath$1(id);
  2772. for (let i = 0; i < excludeMatchers.length; ++i) {
  2773. const matcher = excludeMatchers[i];
  2774. if (matcher.test(pathId))
  2775. return false;
  2776. }
  2777. for (let i = 0; i < includeMatchers.length; ++i) {
  2778. const matcher = includeMatchers[i];
  2779. if (matcher.test(pathId))
  2780. return true;
  2781. }
  2782. return !includeMatchers.length;
  2783. };
  2784. };
  2785. const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  2786. const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  2787. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins$1}`.split(' '));
  2788. forbiddenIdentifiers.add('');
  2789. if (process.versions.pnp) {
  2790. try {
  2791. node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))('pnpapi');
  2792. }
  2793. catch { }
  2794. }
  2795. const createFilter = createFilter$1;
  2796. const windowsSlashRE = /\\/g;
  2797. function slash(p) {
  2798. return p.replace(windowsSlashRE, '/');
  2799. }
  2800. //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
  2801. const builtins = new Set([
  2802. ...node_module.builtinModules,
  2803. 'assert/strict',
  2804. 'diagnostics_channel',
  2805. 'dns/promises',
  2806. 'fs/promises',
  2807. 'path/posix',
  2808. 'path/win32',
  2809. 'readline/promises',
  2810. 'stream/consumers',
  2811. 'stream/promises',
  2812. 'stream/web',
  2813. 'timers/promises',
  2814. 'util/types',
  2815. 'wasi',
  2816. ]);
  2817. // Some runtimes like Bun injects namespaced modules here, which is not a node builtin
  2818. [...builtins].filter((id) => !id.includes(':'));
  2819. function isInNodeModules(id) {
  2820. return id.includes('node_modules');
  2821. }
  2822. // TODO: use import()
  2823. const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)));
  2824. // set in bin/vite.js
  2825. const filter = process.env.VITE_DEBUG_FILTER;
  2826. const DEBUG = process.env.DEBUG;
  2827. function createDebugger(namespace, options = {}) {
  2828. const log = debug$1(namespace);
  2829. const { onlyWhenFocused } = options;
  2830. let enabled = log.enabled;
  2831. if (enabled && onlyWhenFocused) {
  2832. const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace;
  2833. enabled = !!DEBUG?.includes(ns);
  2834. }
  2835. if (enabled) {
  2836. return (...args) => {
  2837. if (!filter || args.some((a) => a?.includes?.(filter))) {
  2838. log(...args);
  2839. }
  2840. };
  2841. }
  2842. }
  2843. function testCaseInsensitiveFS() {
  2844. if (!CLIENT_ENTRY.endsWith('client.mjs')) {
  2845. throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`);
  2846. }
  2847. if (!fs$1.existsSync(CLIENT_ENTRY)) {
  2848. throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' +
  2849. CLIENT_ENTRY);
  2850. }
  2851. return fs$1.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'));
  2852. }
  2853. const isCaseInsensitiveFS = testCaseInsensitiveFS();
  2854. const isWindows = os$1.platform() === 'win32';
  2855. const VOLUME_RE = /^[A-Z]:/i;
  2856. function normalizePath(id) {
  2857. return path$3.posix.normalize(isWindows ? slash(id) : id);
  2858. }
  2859. function fsPathFromId(id) {
  2860. const fsPath = normalizePath(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
  2861. return fsPath[0] === '/' || fsPath.match(VOLUME_RE) ? fsPath : `/${fsPath}`;
  2862. }
  2863. function fsPathFromUrl(url) {
  2864. return fsPathFromId(cleanUrl(url));
  2865. }
  2866. function withTrailingSlash(path) {
  2867. if (path[path.length - 1] !== '/') {
  2868. return `${path}/`;
  2869. }
  2870. return path;
  2871. }
  2872. /**
  2873. * Check if dir is a parent of file
  2874. *
  2875. * Warning: parameters are not validated, only works with normalized absolute paths
  2876. *
  2877. * @param dir - normalized absolute path
  2878. * @param file - normalized absolute path
  2879. * @returns true if dir is a parent of file
  2880. */
  2881. function isParentDirectory(dir, file) {
  2882. dir = withTrailingSlash(dir);
  2883. return (file.startsWith(dir) ||
  2884. (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
  2885. }
  2886. /**
  2887. * Check if 2 file name are identical
  2888. *
  2889. * Warning: parameters are not validated, only works with normalized absolute paths
  2890. *
  2891. * @param file1 - normalized absolute path
  2892. * @param file2 - normalized absolute path
  2893. * @returns true if both files url are identical
  2894. */
  2895. function isSameFileUri(file1, file2) {
  2896. return (file1 === file2 ||
  2897. (isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase()));
  2898. }
  2899. const postfixRE = /[?#].*$/s;
  2900. function cleanUrl(url) {
  2901. return url.replace(postfixRE, '');
  2902. }
  2903. function isObject(value) {
  2904. return Object.prototype.toString.call(value) === '[object Object]';
  2905. }
  2906. function tryStatSync(file) {
  2907. try {
  2908. return fs$1.statSync(file, { throwIfNoEntry: false });
  2909. }
  2910. catch {
  2911. // Ignore errors
  2912. }
  2913. }
  2914. function isFileReadable(filename) {
  2915. try {
  2916. // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
  2917. if (!fs$1.statSync(filename, { throwIfNoEntry: false })) {
  2918. return false;
  2919. }
  2920. // Check if current process has read permission to the file
  2921. fs$1.accessSync(filename, fs$1.constants.R_OK);
  2922. return true;
  2923. }
  2924. catch {
  2925. return false;
  2926. }
  2927. }
  2928. function arraify(target) {
  2929. return Array.isArray(target) ? target : [target];
  2930. }
  2931. // @ts-expect-error jest only exists when running Jest
  2932. const usingDynamicImport = typeof jest === 'undefined';
  2933. /**
  2934. * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup.
  2935. *
  2936. * As a temporary workaround for Jest's lack of stable ESM support, we fallback to require
  2937. * if we're in a Jest environment.
  2938. * See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077
  2939. *
  2940. * @param file File path to import.
  2941. */
  2942. usingDynamicImport
  2943. ? new Function('file', 'return import(file)')
  2944. : _require;
  2945. path$3.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))));
  2946. function mergeConfigRecursively(defaults, overrides, rootPath) {
  2947. const merged = { ...defaults };
  2948. for (const key in overrides) {
  2949. const value = overrides[key];
  2950. if (value == null) {
  2951. continue;
  2952. }
  2953. const existing = merged[key];
  2954. if (existing == null) {
  2955. merged[key] = value;
  2956. continue;
  2957. }
  2958. // fields that require special handling
  2959. if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
  2960. merged[key] = mergeAlias(existing, value);
  2961. continue;
  2962. }
  2963. else if (key === 'assetsInclude' && rootPath === '') {
  2964. merged[key] = [].concat(existing, value);
  2965. continue;
  2966. }
  2967. else if (key === 'noExternal' &&
  2968. rootPath === 'ssr' &&
  2969. (existing === true || value === true)) {
  2970. merged[key] = true;
  2971. continue;
  2972. }
  2973. if (Array.isArray(existing) || Array.isArray(value)) {
  2974. merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])];
  2975. continue;
  2976. }
  2977. if (isObject(existing) && isObject(value)) {
  2978. merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
  2979. continue;
  2980. }
  2981. merged[key] = value;
  2982. }
  2983. return merged;
  2984. }
  2985. function mergeConfig(defaults, overrides, isRoot = true) {
  2986. if (typeof defaults === 'function' || typeof overrides === 'function') {
  2987. throw new Error(`Cannot merge config in form of callback`);
  2988. }
  2989. return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.');
  2990. }
  2991. function mergeAlias(a, b) {
  2992. if (!a)
  2993. return b;
  2994. if (!b)
  2995. return a;
  2996. if (isObject(a) && isObject(b)) {
  2997. return { ...a, ...b };
  2998. }
  2999. // the order is flipped because the alias is resolved from top-down,
  3000. // where the later should have higher priority
  3001. return [...normalizeAlias(b), ...normalizeAlias(a)];
  3002. }
  3003. function normalizeAlias(o = []) {
  3004. return Array.isArray(o)
  3005. ? o.map(normalizeSingleAlias)
  3006. : Object.keys(o).map((find) => normalizeSingleAlias({
  3007. find,
  3008. replacement: o[find],
  3009. }));
  3010. }
  3011. // https://github.com/vitejs/vite/issues/1363
  3012. // work around https://github.com/rollup/plugins/issues/759
  3013. function normalizeSingleAlias({ find, replacement, customResolver, }) {
  3014. if (typeof find === 'string' &&
  3015. find[find.length - 1] === '/' &&
  3016. replacement[replacement.length - 1] === '/') {
  3017. find = find.slice(0, find.length - 1);
  3018. replacement = replacement.slice(0, replacement.length - 1);
  3019. }
  3020. const alias = {
  3021. find,
  3022. replacement,
  3023. };
  3024. if (customResolver) {
  3025. alias.customResolver = customResolver;
  3026. }
  3027. return alias;
  3028. }
  3029. // This file will be built for both ESM and CJS. Avoid relying on other modules as possible.
  3030. // copy from constants.ts
  3031. const CSS_LANGS_RE =
  3032. // eslint-disable-next-line regexp/no-unused-capturing-group
  3033. /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
  3034. const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
  3035. // Use splitVendorChunkPlugin() to get the same manualChunks strategy as Vite 2.7
  3036. // We don't recommend using this strategy as a general solution moving forward
  3037. // splitVendorChunk is a simple index/vendor strategy that was used in Vite
  3038. // until v2.8. It is exposed to let people continue to use it in case it was
  3039. // working well for their setups.
  3040. // The cache needs to be reset on buildStart for watch mode to work correctly
  3041. // Don't use this manualChunks strategy for ssr, lib mode, and 'umd' or 'iife'
  3042. class SplitVendorChunkCache {
  3043. constructor() {
  3044. this.cache = new Map();
  3045. }
  3046. reset() {
  3047. this.cache = new Map();
  3048. }
  3049. }
  3050. function splitVendorChunk(options = {}) {
  3051. const cache = options.cache ?? new SplitVendorChunkCache();
  3052. return (id, { getModuleInfo }) => {
  3053. if (isInNodeModules(id) &&
  3054. !isCSSRequest(id) &&
  3055. staticImportedByEntry(id, getModuleInfo, cache.cache)) {
  3056. return 'vendor';
  3057. }
  3058. };
  3059. }
  3060. function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
  3061. if (cache.has(id)) {
  3062. return cache.get(id);
  3063. }
  3064. if (importStack.includes(id)) {
  3065. // circular deps!
  3066. cache.set(id, false);
  3067. return false;
  3068. }
  3069. const mod = getModuleInfo(id);
  3070. if (!mod) {
  3071. cache.set(id, false);
  3072. return false;
  3073. }
  3074. if (mod.isEntry) {
  3075. cache.set(id, true);
  3076. return true;
  3077. }
  3078. const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id)));
  3079. cache.set(id, someImporterIs);
  3080. return someImporterIs;
  3081. }
  3082. function splitVendorChunkPlugin() {
  3083. const caches = [];
  3084. function createSplitVendorChunk(output, config) {
  3085. const cache = new SplitVendorChunkCache();
  3086. caches.push(cache);
  3087. const build = config.build ?? {};
  3088. const format = output?.format;
  3089. if (!build.ssr && !build.lib && format !== 'umd' && format !== 'iife') {
  3090. return splitVendorChunk({ cache });
  3091. }
  3092. }
  3093. return {
  3094. name: 'vite:split-vendor-chunk',
  3095. config(config) {
  3096. let outputs = config?.build?.rollupOptions?.output;
  3097. if (outputs) {
  3098. outputs = Array.isArray(outputs) ? outputs : [outputs];
  3099. for (const output of outputs) {
  3100. const viteManualChunks = createSplitVendorChunk(output, config);
  3101. if (viteManualChunks) {
  3102. if (output.manualChunks) {
  3103. if (typeof output.manualChunks === 'function') {
  3104. const userManualChunks = output.manualChunks;
  3105. output.manualChunks = (id, api) => {
  3106. return userManualChunks(id, api) ?? viteManualChunks(id, api);
  3107. };
  3108. }
  3109. else {
  3110. // else, leave the object form of manualChunks untouched, as
  3111. // we can't safely replicate rollup handling.
  3112. // eslint-disable-next-line no-console
  3113. console.warn("(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead.");
  3114. }
  3115. }
  3116. else {
  3117. output.manualChunks = viteManualChunks;
  3118. }
  3119. }
  3120. }
  3121. }
  3122. else {
  3123. return {
  3124. build: {
  3125. rollupOptions: {
  3126. output: {
  3127. manualChunks: createSplitVendorChunk({}, config),
  3128. },
  3129. },
  3130. },
  3131. };
  3132. }
  3133. },
  3134. buildStart() {
  3135. caches.forEach((cache) => cache.reset());
  3136. },
  3137. };
  3138. }
  3139. /*!
  3140. * etag
  3141. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  3142. * MIT Licensed
  3143. */
  3144. /**
  3145. * Module exports.
  3146. * @public
  3147. */
  3148. var etag_1 = etag;
  3149. /**
  3150. * Module dependencies.
  3151. * @private
  3152. */
  3153. var crypto$1 = require$$0$2;
  3154. var Stats = fs$2.Stats;
  3155. /**
  3156. * Module variables.
  3157. * @private
  3158. */
  3159. var toString = Object.prototype.toString;
  3160. /**
  3161. * Generate an entity tag.
  3162. *
  3163. * @param {Buffer|string} entity
  3164. * @return {string}
  3165. * @private
  3166. */
  3167. function entitytag (entity) {
  3168. if (entity.length === 0) {
  3169. // fast-path empty
  3170. return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
  3171. }
  3172. // compute hash of entity
  3173. var hash = crypto$1
  3174. .createHash('sha1')
  3175. .update(entity, 'utf8')
  3176. .digest('base64')
  3177. .substring(0, 27);
  3178. // compute length of entity
  3179. var len = typeof entity === 'string'
  3180. ? Buffer.byteLength(entity, 'utf8')
  3181. : entity.length;
  3182. return '"' + len.toString(16) + '-' + hash + '"'
  3183. }
  3184. /**
  3185. * Create a simple ETag.
  3186. *
  3187. * @param {string|Buffer|Stats} entity
  3188. * @param {object} [options]
  3189. * @param {boolean} [options.weak]
  3190. * @return {String}
  3191. * @public
  3192. */
  3193. function etag (entity, options) {
  3194. if (entity == null) {
  3195. throw new TypeError('argument entity is required')
  3196. }
  3197. // support fs.Stats object
  3198. var isStats = isstats(entity);
  3199. var weak = options && typeof options.weak === 'boolean'
  3200. ? options.weak
  3201. : isStats;
  3202. // validate argument
  3203. if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
  3204. throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
  3205. }
  3206. // generate entity tag
  3207. var tag = isStats
  3208. ? stattag(entity)
  3209. : entitytag(entity);
  3210. return weak
  3211. ? 'W/' + tag
  3212. : tag
  3213. }
  3214. /**
  3215. * Determine if object is a Stats object.
  3216. *
  3217. * @param {object} obj
  3218. * @return {boolean}
  3219. * @api private
  3220. */
  3221. function isstats (obj) {
  3222. // genuine fs.Stats
  3223. if (typeof Stats === 'function' && obj instanceof Stats) {
  3224. return true
  3225. }
  3226. // quack quack
  3227. return obj && typeof obj === 'object' &&
  3228. 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&
  3229. 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&
  3230. 'ino' in obj && typeof obj.ino === 'number' &&
  3231. 'size' in obj && typeof obj.size === 'number'
  3232. }
  3233. /**
  3234. * Generate a tag for a stat.
  3235. *
  3236. * @param {object} stat
  3237. * @return {string}
  3238. * @private
  3239. */
  3240. function stattag (stat) {
  3241. var mtime = stat.mtime.getTime().toString(16);
  3242. var size = stat.size.toString(16);
  3243. return '"' + size + '-' + mtime + '"'
  3244. }
  3245. var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1);
  3246. const debug = createDebugger('vite:sourcemap', {
  3247. onlyWhenFocused: true,
  3248. });
  3249. function genSourceMapUrl(map) {
  3250. if (typeof map !== 'string') {
  3251. map = JSON.stringify(map);
  3252. }
  3253. return `data:application/json;base64,${Buffer.from(map).toString('base64')}`;
  3254. }
  3255. function getCodeWithSourcemap(type, code, map) {
  3256. if (debug) {
  3257. code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
  3258. }
  3259. if (type === 'js') {
  3260. code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
  3261. }
  3262. else if (type === 'css') {
  3263. code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
  3264. }
  3265. return code;
  3266. }
  3267. const alias = {
  3268. js: 'application/javascript',
  3269. css: 'text/css',
  3270. html: 'text/html',
  3271. json: 'application/json',
  3272. };
  3273. function send(req, res, content, type, options) {
  3274. const { etag = getEtag(content, { weak: true }), cacheControl = 'no-cache', headers, map, } = options;
  3275. if (res.writableEnded) {
  3276. return;
  3277. }
  3278. if (req.headers['if-none-match'] === etag) {
  3279. res.statusCode = 304;
  3280. res.end();
  3281. return;
  3282. }
  3283. res.setHeader('Content-Type', alias[type] || type);
  3284. res.setHeader('Cache-Control', cacheControl);
  3285. res.setHeader('Etag', etag);
  3286. if (headers) {
  3287. for (const name in headers) {
  3288. res.setHeader(name, headers[name]);
  3289. }
  3290. }
  3291. // inject source map reference
  3292. if (map && map.mappings) {
  3293. if (type === 'js' || type === 'css') {
  3294. content = getCodeWithSourcemap(type, content.toString(), map);
  3295. }
  3296. }
  3297. res.statusCode = 200;
  3298. res.end(content);
  3299. return;
  3300. }
  3301. /* eslint no-console: 0 */
  3302. const LogLevels = {
  3303. silent: 0,
  3304. error: 1,
  3305. warn: 2,
  3306. info: 3,
  3307. };
  3308. let lastType;
  3309. let lastMsg;
  3310. let sameCount = 0;
  3311. function clearScreen() {
  3312. const repeatCount = process.stdout.rows - 2;
  3313. const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : '';
  3314. console.log(blank);
  3315. readline.cursorTo(process.stdout, 0, 0);
  3316. readline.clearScreenDown(process.stdout);
  3317. }
  3318. function createLogger(level = 'info', options = {}) {
  3319. if (options.customLogger) {
  3320. return options.customLogger;
  3321. }
  3322. const timeFormatter = new Intl.DateTimeFormat(undefined, {
  3323. hour: 'numeric',
  3324. minute: 'numeric',
  3325. second: 'numeric',
  3326. });
  3327. const loggedErrors = new WeakSet();
  3328. const { prefix = '[vite]', allowClearScreen = true } = options;
  3329. const thresh = LogLevels[level];
  3330. const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  3331. const clear = canClearScreen ? clearScreen : () => { };
  3332. function output(type, msg, options = {}) {
  3333. if (thresh >= LogLevels[type]) {
  3334. const method = type === 'info' ? 'log' : type;
  3335. const format = () => {
  3336. if (options.timestamp) {
  3337. const tag = type === 'info'
  3338. ? colors.cyan(colors.bold(prefix))
  3339. : type === 'warn'
  3340. ? colors.yellow(colors.bold(prefix))
  3341. : colors.red(colors.bold(prefix));
  3342. return `${colors.dim(timeFormatter.format(new Date()))} ${tag} ${msg}`;
  3343. }
  3344. else {
  3345. return msg;
  3346. }
  3347. };
  3348. if (options.error) {
  3349. loggedErrors.add(options.error);
  3350. }
  3351. if (canClearScreen) {
  3352. if (type === lastType && msg === lastMsg) {
  3353. sameCount++;
  3354. clear();
  3355. console[method](format(), colors.yellow(`(x${sameCount + 1})`));
  3356. }
  3357. else {
  3358. sameCount = 0;
  3359. lastMsg = msg;
  3360. lastType = type;
  3361. if (options.clear) {
  3362. clear();
  3363. }
  3364. console[method](format());
  3365. }
  3366. }
  3367. else {
  3368. console[method](format());
  3369. }
  3370. }
  3371. }
  3372. const warnedMessages = new Set();
  3373. const logger = {
  3374. hasWarned: false,
  3375. info(msg, opts) {
  3376. output('info', msg, opts);
  3377. },
  3378. warn(msg, opts) {
  3379. logger.hasWarned = true;
  3380. output('warn', msg, opts);
  3381. },
  3382. warnOnce(msg, opts) {
  3383. if (warnedMessages.has(msg))
  3384. return;
  3385. logger.hasWarned = true;
  3386. output('warn', msg, opts);
  3387. warnedMessages.add(msg);
  3388. },
  3389. error(msg, opts) {
  3390. logger.hasWarned = true;
  3391. output('error', msg, opts);
  3392. },
  3393. clearScreen(type) {
  3394. if (thresh >= LogLevels[type]) {
  3395. clear();
  3396. }
  3397. },
  3398. hasErrorLogged(error) {
  3399. return loggedErrors.has(error);
  3400. },
  3401. };
  3402. return logger;
  3403. }
  3404. // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
  3405. const ROOT_FILES = [
  3406. // '.git',
  3407. // https://pnpm.io/workspaces/
  3408. 'pnpm-workspace.yaml',
  3409. // https://rushjs.io/pages/advanced/config_files/
  3410. // 'rush.json',
  3411. // https://nx.dev/latest/react/getting-started/nx-setup
  3412. // 'workspace.json',
  3413. // 'nx.json',
  3414. // https://github.com/lerna/lerna#lernajson
  3415. 'lerna.json',
  3416. ];
  3417. // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
  3418. // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
  3419. function hasWorkspacePackageJSON(root) {
  3420. const path = path$3.join(root, 'package.json');
  3421. if (!isFileReadable(path)) {
  3422. return false;
  3423. }
  3424. try {
  3425. const content = JSON.parse(fs$1.readFileSync(path, 'utf-8')) || {};
  3426. return !!content.workspaces;
  3427. }
  3428. catch {
  3429. return false;
  3430. }
  3431. }
  3432. function hasRootFile(root) {
  3433. return ROOT_FILES.some((file) => fs$1.existsSync(path$3.join(root, file)));
  3434. }
  3435. function hasPackageJSON(root) {
  3436. const path = path$3.join(root, 'package.json');
  3437. return fs$1.existsSync(path);
  3438. }
  3439. /**
  3440. * Search up for the nearest `package.json`
  3441. */
  3442. function searchForPackageRoot(current, root = current) {
  3443. if (hasPackageJSON(current))
  3444. return current;
  3445. const dir = path$3.dirname(current);
  3446. // reach the fs root
  3447. if (!dir || dir === current)
  3448. return root;
  3449. return searchForPackageRoot(dir, root);
  3450. }
  3451. /**
  3452. * Search up for the nearest workspace root
  3453. */
  3454. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  3455. if (hasRootFile(current))
  3456. return current;
  3457. if (hasWorkspacePackageJSON(current))
  3458. return current;
  3459. const dir = path$3.dirname(current);
  3460. // reach the fs root
  3461. if (!dir || dir === current)
  3462. return root;
  3463. return searchForWorkspaceRoot(dir, root);
  3464. }
  3465. /**
  3466. * Check if the url is allowed to be served, via the `server.fs` config.
  3467. * @deprecated Use the `isFileLoadingAllowed` function instead.
  3468. */
  3469. function isFileServingAllowed(url, server) {
  3470. if (!server.config.server.fs.strict)
  3471. return true;
  3472. const filePath = fsPathFromUrl(url);
  3473. return isFileLoadingAllowed(server, filePath);
  3474. }
  3475. function isUriInFilePath(uri, filePath) {
  3476. return isSameFileUri(uri, filePath) || isParentDirectory(uri, filePath);
  3477. }
  3478. function isFileLoadingAllowed(server, filePath) {
  3479. const { fs } = server.config.server;
  3480. if (!fs.strict)
  3481. return true;
  3482. if (server._fsDenyGlob(filePath))
  3483. return false;
  3484. if (server.moduleGraph.safeModulesPath.has(filePath))
  3485. return true;
  3486. if (fs.allow.some((uri) => isUriInFilePath(uri, filePath)))
  3487. return true;
  3488. return false;
  3489. }
  3490. var main$1 = {exports: {}};
  3491. var name = "dotenv";
  3492. var version$1 = "16.3.1";
  3493. var description = "Loads environment variables from .env file";
  3494. var main = "lib/main.js";
  3495. var types = "lib/main.d.ts";
  3496. var exports$1 = {
  3497. ".": {
  3498. types: "./lib/main.d.ts",
  3499. require: "./lib/main.js",
  3500. "default": "./lib/main.js"
  3501. },
  3502. "./config": "./config.js",
  3503. "./config.js": "./config.js",
  3504. "./lib/env-options": "./lib/env-options.js",
  3505. "./lib/env-options.js": "./lib/env-options.js",
  3506. "./lib/cli-options": "./lib/cli-options.js",
  3507. "./lib/cli-options.js": "./lib/cli-options.js",
  3508. "./package.json": "./package.json"
  3509. };
  3510. var scripts = {
  3511. "dts-check": "tsc --project tests/types/tsconfig.json",
  3512. lint: "standard",
  3513. "lint-readme": "standard-markdown",
  3514. pretest: "npm run lint && npm run dts-check",
  3515. test: "tap tests/*.js --100 -Rspec",
  3516. prerelease: "npm test",
  3517. release: "standard-version"
  3518. };
  3519. var repository = {
  3520. type: "git",
  3521. url: "git://github.com/motdotla/dotenv.git"
  3522. };
  3523. var funding = "https://github.com/motdotla/dotenv?sponsor=1";
  3524. var keywords = [
  3525. "dotenv",
  3526. "env",
  3527. ".env",
  3528. "environment",
  3529. "variables",
  3530. "config",
  3531. "settings"
  3532. ];
  3533. var readmeFilename = "README.md";
  3534. var license = "BSD-2-Clause";
  3535. var devDependencies = {
  3536. "@definitelytyped/dtslint": "^0.0.133",
  3537. "@types/node": "^18.11.3",
  3538. decache: "^4.6.1",
  3539. sinon: "^14.0.1",
  3540. standard: "^17.0.0",
  3541. "standard-markdown": "^7.1.0",
  3542. "standard-version": "^9.5.0",
  3543. tap: "^16.3.0",
  3544. tar: "^6.1.11",
  3545. typescript: "^4.8.4"
  3546. };
  3547. var engines = {
  3548. node: ">=12"
  3549. };
  3550. var browser = {
  3551. fs: false
  3552. };
  3553. var require$$4 = {
  3554. name: name,
  3555. version: version$1,
  3556. description: description,
  3557. main: main,
  3558. types: types,
  3559. exports: exports$1,
  3560. scripts: scripts,
  3561. repository: repository,
  3562. funding: funding,
  3563. keywords: keywords,
  3564. readmeFilename: readmeFilename,
  3565. license: license,
  3566. devDependencies: devDependencies,
  3567. engines: engines,
  3568. browser: browser
  3569. };
  3570. const fs = fs$2;
  3571. const path = require$$0$1;
  3572. const os = require$$2;
  3573. const crypto = require$$0$2;
  3574. const packageJson = require$$4;
  3575. const version = packageJson.version;
  3576. const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
  3577. // Parse src into an Object
  3578. function parse (src) {
  3579. const obj = {};
  3580. // Convert buffer to string
  3581. let lines = src.toString();
  3582. // Convert line breaks to same format
  3583. lines = lines.replace(/\r\n?/mg, '\n');
  3584. let match;
  3585. while ((match = LINE.exec(lines)) != null) {
  3586. const key = match[1];
  3587. // Default undefined or null to empty string
  3588. let value = (match[2] || '');
  3589. // Remove whitespace
  3590. value = value.trim();
  3591. // Check if double quoted
  3592. const maybeQuote = value[0];
  3593. // Remove surrounding quotes
  3594. value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2');
  3595. // Expand newlines if double quoted
  3596. if (maybeQuote === '"') {
  3597. value = value.replace(/\\n/g, '\n');
  3598. value = value.replace(/\\r/g, '\r');
  3599. }
  3600. // Add to object
  3601. obj[key] = value;
  3602. }
  3603. return obj
  3604. }
  3605. function _parseVault (options) {
  3606. const vaultPath = _vaultPath(options);
  3607. // Parse .env.vault
  3608. const result = DotenvModule.configDotenv({ path: vaultPath });
  3609. if (!result.parsed) {
  3610. throw new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)
  3611. }
  3612. // handle scenario for comma separated keys - for use with key rotation
  3613. // example: DOTENV_KEY="dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenv.org/vault/.env.vault?environment=prod"
  3614. const keys = _dotenvKey(options).split(',');
  3615. const length = keys.length;
  3616. let decrypted;
  3617. for (let i = 0; i < length; i++) {
  3618. try {
  3619. // Get full key
  3620. const key = keys[i].trim();
  3621. // Get instructions for decrypt
  3622. const attrs = _instructions(result, key);
  3623. // Decrypt
  3624. decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
  3625. break
  3626. } catch (error) {
  3627. // last key
  3628. if (i + 1 >= length) {
  3629. throw error
  3630. }
  3631. // try next key
  3632. }
  3633. }
  3634. // Parse decrypted .env string
  3635. return DotenvModule.parse(decrypted)
  3636. }
  3637. function _log (message) {
  3638. console.log(`[dotenv@${version}][INFO] ${message}`);
  3639. }
  3640. function _warn (message) {
  3641. console.log(`[dotenv@${version}][WARN] ${message}`);
  3642. }
  3643. function _debug (message) {
  3644. console.log(`[dotenv@${version}][DEBUG] ${message}`);
  3645. }
  3646. function _dotenvKey (options) {
  3647. // prioritize developer directly setting options.DOTENV_KEY
  3648. if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
  3649. return options.DOTENV_KEY
  3650. }
  3651. // secondary infra already contains a DOTENV_KEY environment variable
  3652. if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
  3653. return process.env.DOTENV_KEY
  3654. }
  3655. // fallback to empty string
  3656. return ''
  3657. }
  3658. function _instructions (result, dotenvKey) {
  3659. // Parse DOTENV_KEY. Format is a URI
  3660. let uri;
  3661. try {
  3662. uri = new URL(dotenvKey);
  3663. } catch (error) {
  3664. if (error.code === 'ERR_INVALID_URL') {
  3665. throw new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development')
  3666. }
  3667. throw error
  3668. }
  3669. // Get decrypt key
  3670. const key = uri.password;
  3671. if (!key) {
  3672. throw new Error('INVALID_DOTENV_KEY: Missing key part')
  3673. }
  3674. // Get environment
  3675. const environment = uri.searchParams.get('environment');
  3676. if (!environment) {
  3677. throw new Error('INVALID_DOTENV_KEY: Missing environment part')
  3678. }
  3679. // Get ciphertext payload
  3680. const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
  3681. const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION
  3682. if (!ciphertext) {
  3683. throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)
  3684. }
  3685. return { ciphertext, key }
  3686. }
  3687. function _vaultPath (options) {
  3688. let dotenvPath = path.resolve(process.cwd(), '.env');
  3689. if (options && options.path && options.path.length > 0) {
  3690. dotenvPath = options.path;
  3691. }
  3692. // Locate .env.vault
  3693. return dotenvPath.endsWith('.vault') ? dotenvPath : `${dotenvPath}.vault`
  3694. }
  3695. function _resolveHome (envPath) {
  3696. return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
  3697. }
  3698. function _configVault (options) {
  3699. _log('Loading env from encrypted .env.vault');
  3700. const parsed = DotenvModule._parseVault(options);
  3701. let processEnv = process.env;
  3702. if (options && options.processEnv != null) {
  3703. processEnv = options.processEnv;
  3704. }
  3705. DotenvModule.populate(processEnv, parsed, options);
  3706. return { parsed }
  3707. }
  3708. function configDotenv (options) {
  3709. let dotenvPath = path.resolve(process.cwd(), '.env');
  3710. let encoding = 'utf8';
  3711. const debug = Boolean(options && options.debug);
  3712. if (options) {
  3713. if (options.path != null) {
  3714. dotenvPath = _resolveHome(options.path);
  3715. }
  3716. if (options.encoding != null) {
  3717. encoding = options.encoding;
  3718. }
  3719. }
  3720. try {
  3721. // Specifying an encoding returns a string instead of a buffer
  3722. const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, { encoding }));
  3723. let processEnv = process.env;
  3724. if (options && options.processEnv != null) {
  3725. processEnv = options.processEnv;
  3726. }
  3727. DotenvModule.populate(processEnv, parsed, options);
  3728. return { parsed }
  3729. } catch (e) {
  3730. if (debug) {
  3731. _debug(`Failed to load ${dotenvPath} ${e.message}`);
  3732. }
  3733. return { error: e }
  3734. }
  3735. }
  3736. // Populates process.env from .env file
  3737. function config (options) {
  3738. const vaultPath = _vaultPath(options);
  3739. // fallback to original dotenv if DOTENV_KEY is not set
  3740. if (_dotenvKey(options).length === 0) {
  3741. return DotenvModule.configDotenv(options)
  3742. }
  3743. // dotenvKey exists but .env.vault file does not exist
  3744. if (!fs.existsSync(vaultPath)) {
  3745. _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
  3746. return DotenvModule.configDotenv(options)
  3747. }
  3748. return DotenvModule._configVault(options)
  3749. }
  3750. function decrypt (encrypted, keyStr) {
  3751. const key = Buffer.from(keyStr.slice(-64), 'hex');
  3752. let ciphertext = Buffer.from(encrypted, 'base64');
  3753. const nonce = ciphertext.slice(0, 12);
  3754. const authTag = ciphertext.slice(-16);
  3755. ciphertext = ciphertext.slice(12, -16);
  3756. try {
  3757. const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce);
  3758. aesgcm.setAuthTag(authTag);
  3759. return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
  3760. } catch (error) {
  3761. const isRange = error instanceof RangeError;
  3762. const invalidKeyLength = error.message === 'Invalid key length';
  3763. const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data';
  3764. if (isRange || invalidKeyLength) {
  3765. const msg = 'INVALID_DOTENV_KEY: It must be 64 characters long (or more)';
  3766. throw new Error(msg)
  3767. } else if (decryptionFailed) {
  3768. const msg = 'DECRYPTION_FAILED: Please check your DOTENV_KEY';
  3769. throw new Error(msg)
  3770. } else {
  3771. console.error('Error: ', error.code);
  3772. console.error('Error: ', error.message);
  3773. throw error
  3774. }
  3775. }
  3776. }
  3777. // Populate process.env with parsed values
  3778. function populate (processEnv, parsed, options = {}) {
  3779. const debug = Boolean(options && options.debug);
  3780. const override = Boolean(options && options.override);
  3781. if (typeof parsed !== 'object') {
  3782. throw new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')
  3783. }
  3784. // Set process.env
  3785. for (const key of Object.keys(parsed)) {
  3786. if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
  3787. if (override === true) {
  3788. processEnv[key] = parsed[key];
  3789. }
  3790. if (debug) {
  3791. if (override === true) {
  3792. _debug(`"${key}" is already defined and WAS overwritten`);
  3793. } else {
  3794. _debug(`"${key}" is already defined and was NOT overwritten`);
  3795. }
  3796. }
  3797. } else {
  3798. processEnv[key] = parsed[key];
  3799. }
  3800. }
  3801. }
  3802. const DotenvModule = {
  3803. configDotenv,
  3804. _configVault,
  3805. _parseVault,
  3806. config,
  3807. decrypt,
  3808. parse,
  3809. populate
  3810. };
  3811. main$1.exports.configDotenv = DotenvModule.configDotenv;
  3812. main$1.exports._configVault = DotenvModule._configVault;
  3813. main$1.exports._parseVault = DotenvModule._parseVault;
  3814. main$1.exports.config = DotenvModule.config;
  3815. main$1.exports.decrypt = DotenvModule.decrypt;
  3816. var parse_1 = main$1.exports.parse = DotenvModule.parse;
  3817. main$1.exports.populate = DotenvModule.populate;
  3818. main$1.exports = DotenvModule;
  3819. function _interpolate (envValue, environment, config) {
  3820. const matches = envValue.match(/(.?\${*[\w]*(?::-[\w/]*)?}*)/g) || [];
  3821. return matches.reduce(function (newEnv, match, index) {
  3822. const parts = /(.?)\${*([\w]*(?::-[\w/]*)?)?}*/g.exec(match);
  3823. if (!parts || parts.length === 0) {
  3824. return newEnv
  3825. }
  3826. const prefix = parts[1];
  3827. let value, replacePart;
  3828. if (prefix === '\\') {
  3829. replacePart = parts[0];
  3830. value = replacePart.replace('\\$', '$');
  3831. } else {
  3832. // PATCH: compatible with env variables ended with unescaped $
  3833. if(!parts[2]) {
  3834. return newEnv
  3835. }
  3836. const keyParts = parts[2].split(':-');
  3837. const key = keyParts[0];
  3838. replacePart = parts[0].substring(prefix.length);
  3839. // process.env value 'wins' over .env file's value
  3840. value = Object.prototype.hasOwnProperty.call(environment, key)
  3841. ? environment[key]
  3842. : (config.parsed[key] || keyParts[1] || '');
  3843. // If the value is found, remove nested expansions.
  3844. if (keyParts.length > 1 && value) {
  3845. const replaceNested = matches[index + 1];
  3846. matches[index + 1] = '';
  3847. newEnv = newEnv.replace(replaceNested, '');
  3848. }
  3849. // Resolve recursive interpolations
  3850. value = _interpolate(value, environment, config);
  3851. }
  3852. return newEnv.replace(replacePart, value)
  3853. }, envValue)
  3854. }
  3855. function expand (config) {
  3856. // if ignoring process.env, use a blank object
  3857. const environment = config.ignoreProcessEnv ? {} : process.env;
  3858. for (const configKey in config.parsed) {
  3859. const value = Object.prototype.hasOwnProperty.call(environment, configKey) ? environment[configKey] : config.parsed[configKey];
  3860. config.parsed[configKey] = _interpolate(value, environment, config);
  3861. }
  3862. // PATCH: don't write to process.env
  3863. // for (const processKey in config.parsed) {
  3864. // environment[processKey] = config.parsed[processKey]
  3865. // }
  3866. return config
  3867. }
  3868. var expand_1 = expand;
  3869. function loadEnv(mode, envDir, prefixes = 'VITE_') {
  3870. if (mode === 'local') {
  3871. throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
  3872. `the .local postfix for .env files.`);
  3873. }
  3874. prefixes = arraify(prefixes);
  3875. const env = {};
  3876. const envFiles = [
  3877. /** default file */ `.env`,
  3878. /** local file */ `.env.local`,
  3879. /** mode file */ `.env.${mode}`,
  3880. /** mode local file */ `.env.${mode}.local`,
  3881. ];
  3882. const parsed = Object.fromEntries(envFiles.flatMap((file) => {
  3883. const filePath = path$3.join(envDir, file);
  3884. if (!tryStatSync(filePath)?.isFile())
  3885. return [];
  3886. return Object.entries(parse_1(fs$1.readFileSync(filePath)));
  3887. }));
  3888. // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this
  3889. if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {
  3890. process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
  3891. }
  3892. // support BROWSER and BROWSER_ARGS env variables
  3893. if (parsed.BROWSER && process.env.BROWSER === undefined) {
  3894. process.env.BROWSER = parsed.BROWSER;
  3895. }
  3896. if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) {
  3897. process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
  3898. }
  3899. // let environment variables use each other
  3900. // `expand` patched in patches/dotenv-expand@9.0.0.patch
  3901. expand_1({ parsed });
  3902. // only keys that start with prefix are exposed to client
  3903. for (const [key, value] of Object.entries(parsed)) {
  3904. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  3905. env[key] = value;
  3906. }
  3907. }
  3908. // check if there are actual env variables starting with VITE_*
  3909. // these are typically provided inline and should be prioritized
  3910. for (const key in process.env) {
  3911. if (prefixes.some((prefix) => key.startsWith(prefix))) {
  3912. env[key] = process.env[key];
  3913. }
  3914. }
  3915. return env;
  3916. }
  3917. function resolveEnvPrefix({ envPrefix = 'VITE_', }) {
  3918. envPrefix = arraify(envPrefix);
  3919. if (envPrefix.some((prefix) => prefix === '')) {
  3920. throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
  3921. }
  3922. return envPrefix;
  3923. }
  3924. exports.esbuildVersion = esbuild.version;
  3925. exports.rollupVersion = rollup.VERSION;
  3926. exports.createFilter = createFilter;
  3927. exports.createLogger = createLogger;
  3928. exports.isCSSRequest = isCSSRequest;
  3929. exports.isFileLoadingAllowed = isFileLoadingAllowed;
  3930. exports.isFileServingAllowed = isFileServingAllowed;
  3931. exports.loadEnv = loadEnv;
  3932. exports.mergeAlias = mergeAlias;
  3933. exports.mergeConfig = mergeConfig;
  3934. exports.normalizePath = normalizePath;
  3935. exports.resolveEnvPrefix = resolveEnvPrefix;
  3936. exports.searchForWorkspaceRoot = searchForWorkspaceRoot;
  3937. exports.send = send;
  3938. exports.splitVendorChunk = splitVendorChunk;
  3939. exports.splitVendorChunkPlugin = splitVendorChunkPlugin;
  3940. exports.version = VERSION;